Example usage for io.netty.buffer ByteBuf markReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf markReaderIndex();

Source Link

Document

Marks the current readerIndex in this buffer.

Usage

From source file:org.mobicents.protocols.ss7.m3ua.impl.message.MessageFactoryImpl.java

License:Open Source License

public M3UAMessageImpl createMessage(ByteBuf message) {
    int dataLen;/*from w  w w  . j  a va 2s .c  o m*/
    if (message.readableBytes() < 8) {
        return null;
    }

    // obtain message class and type from header
    message.markReaderIndex();
    message.skipBytes(2);
    int messageClass = message.readUnsignedByte();
    int messageType = message.readUnsignedByte();

    // obtain remaining length of the message and prepare buffer
    dataLen = message.readInt() - 8;
    if (message.readableBytes() < dataLen) {
        message.resetReaderIndex();
        return null;
    }

    // construct new message instance
    M3UAMessageImpl messageTemp = this.createMessage(messageClass, messageType);

    // parsing params of this message
    message.markWriterIndex();
    message.writerIndex(message.readerIndex() + dataLen);
    messageTemp.decode(message);
    message.resetWriterIndex();

    return messageTemp;
}

From source file:org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder.java

License:Open Source License

@Override
@VisibleForTesting/*  w w  w. ja  va2 s  . c  o m*/
public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws IOException, SAXException, NetconfDocumentedException {
    if (in.readableBytes() == 0) {
        LOG.debug("No more content in incoming buffer.");
        return;
    }

    in.markReaderIndex();
    try {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
        }

        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);

        logMessage(bytes);

        // Extract bytes containing header with additional metadata
        String additionalHeader = null;
        if (startsWithAdditionalHeader(bytes)) {
            // Auth information containing username, ip address... extracted for monitoring
            int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
            if (endOfAuthHeader > -1) {
                byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
                additionalHeader = additionalHeaderToString(additionalHeaderBytes);
                bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
            }
        }

        Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));

        final NetconfMessage message = getNetconfMessage(additionalHeader, doc);
        if (message instanceof NetconfHelloMessage) {
            Preconditions.checkState(helloReceived == false,
                    "Multiple hello messages received, unexpected hello: %s", message);
            out.add(message);
            helloReceived = true;
            // Non hello message, suspend the message and insert into cache
        } else {
            Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s",
                    message);
            LOG.debug("Netconf message received during negotiation, caching {}", message);
            nonHelloMessages.add(message);
        }
    } finally {
        in.discardReadBytes();
    }
}

From source file:org.opendaylight.controller.netconf.util.handler.NetconfXMLToHelloMessageDecoder.java

License:Open Source License

@Override
@VisibleForTesting//from w w  w.j ava 2 s .  c  o m
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() == 0) {
        LOG.debug("No more content in incoming buffer.");
        return;
    }

    in.markReaderIndex();
    try {
        LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);

        logMessage(bytes);

        // Extract bytes containing header with additional metadata
        String additionalHeader = null;
        if (startsWithAdditionalHeader(bytes)) {
            // Auth information containing username, ip address... extracted for monitoring
            int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
            if (endOfAuthHeader > -1) {
                byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
                additionalHeader = additionalHeaderToString(additionalHeaderBytes);
                bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
            }
        }

        Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));

        final NetconfMessage message;
        if (additionalHeader != null) {
            message = new NetconfHelloMessage(doc,
                    NetconfHelloMessageAdditionalHeader.fromString(additionalHeader));
        } else {
            message = new NetconfHelloMessage(doc);
        }
        out.add(message);
    } finally {
        in.discardReadBytes();
    }
}

From source file:org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder.java

License:Open Source License

@Override
@VisibleForTesting/* w  ww.  ja  va 2 s.  c  o  m*/
public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws IOException, SAXException, NetconfDocumentedException {
    if (in.readableBytes() == 0) {
        LOG.debug("No more content in incoming buffer.");
        return;
    }

    in.markReaderIndex();
    try {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
        }

        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);

        logMessage(bytes);

        // Extract bytes containing header with additional metadata
        String additionalHeader = null;
        if (startsWithAdditionalHeader(bytes)) {
            // Auth information containing username, ip address... extracted for monitoring
            int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
            if (endOfAuthHeader > -1) {
                byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader);
                additionalHeader = additionalHeaderToString(additionalHeaderBytes);
                bytes = Arrays.copyOfRange(bytes, endOfAuthHeader, bytes.length);
            }
        }

        Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));

        final NetconfMessage message = getNetconfMessage(additionalHeader, doc);
        if (message instanceof NetconfHelloMessage) {
            Preconditions.checkState(helloReceived == false,
                    "Multiple hello messages received, unexpected hello: %s", message);
            out.add(message);
            helloReceived = true;
            // Non hello message, suspend the message and insert into cache
        } else {
            Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s",
                    message);
            LOG.debug("Netconf message received during negotiation, caching {}", message);
            nonHelloMessages.add(message);
        }
    } finally {
        in.discardReadBytes();
    }
}

From source file:org.opendaylight.protocol.pcep.impl.PCEPByteToMessageDecoder.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
    if (!in.isReadable()) {
        LOG.debug("No more content in incoming buffer.");
        return;/*from   w  ww  .  j  ava2 s  .  c o m*/
    }

    in.markReaderIndex();
    LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));

    final List<Message> errors = new ArrayList<>();

    try {
        out.add(parse(in, errors));
    } catch (final PCEPDeserializerException e) {
        LOG.debug("Failed to decode protocol message", e);
    }
    in.discardReadBytes();

    if (!errors.isEmpty()) {
        // We have a bunch of messages, send them out
        for (final Object e : errors) {
            ctx.channel().writeAndFlush(e).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(final ChannelFuture f) {
                    if (!f.isSuccess()) {
                        LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause());
                    } else {
                        LOG.trace("Message {} sent to socket {}", e, ctx.channel());
                    }
                }
            });
        }
    }
}

From source file:org.opendaylight.protocol.pcep.spi.UtilsTest.java

License:Open Source License

@Test
public void testXROSubobjectUtil() {
    byte[] expected = { (byte) 0x82, 6, 0, 1, 2, 3 };
    final ByteBuf out = Unpooled.buffer();
    final ByteBuf body = Unpooled.copiedBuffer(new byte[] { 0, 1, 2, 3 });
    body.markReaderIndex();
    XROSubobjectUtil.formatSubobject(2, true, body, out);
    assertArrayEquals(expected, ByteArray.getAllBytes(out));

    expected = new byte[] { 2, 6, 0, 1, 2, 3 };
    out.clear();//  www  . j ava 2s .  c  o  m
    body.resetReaderIndex();
    XROSubobjectUtil.formatSubobject(2, false, body, out);
    assertArrayEquals(expected, ByteArray.getAllBytes(out));

    out.clear();
    body.resetReaderIndex();
    XROSubobjectUtil.formatSubobject(2, null, body, out);
    assertArrayEquals(expected, ByteArray.getAllBytes(out));
}

From source file:org.opendaylight.protocol.pcep.spi.UtilsTest.java

License:Open Source License

@Test
public void testEROSubobjectUtil() {
    byte[] expected = { (byte) 0x82, 6, 0, 1, 2, 3 };
    final ByteBuf out = Unpooled.buffer();
    final ByteBuf body = Unpooled.copiedBuffer(new byte[] { 0, 1, 2, 3 });
    body.markReaderIndex();
    EROSubobjectUtil.formatSubobject(2, true, body, out);
    assertArrayEquals(expected, ByteArray.getAllBytes(out));

    expected = new byte[] { 2, 6, 0, 1, 2, 3 };
    out.clear();/*from www . j  a v  a 2 s.  c  o  m*/
    body.resetReaderIndex();
    EROSubobjectUtil.formatSubobject(2, false, body, out);
    assertArrayEquals(expected, ByteArray.getAllBytes(out));
}

From source file:org.quartzpowered.network.codec.FrameCodec.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // check for length field readability
    in.markReaderIndex();
    if (!readableVarInt(in)) {
        return;/*from   w ww. j  a v  a 2 s  .  co  m*/
    }

    // check for contents readability
    Buffer buffer = new Buffer(in);
    int length = buffer.readVarInt();
    if (in.readableBytes() < length) {
        in.resetReaderIndex();
        return;
    }

    // read contents into buf
    out.add(in.readBytes(length));
}

From source file:org.ratpackframework.groovy.templating.internal.TemplateParser.java

License:Apache License

public void parse(ByteBuf input, ByteBuf output) throws IOException {
    startScript(output);// www. j ava  2  s .c o m
    byte c;
    while (input.isReadable()) {
        c = input.readByte();
        if (c == '<') {
            input.markReaderIndex();
            c = input.readByte();
            if (c != '%') {
                output.writeBytes(LESS_THAN);
                input.resetReaderIndex();
            } else {
                input.markReaderIndex();
                c = input.readByte();
                if (c == '=') {
                    groovyExpression(input, output);
                } else {
                    input.resetReaderIndex();
                    groovySection(input, output);
                }
            }
            continue; // at least '<' is consumed ... read next chars.
        }
        if (c == '$') {
            input.markReaderIndex();
            c = input.readByte();
            if (c != '{') {
                output.writeBytes(DOLLAR);
                input.resetReaderIndex();
            } else {
                input.markReaderIndex();
                processGSstring(input, output);
            }
            continue; // at least '$' is consumed ... read next chars.
        }
        if (c == '\"') {
            output.writeBytes(BACKSLASH);
        }

        // Handle raw new line characters.
        if (c == '\n' || c == '\r') {
            if (c == '\r') { // on Windows, "\r\n" is a new line.
                input.markReaderIndex();
                c = input.readByte();
                if (c != '\n') {
                    input.resetReaderIndex();
                }
            }
            output.writeByte('\n');
            continue;
        }
        output.writeByte(c);
    }

    endScript(output);
}

From source file:org.spongepowered.clean.network.netty.PacketSplitter.java

License:MIT License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();
    int numRead = 0;
    int length = 0;
    byte read;/*  w ww  . j  a  v  a2  s . c  om*/
    do {
        if (!in.isReadable()) {
            in.resetReaderIndex();
            return;
        }
        read = in.readByte();
        int value = (read & 0b01111111);
        length |= (value << (7 * numRead));

        numRead++;
        if (numRead > 5) {
            throw new RuntimeException("Error decoding packet, length not a varint!");
        }
    } while ((read & 0b10000000) != 0);
    if (in.readableBytes() >= length) {
        out.add(in.readBytes(length));
    } else {
        in.resetReaderIndex();
    }
}