Example usage for io.netty.buffer ByteBuf getByte

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

Introduction

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

Prototype

public abstract byte getByte(int index);

Source Link

Document

Gets a byte at the specified absolute index in this buffer.

Usage

From source file:org.hornetq.tests.integration.transports.netty.HornetQFrameDecoder2Test.java

License:Apache License

@Test
public void testExtremeFragmentation() throws Exception {
    final EmbeddedChannel decoder = new EmbeddedChannel(new HornetQFrameDecoder2());

    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 4 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 5 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 6 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 7 }));
    Assert.assertNull(decoder.readInbound());
    decoder.writeInbound(Unpooled.wrappedBuffer(new byte[] { 8 }));

    ByteBuf frame = (ByteBuf) decoder.readInbound();
    Assert.assertEquals(4, frame.readerIndex());
    Assert.assertEquals(4, frame.readableBytes());
    Assert.assertEquals(5, frame.getByte(4));
    Assert.assertEquals(6, frame.getByte(5));
    Assert.assertEquals(7, frame.getByte(6));
    Assert.assertEquals(8, frame.getByte(7));
    frame.release();//from w  w  w  . j av  a  2 s.  c  o  m
}

From source file:org.jfxvnc.net.rfb.codec.decoder.FramebufferUpdateRectDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf m, List<Object> out) throws Exception {

    if (state == State.INIT) {
        logger.debug("init readable {} bytes", m.readableBytes());
        if (!m.isReadable()) {
            return false;
        }/*from w  w  w.  j  ava 2s.c  o  m*/
        if (m.getByte(0) != ServerEvent.FRAMEBUFFER_UPDATE.getType()) {
            logger.error("no FBU type!!! {}", m.getByte(0));
            ctx.pipeline().fireChannelReadComplete();
            return false;
        }
        if (!m.isReadable(4)) {
            return false;
        }
        m.skipBytes(2); // padding
        numberRects = m.readUnsignedShort();
        currentRect = 0;
        logger.debug("number of rectangles: {}", numberRects);
        if (numberRects < 1) {
            return true;
        }
        state = State.NEW_RECT;
    }

    if (state == State.NEW_RECT) {
        if (!readRect(ctx, m, out)) {
            return false;
        }
        state = State.READ_RECT;
    }

    FrameRectDecoder dec = frameRectDecoder.get(rect.getEncoding());
    if (dec == null) {
        throw new ProtocolException("Encoding not supported: " + rect.getEncoding());
    }
    dec.setRect(rect);
    if (!dec.decode(ctx, m, out)) {
        return false;
    }

    if (currentRect == numberRects) {
        state = State.INIT;
        ctx.pipeline().fireUserEventTriggered(ProtocolState.FBU_REQUEST);
        return true;
    }

    if (!readRect(ctx, m, out)) {
        state = State.NEW_RECT;
    }
    return false;
}

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.CursorRectDecoder.java

License:Apache License

@Override
protected void sendRect(List<Object> out) {
    int i = 0;//  w  w w.  ja v a2s . co m
    ByteBuf pixels = aloc.buffer(capacity - bitMaskLength);
    while (pixels.isWritable(4)) {
        pixels.writeInt(framebuffer.getUnsignedByte(i * 4 + redPos) << pixelFormat.getRedShift()
                | framebuffer.getUnsignedByte(i * 4 + 1) << pixelFormat.getGreenShift()
                | framebuffer.getUnsignedByte(i * 4 + bluePos) << pixelFormat.getBlueShift() | 0xff000000);
        i++;
    }

    if (bitMaskLength > 0) {
        ByteBuf bitmask = aloc.buffer(bitMaskLength);
        framebuffer.getBytes(capacity - bitMaskLength, bitmask);
        // remove transparent pixels
        int maskBytesPerRow = Math.floorDiv((rect.getWidth() + 7), 8);
        IntStream.range(0, rect.getHeight())
                .forEach(y -> IntStream.range(0, rect.getWidth())
                        .filter(x -> (bitmask.getByte((y * maskBytesPerRow) + Math.floorDiv(x, 8))
                                & (1 << 7 - Math.floorMod(x, 8))) < 1)
                        .forEach(x -> pixels.setInt((y * rect.getWidth() + x) * 4, 0)));
        bitmask.release();
    }
    out.add(new CursorImageRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), pixels));
}

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

License:Apache License

/**
 * Decode the bytes to Json object./*ww  w .  j a  va2  s.co m*/
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext) throws Exception {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}

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

License:Apache License

/**
 * Filter the invalid characters before decoding.
 * @param in input of bytes/*from ww w.  ja  va  2  s.co  m*/
 * @param lastReadBytes the bytes for last decoding incomplete record
 */
private static void fliterCharaters(ByteBuf in) {
    while (in.isReadable()) {
        int ch = in.getByte(in.readerIndex());
        if ((ch != ' ') && (ch != '\n') && (ch != '\t') && (ch != '\r')) {
            break;
        } else {
            in.readByte();
        }
    }
}

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

License:Apache License

/**
 * Decode the bytes to Json object.//from w  w w .ja  va  2 s  .c o m
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 * @throws IOException IOException
 * @throws JsonParseException JsonParseException
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext) throws IOException {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}

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

License:Open Source License

private int indexOfSequence(ByteBuf in, byte[] sequence) {
    int index = -1;
    for (int i = 0; i < in.readableBytes() - sequence.length + 1; i++) {
        if (in.getByte(i) == sequence[0]) {
            index = i;/* ww  w  . j  a va2s  .  c o  m*/
            for (int j = 1; j < sequence.length; j++) {
                if (in.getByte(i + j) != sequence[j]) {
                    index = -1;
                    break;
                }
            }
            if (index != -1) {
                return index;
            }
        }
    }
    return index;
}

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   www  .  ja v a2  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.groupbasedpolicy.jsonrpc.JsonRpcDecoder.java

License:Open Source License

private static void skipSpaces(ByteBuf b) throws IOException {
    while (b.isReadable()) {
        int ch = b.getByte(b.readerIndex()) & 0xFF;
        if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
            return;
        }/*w  w  w  .j a va  2 s  . co  m*/
        b.readByte(); //move the read index
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.clients.SimpleClientFramer.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() < LENGTH_OF_HEADER) {
        LOGGER.debug("skipping bb - too few data for header: " + bb.readableBytes());
        return;/*  w ww  . j a v  a 2s  .c om*/
    }

    int length = bb.getUnsignedShort(LENGTH_INDEX_IN_HEADER);
    if (bb.readableBytes() < length) {
        LOGGER.debug("skipping bb - too few data for msg: " + bb.readableBytes() + " < " + length);
        return;
    }
    LOGGER.debug("OF Protocol message received, type:{}", bb.getByte(1));

    ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
    list.add(messageBuffer);
    messageBuffer.retain();
    bb.skipBytes(length);
}