Example usage for io.netty.buffer ByteBuf getBytes

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

Introduction

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

Prototype

public abstract ByteBuf getBytes(int index, ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the specified absolute index until the destination's position reaches its limit.

Usage

From source file:org.onosproject.ovsdb.rfc.utils.JsonRpcReaderUtil.java

License:Apache License

/**
 * Check whether the encoding is valid.//from ww  w.jav  a  2s.c om
 * @param in input of bytes
 * @throws IOException this is an IO exception
 * @throws UnsupportedException this is an unsupported exception
 */
private static void checkEncoding(ByteBuf in) throws IOException {
    int inputStart = 0;
    int inputLength = 4;
    fliterCharaters(in);
    byte[] buff = new byte[4];
    in.getBytes(in.readerIndex(), buff);
    ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(
            new IOContext(new BufferRecycler(), null, false), buff, inputStart, inputLength);
    JsonEncoding jsonEncoding = strapper.detectEncoding();
    if (!JsonEncoding.UTF8.equals(jsonEncoding)) {
        throw new UnsupportedException("Only UTF-8 encoding is supported.");
    }
}

From source file:org.opendaylight.controller.netconf.impl.MessageParserTest.java

License:Open Source License

@Test
public void testChunkedFramingMechanismOnPipeline() throws Exception {
    EmbeddedChannel testChunkChannel = new EmbeddedChannel(
            FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK),
            new NetconfMessageToXMLEncoder(),

            new NetconfChunkAggregator(), new NetconfXMLToMessageDecoder());

    testChunkChannel.writeOutbound(this.msg);
    Queue<Object> messages = testChunkChannel.outboundMessages();
    assertFalse(messages.isEmpty());//from ww w . j  ava  2 s.  co m

    final NetconfMessageToXMLEncoder enc = new NetconfMessageToXMLEncoder();
    final ByteBuf out = Unpooled.buffer();
    enc.encode(null, msg, out);
    int msgLength = out.readableBytes();

    int chunkCount = msgLength / ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
    if ((msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE) != 0) {
        chunkCount++;
    }
    for (int i = 1; i <= chunkCount; i++) {
        ByteBuf recievedOutbound = (ByteBuf) messages.poll();
        int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
        if (i == chunkCount) {
            exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
            byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
            recievedOutbound.getBytes(
                    recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
            assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
        }

        byte[] header = new byte[String.valueOf(exptHeaderLength).length()
                + NetconfMessageConstants.MIN_HEADER_LENGTH - 1];
        recievedOutbound.getBytes(0, header);
        NetconfMessageHeader messageHeader = NetconfMessageHeader.fromBytes(header);
        assertEquals(exptHeaderLength, messageHeader.getLength());

        testChunkChannel.writeInbound(recievedOutbound);
    }
    assertTrue(messages.isEmpty());

    NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
    assertNotNull(receivedMessage);
    assertXMLEqual(this.msg.getDocument(), receivedMessage.getDocument());
}

From source file:org.opendaylight.controller.netconf.impl.MessageParserTest.java

License:Open Source License

@Test
public void testEOMFramingMechanismOnPipeline() throws Exception {
    EmbeddedChannel testChunkChannel = new EmbeddedChannel(
            FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM),
            new NetconfMessageToXMLEncoder(), new NetconfEOMAggregator(), new NetconfXMLToMessageDecoder());

    testChunkChannel.writeOutbound(this.msg);
    ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();

    byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length];
    recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length,
            eom);//from   ww w  .j  a v a  2 s  . com
    assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom);

    testChunkChannel.writeInbound(recievedOutbound);
    NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
    assertNotNull(receivedMessage);
    assertXMLEqual(this.msg.getDocument(), receivedMessage.getDocument());
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.JsonRpcDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {

    logger.trace("readable bytes {}, records read {}, incomplete record bytes {}", buf.readableBytes(),
            recordsRead, lastRecordBytes);

    if (lastRecordBytes == 0) {
        if (buf.readableBytes() < 4) {
            return; //wait for more data
        }/*from  w ww.j  a va 2  s. c om*/

        skipSpaces(buf);

        byte[] buff = new byte[4];
        buf.getBytes(buf.readerIndex(), buff);
        ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(jacksonIOContext, buff, 0, 4);
        JsonEncoding jsonEncoding = strapper.detectEncoding();
        if (!JsonEncoding.UTF8.equals(jsonEncoding)) {
            throw new InvalidEncodingException(jsonEncoding.getJavaName(), "currently only UTF-8 is supported");
        }
    }

    int i = lastRecordBytes + buf.readerIndex();

    for (; i < buf.writerIndex(); i++) {
        switch (buf.getByte(i)) {
        case '{':
            if (!inS)
                leftCurlies++;
            break;
        case '}':
            if (!inS)
                rightCurlies++;
            break;
        case '"': {
            if (buf.getByte(i - 1) != '\\')
                inS = !inS;
            break;
        }
        default:
            break;
        }

        if (leftCurlies != 0 && leftCurlies == rightCurlies && !inS) {
            ByteBuf slice = buf.readSlice(1 + i - buf.readerIndex());
            JsonParser jp = jacksonJsonFactory.createParser(new ByteBufInputStream(slice));
            JsonNode root = jp.readValueAsTree();
            out.add(root);
            leftCurlies = rightCurlies = lastRecordBytes = 0;
            recordsRead++;
            break;
        }

        if (i - buf.readerIndex() >= maxFrameLength) {
            fail(ctx, i - buf.readerIndex());
        }
    }

    // end of stream, save the incomplete record index to avoid reexamining the whole on next run
    if (i >= buf.writerIndex()) {
        lastRecordBytes = buf.readableBytes();
        return;
    }
}

From source file:org.opendaylight.netconf.impl.MessageParserTest.java

License:Open Source License

@Test
public void testChunkedFramingMechanismOnPipeline() throws Exception {
    EmbeddedChannel testChunkChannel = new EmbeddedChannel(
            FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK),
            new NetconfMessageToXMLEncoder(),

            new NetconfChunkAggregator(), new NetconfXMLToMessageDecoder());

    testChunkChannel.writeOutbound(this.msg);
    Queue<Object> messages = testChunkChannel.outboundMessages();
    assertFalse(messages.isEmpty());//w  w w.j  a v  a  2  s  . c o m

    final NetconfMessageToXMLEncoder enc = new NetconfMessageToXMLEncoder();
    final ByteBuf out = Unpooled.buffer();
    enc.encode(null, msg, out);
    int msgLength = out.readableBytes();

    int chunkCount = msgLength / ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
    if ((msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE) != 0) {
        chunkCount++;
    }
    for (int i = 1; i <= chunkCount; i++) {
        ByteBuf recievedOutbound = (ByteBuf) messages.poll();
        int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
        if (i == chunkCount) {
            exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
            byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
            recievedOutbound.getBytes(
                    recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
            assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
        }

        byte[] header = new byte[String.valueOf(exptHeaderLength).length()
                + NetconfMessageConstants.MIN_HEADER_LENGTH - 1];
        recievedOutbound.getBytes(0, header);
        assertEquals(exptHeaderLength, getHeaderLength(header));

        testChunkChannel.writeInbound(recievedOutbound);
    }
    assertTrue(messages.isEmpty());

    NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound();
    assertNotNull(receivedMessage);
    assertXMLEqual(this.msg.getDocument(), receivedMessage.getDocument());
}

From source file:org.opendaylight.netide.netiplib.OpenFlowMessage.java

License:Open Source License

@Override
public byte[] getPayload() {
    SerializerRegistry registry = new SerializerRegistryImpl();
    registry.init();//from  www  .jav a  2 s  . com
    SerializationFactory factory = new SerializationFactory();
    factory.setSerializerTable(registry);
    ByteBuf output = UnpooledByteBufAllocator.DEFAULT.buffer();
    factory.messageToBuffer(getOfVersion(), output, getOfMessage());
    byte[] rawPayload = new byte[output.readableBytes()];
    output.getBytes(0, rawPayload);
    return rawPayload;
}

From source file:org.opendaylight.ocpjava.protocol.impl.serialization.factories.CreateObjInputFactoryTest.java

License:Open Source License

/**
 * Testing of {@link CreateObjInputFactory} for correct translation from POJO
 * @throws Exception/*from w  ww .  j ava  2s  .c om*/
 */
@Test
public void testElementsSet() throws Exception {
    CreateObjInputBuilder hib = new CreateObjInputBuilder();
    BufferHelper.setupHeader(hib, OcpMsgType.valueOf("CREATEOBJREQ"));
    boolean testEvent = true;
    String testObjTypeId = "exampleObj";

    //set xid
    Method m2_t = hib.getClass().getMethod("setXid", Long.class);
    m2_t.invoke(hib, new Long(0));

    //set ObjType
    Method m3_t = hib.getClass().getMethod("setObjType", ObjType.class);
    m3_t.invoke(hib, new ObjType(testObjTypeId));

    //set params
    ParamBuilder parambuilder1 = new ParamBuilder();
    List<Param> plist = new ArrayList();
    parambuilder1.setName("parameter1");
    parambuilder1.setValue("value1");
    plist.add(parambuilder1.build());
    ParamBuilder parambuilder2 = new ParamBuilder();
    parambuilder2.setName("parameter2");
    parambuilder2.setValue("value2");
    plist.add(parambuilder2.build());
    Method m4_t = hib.getClass().getMethod("setParam", List.class);
    m4_t.invoke(hib, plist);

    CreateObjInput hi = hib.build();
    LOG.debug("CreateObjInputFactoryTest - hi objId value = {}", hi.getObjType());

    ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
    createObjInputFactory.serialize(hi, out);

    //Verify and check the bytebuf info
    LOG.debug("HealthCheckInputMessageFactoryTest - out = {}", out.readableBytes());
    byte[] bytes = new byte[out.readableBytes()];
    int readerIndex = out.readerIndex();
    out.getBytes(readerIndex, bytes);

    String buf = new String(bytes, "UTF-8");
    StringBuilder seq = new StringBuilder("");
    seq.append("<param name=\"parameter1\">value1</param>");
    boolean checkVal = buf.contains(seq);

    StringBuilder seq2 = new StringBuilder("");
    seq2.append("<objType objTypeID=\"");
    seq2.append(testObjTypeId);
    seq2.append("\">");
    boolean checkVal2 = buf.contains(seq2);

    //Check and compare elements
    Assert.assertEquals("Wrong length", true, checkVal);
    Assert.assertEquals("Wrong length", true, checkVal2);
}

From source file:org.opendaylight.ocpjava.protocol.impl.serialization.factories.DeleteObjInputFactoryTest.java

License:Open Source License

/**
 * Testing of {@link HealthCheckInputMessageFactory} for correct translation from POJO
 * @throws Exception//from  w  w  w.j av a  2  s  .  c o  m
 */
@Test
public void testElementsSet() throws Exception {
    DeleteObjInputBuilder hib = new DeleteObjInputBuilder();
    BufferHelper.setupHeader(hib, OcpMsgType.valueOf("DELETEOBJREQ"));
    boolean testEvent = true;
    String testObjId = "exampleObj:0";
    //set xid
    Method m2_t = hib.getClass().getMethod("setXid", Long.class);
    m2_t.invoke(hib, new Long(0));

    //set ObjId
    Method m4_t = hib.getClass().getMethod("setObjId", ObjId.class);
    m4_t.invoke(hib, new ObjId(testObjId));

    DeleteObjInput hi = hib.build();
    LOG.debug("GetFaultInputFactoryTest - hi objId value = {}", hi.getObjId());

    ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
    deleteObjInputFactory.serialize(hi, out);

    //Verify and check the bytebuf info
    LOG.debug("DeleteObjInputFactoryTest - out = {}", out.readableBytes());
    byte[] bytes = new byte[out.readableBytes()];
    int readerIndex = out.readerIndex();
    out.getBytes(readerIndex, bytes);

    String buf = new String(bytes, "UTF-8");
    StringBuilder seq = new StringBuilder("");
    seq.append("<obj objID=\"");
    seq.append(testObjId);
    seq.append("\"/>");
    boolean checkVal = buf.contains(seq);

    //Check and compare elements
    Assert.assertEquals("Wrong length", true, checkVal);
}

From source file:org.opendaylight.ocpjava.protocol.impl.serialization.factories.GetFaultInputFactoryTest.java

License:Open Source License

/**
 * Testing of {@link HealthCheckInputMessageFactory} for correct translation from POJO
 * @throws Exception//www. j  av a2s  .  co m
 */
@Test
public void testElementsSet() throws Exception {
    GetFaultInputBuilder hib = new GetFaultInputBuilder();
    BufferHelper.setupHeader(hib, OcpMsgType.valueOf("GETFAULTREQ"));
    boolean testEvent = true;
    String testObjId = "ALL";
    //set xid
    Method m2_t = hib.getClass().getMethod("setXid", Long.class);
    m2_t.invoke(hib, new Long(0));

    //set ObjId
    Method m3_t = hib.getClass().getMethod("setObjId", ObjId.class);
    m3_t.invoke(hib, new ObjId(testObjId));

    //set eventDrivenReporting
    Method m4_t = hib.getClass().getMethod("setEventDrivenReporting", Boolean.class);
    m4_t.invoke(hib, new Boolean(testEvent));

    GetFaultInput hi = hib.build();
    LOG.debug("GetFaultInputFactoryTest - hi objId value = {}", hi.getObjId());

    ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
    getFaultInputFactory.serialize(hi, out);

    //Verify and check the bytebuf info
    LOG.debug("HealthCheckInputMessageFactoryTest - out = {}", out.readableBytes());
    byte[] bytes = new byte[out.readableBytes()];
    int readerIndex = out.readerIndex();
    out.getBytes(readerIndex, bytes);

    String buf = new String(bytes, "UTF-8");
    StringBuilder seq = new StringBuilder("");
    seq.append("<eventDrivenReporting>");
    seq.append(String.valueOf(testEvent));
    seq.append("</eventDrivenReporting>");
    boolean checkVal = buf.contains(seq);

    StringBuilder seq2 = new StringBuilder("");
    seq2.append("<obj objID=\"");
    seq2.append(testObjId);
    seq2.append("\"/>");
    boolean checkVal2 = buf.contains(seq2);

    //Check and compare elements
    Assert.assertEquals("Wrong length", true, checkVal);
    Assert.assertEquals("Wrong length", true, checkVal2);
}

From source file:org.opendaylight.ocpjava.protocol.impl.serialization.factories.GetParamInputFactoryTest.java

License:Open Source License

/**
 * Testing of {@link GetParamInputFactory} for correct translation from POJO
 * @throws Exception/*from   w  w w  .  j a va  2s .  com*/
 */
@Test
public void testElementsSet() throws Exception {
    GetParamInputBuilder hib = new GetParamInputBuilder();
    BufferHelper.setupHeader(hib, OcpMsgType.valueOf("GETPARAMREQ"));
    String testObjId = "RE:0";
    //set xid
    Method m2_t = hib.getClass().getMethod("setXid", Long.class);
    m2_t.invoke(hib, new Long(0));

    //set ObjId
    Method m3_t = hib.getClass().getMethod("setObjId", ObjId.class);
    m3_t.invoke(hib, new ObjId(testObjId));

    //set paramName
    Method m4_t = hib.getClass().getMethod("setParamName", String.class);
    m4_t.invoke(hib, "vendorID");

    GetParamInput hi = hib.build();
    LOG.debug("GetParamInputFactoryTest - hi objId = {}", hi.getObjId().getValue());
    LOG.debug("GetParamInputFactoryTest - hi paramName = {}", hi.getParamName());

    ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
    getParamInputFactory.serialize(hi, out);

    //Verify and check the bytebuf info
    LOG.debug("GetParamInputFactoryTest - out = {}", out.readableBytes());
    byte[] bytes = new byte[out.readableBytes()];
    int readerIndex = out.readerIndex();
    out.getBytes(readerIndex, bytes);

    String buf = new String(bytes, "UTF-8");
    StringBuilder seq = new StringBuilder("");
    seq.append("<obj objID=\"");
    seq.append(testObjId);
    seq.append("\">");
    boolean checkVal = buf.contains(seq);

    //Check and compare elements
    Assert.assertEquals("Wrong length", true, checkVal);
}