Example usage for io.netty.buffer ByteBuf writerIndex

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

Introduction

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

Prototype

public abstract int writerIndex();

Source Link

Document

Returns the writerIndex of this buffer.

Usage

From source file:org.spout.engine.protocol.builtin.SpoutProtocol.java

License:Open Source License

@Override
public ByteBuf writeHeader(MessageCodec<?> codec, ByteBuf data) {
    ByteBuf buf = Unpooled.buffer(4);/*from  w  w  w  .j a  v a 2 s .  c o m*/
    buf.writeShort(codec.getOpcode());
    //if (Spout.debugMode()) System.out.println("Writing codec header: " + codec.getOpcode());
    buf.writeInt(data.writerIndex());
    return buf;
}

From source file:org.spout.vanilla.protocol.rcon.codec.RconCodec.java

License:Open Source License

@Override
public T decode(ByteBuf buffer) {
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf expandingBytes = Unpooled.buffer(buffer.writerIndex());
    byte b;/* www  .  ja v a 2 s. com*/
    while ((b = buffer.readByte()) != 0) {
        expandingBytes.writeByte(b);
    }
    assert buffer.readByte() == 0; // Second null byte

    String value = new String(expandingBytes.array(), CharsetUtil.US_ASCII);
    return createMessage(value);
}

From source file:org.springframework.reactive.codec.decoder.JsonObjectDecoder.java

License:Apache License

@Override
public Publisher<ByteBuffer> decode(Publisher<ByteBuffer> inputStream, ResolvableType type, MediaType mediaType,
        Object... hints) {//from  w ww.  j a  v  a  2s  . c o m

    return Streams.wrap(inputStream).flatMap(new Function<ByteBuffer, Publisher<? extends ByteBuffer>>() {

        int openBraces;
        int idx;
        int state;
        boolean insideString;
        ByteBuf in;
        Integer wrtIdx;

        @Override
        public Publisher<? extends ByteBuffer> apply(ByteBuffer b) {
            List<ByteBuffer> chunks = new ArrayList<>();

            if (in == null) {
                in = Unpooled.copiedBuffer(b);
                wrtIdx = in.writerIndex();
            } else {
                in = Unpooled.copiedBuffer(in, Unpooled.copiedBuffer(b));
                wrtIdx = in.writerIndex();
            }
            if (state == ST_CORRUPTED) {
                in.skipBytes(in.readableBytes());
                return Streams.fail(new IllegalStateException("Corrupted stream"));
            }

            if (wrtIdx > maxObjectLength) {
                // buffer size exceeded maxObjectLength; discarding the complete buffer.
                in.skipBytes(in.readableBytes());
                reset();
                return Streams.fail(new IllegalStateException(
                        "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded"));
            }

            for (/* use current idx */; idx < wrtIdx; idx++) {
                byte c = in.getByte(idx);
                if (state == ST_DECODING_NORMAL) {
                    decodeByte(c, in, idx);

                    // All opening braces/brackets have been closed. That's enough to conclude
                    // that the JSON object/array is complete.
                    if (openBraces == 0) {
                        ByteBuf json = extractObject(in, in.readerIndex(), idx + 1 - in.readerIndex());
                        if (json != null) {
                            chunks.add(json.nioBuffer());
                        }

                        // The JSON object/array was extracted => discard the bytes from
                        // the input buffer.
                        in.readerIndex(idx + 1);
                        // Reset the object state to get ready for the next JSON object/text
                        // coming along the byte stream.
                        reset();
                    }
                } else if (state == ST_DECODING_ARRAY_STREAM) {
                    decodeByte(c, in, idx);

                    if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                        // skip leading spaces. No range check is needed and the loop will terminate
                        // because the byte at position idx is not a whitespace.
                        for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                            in.skipBytes(1);
                        }

                        // skip trailing spaces.
                        int idxNoSpaces = idx - 1;
                        while (idxNoSpaces >= in.readerIndex()
                                && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                            idxNoSpaces--;
                        }

                        ByteBuf json = extractObject(in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                        if (json != null) {
                            chunks.add(json.nioBuffer());
                        }

                        in.readerIndex(idx + 1);

                        if (c == ']') {
                            reset();
                        }
                    }
                    // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
                } else if (c == '{' || c == '[') {
                    initDecoding(c, streamArrayElements);

                    if (state == ST_DECODING_ARRAY_STREAM) {
                        // Discard the array bracket
                        in.skipBytes(1);
                    }
                    // Discard leading spaces in front of a JSON object/array.
                } else if (Character.isWhitespace(c)) {
                    in.skipBytes(1);
                } else {
                    state = ST_CORRUPTED;
                    return Streams.fail(new IllegalStateException(
                            "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)));
                }
            }

            if (in.readableBytes() == 0) {
                idx = 0;
            }
            return Streams.from(chunks);
        }

        /**
         * Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
         */
        @SuppressWarnings("UnusedParameters")
        protected ByteBuf extractObject(ByteBuf buffer, int index, int length) {
            return buffer.slice(index, length).retain();
        }

        private void decodeByte(byte c, ByteBuf in, int idx) {
            if ((c == '{' || c == '[') && !insideString) {
                openBraces++;
            } else if ((c == '}' || c == ']') && !insideString) {
                openBraces--;
            } else if (c == '"') {
                // start of a new JSON string. It's necessary to detect strings as they may
                // also contain braces/brackets and that could lead to incorrect results.
                if (!insideString) {
                    insideString = true;
                    // If the double quote wasn't escaped then this is the end of a string.
                } else if (in.getByte(idx - 1) != '\\') {
                    insideString = false;
                }
            }
        }

        private void initDecoding(byte openingBrace, boolean streamArrayElements) {
            openBraces = 1;
            if (openingBrace == '[' && streamArrayElements) {
                state = ST_DECODING_ARRAY_STREAM;
            } else {
                state = ST_DECODING_NORMAL;
            }
        }

        private void reset() {
            insideString = false;
            state = ST_INIT;
            openBraces = 0;
        }

    });
}

From source file:org.teiid.transport.ObjectEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    ByteBuf out = allocateBuffer(ctx, this.estimatedLength, this.preferDirect);
    int startIdx = out.writerIndex();
    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    bout.write(LENGTH_PLACEHOLDER);// w w  w  .j  ava 2  s.  c  o  m
    final CompactObjectOutputStream oout = new CompactObjectOutputStream(bout);
    try {
        oout.writeObject(msg);
        ExternalizeUtil.writeCollection(oout, oout.getReferences());
        oout.flush();
        oout.close();

        int endIdx = out.writerIndex();
        out.setInt(startIdx, endIdx - startIdx - 4);

        if (out.isReadable()) {
            ctx.write(out, promise);
            for (InputStream is : oout.getStreams()) {
                ctx.write(new AnonymousChunkedStream(new BufferedInputStream(is, CHUNK_SIZE)), promise);
            }
        } else {
            out.release();
            ctx.write(Unpooled.EMPTY_BUFFER, promise);
        }
        ctx.flush();
        out = null;
    } catch (Throwable t) {
        throw new FailedWriteException(msg, t);
    } finally {
        if (out != null) {
            out.release();
        }
    }
}

From source file:org.tiger.netty.rpc.all.codec.MarshallingEncoder.java

License:Apache License

protected void encode(Object msg, ByteBuf out) throws Exception {
    try {/*  www .j a v  a2  s. c  o  m*/
        int lengthPos = out.writerIndex();
        out.writeBytes(LENGTH_PLACEHOLDER);//??
        ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
        marshaller.start(output);
        marshaller.writeObject(msg);
        marshaller.finish();
        //ByteBufsetInt(int index, int value):indexvalueint
        //?ByteBufwriteIntsetInt??readerIndexwriterIndex
        //??4??
        out.setInt(lengthPos, out.writerIndex() - lengthPos - 4);
    } finally {
        marshaller.close();
    }
}

From source file:org.tinygroup.nettyremote.codec.serialization.HessianEncoder.java

License:GNU General Public License

@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    int startIdx = out.writerIndex();

    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    bout.write(LENGTH_PLACEHOLDER);/*  w  ww . j  a  v a  2  s.c  o m*/
    //        ObjectOutputStream oout = new CompactObjectOutputStream(bout);
    //        oout.writeObject(msg);
    //        oout.flush();
    //        oout.close();
    SerializerFactory serializerFactory = new SerializerFactory();
    serializerFactory.addFactory(new BigDecimalSerializerFactory());
    HessianOutput hout = new HessianOutput(bout);
    hout.setSerializerFactory(serializerFactory);
    hout.writeObject(msg);
    int endIdx = out.writerIndex();

    out.setInt(startIdx, endIdx - startIdx - 4);
}

From source file:org.traccar.protocol.AtrackFrameDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {

    if (buf.readableBytes() >= 2) {

        if (buf.getUnsignedShort(buf.readerIndex()) == 0xfe02) {

            if (buf.readableBytes() >= KEEPALIVE_LENGTH) {
                return buf.readRetainedSlice(KEEPALIVE_LENGTH);
            }//  ww  w .java  2s  . c om

        } else if (buf.getUnsignedShort(buf.readerIndex()) == 0x4050
                && buf.getByte(buf.readerIndex() + 2) != ',') {

            if (buf.readableBytes() > 6) {
                int length = buf.getUnsignedShort(buf.readerIndex() + 4) + 4 + 2;
                if (buf.readableBytes() >= length) {
                    return buf.readRetainedSlice(length);
                }
            }

        } else {

            int lengthStart = buf.indexOf(buf.readerIndex() + 3, buf.writerIndex(), (byte) ',') + 1;
            if (lengthStart > 0) {
                int lengthEnd = buf.indexOf(lengthStart, buf.writerIndex(), (byte) ',');
                if (lengthEnd > 0) {
                    int length = lengthEnd + Integer.parseInt(
                            buf.toString(lengthStart, lengthEnd - lengthStart, StandardCharsets.US_ASCII));
                    if (buf.readableBytes() > length && buf.getByte(buf.readerIndex() + length) == '\n') {
                        length += 1;
                    }
                    if (buf.readableBytes() >= length) {
                        return buf.readRetainedSlice(length);
                    }
                }
            } else {
                int endIndex = BufferUtil.indexOf("\r\n", buf);
                if (endIndex > 0) {
                    return buf.readRetainedSlice(endIndex - buf.readerIndex() + 2);
                }
            }

        }

    }

    return null;
}

From source file:org.traccar.protocol.AtrackProtocolDecoder.java

License:Apache License

private static String readString(ByteBuf buf) {
    String result = null;/*from   ww w. j a v  a  2s.co  m*/
    int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) 0);
    if (index > buf.readerIndex()) {
        result = buf.readSlice(index - buf.readerIndex()).toString(StandardCharsets.US_ASCII);
    }
    buf.readByte();
    return result;
}

From source file:org.traccar.protocol.AutoFonProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    int type = buf.readUnsignedByte();

    if (type == MSG_LOGIN || type == MSG_45_LOGIN) {

        if (type == MSG_LOGIN) {
            buf.readUnsignedByte(); // hardware version
            buf.readUnsignedByte(); // software version
        }//www  .  j  av  a 2s  .  com

        String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1);
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);

        if (deviceSession != null && channel != null) {
            ByteBuf response = Unpooled.buffer();
            response.writeBytes("resp_crc=".getBytes(StandardCharsets.US_ASCII));
            response.writeByte(buf.getByte(buf.writerIndex() - 1));
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }

        return null;

    }

    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
    if (deviceSession == null) {
        return null;
    }

    if (type == MSG_LOCATION) {

        return decodePosition(deviceSession, buf, false);

    } else if (type == MSG_HISTORY) {

        int count = buf.readUnsignedByte() & 0x0f;
        buf.readUnsignedShort(); // total count
        List<Position> positions = new LinkedList<>();

        for (int i = 0; i < count; i++) {
            positions.add(decodePosition(deviceSession, buf, true));
        }

        return positions;

    } else if (type == MSG_45_LOCATION) {

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        short status = buf.readUnsignedByte();
        if (BitUtil.check(status, 7)) {
            position.set(Position.KEY_ALARM, Position.ALARM_GENERAL);
        }
        position.set(Position.KEY_BATTERY, BitUtil.to(status, 7));

        buf.skipBytes(2); // remaining time

        position.set(Position.PREFIX_TEMP + 1, buf.readByte());

        buf.skipBytes(2); // timer (interval and units)
        buf.readByte(); // mode
        buf.readByte(); // gprs sending interval

        buf.skipBytes(6); // mcc, mnc, lac, cid

        int valid = buf.readUnsignedByte();
        position.setValid(BitUtil.from(valid, 6) != 0);
        position.set(Position.KEY_SATELLITES, BitUtil.from(valid, 6));

        int time = buf.readUnsignedMedium();
        int date = buf.readUnsignedMedium();

        DateBuilder dateBuilder = new DateBuilder().setTime(time / 10000, time / 100 % 100, time % 100)
                .setDateReverse(date / 10000, date / 100 % 100, date % 100);
        position.setTime(dateBuilder.getDate());

        position.setLatitude(convertCoordinate(buf.readUnsignedByte(), buf.readUnsignedMedium()));
        position.setLongitude(convertCoordinate(buf.readUnsignedByte(), buf.readUnsignedMedium()));
        position.setSpeed(buf.readUnsignedByte());
        position.setCourse(buf.readUnsignedShort());

        return position;

    }

    return null;
}

From source file:org.traccar.protocol.BceProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;//from   www.j a  v a 2 s .co  m

    String imei = String.format("%015d", buf.readLongLE());
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
    if (deviceSession == null) {
        return null;
    }

    List<Position> positions = new LinkedList<>();

    while (buf.readableBytes() > 1) {

        int dataEnd = buf.readUnsignedShortLE() + buf.readerIndex();
        int type = buf.readUnsignedByte();

        if (type != MSG_ASYNC_STACK && type != MSG_TIME_TRIGGERED) {
            return null;
        }

        int confirmKey = buf.readUnsignedByte() & 0x7F;

        while (buf.readerIndex() < dataEnd) {

            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            int structEnd = buf.readUnsignedByte() + buf.readerIndex();

            long time = buf.readUnsignedIntLE();
            if ((time & 0x0f) == DATA_TYPE) {

                time = time >> 4 << 1;
                time += 0x47798280; // 01/01/2008
                position.setTime(new Date(time * 1000));

                // Read masks
                int mask;
                List<Integer> masks = new LinkedList<>();
                do {
                    mask = buf.readUnsignedShortLE();
                    masks.add(mask);
                } while (BitUtil.check(mask, 15));

                mask = masks.get(0);

                if (BitUtil.check(mask, 0)) {
                    position.setValid(true);
                    position.setLongitude(buf.readFloatLE());
                    position.setLatitude(buf.readFloatLE());
                    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));

                    int status = buf.readUnsignedByte();
                    position.set(Position.KEY_SATELLITES, BitUtil.to(status, 4));
                    position.set(Position.KEY_HDOP, BitUtil.from(status, 4));

                    position.setCourse(buf.readUnsignedByte() * 2);
                    position.setAltitude(buf.readUnsignedShortLE());

                    position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
                }

                if (BitUtil.check(mask, 1)) {
                    position.set(Position.KEY_INPUT, buf.readUnsignedShortLE());
                }

                for (int i = 1; i <= 8; i++) {
                    if (BitUtil.check(mask, i + 1)) {
                        position.set(Position.PREFIX_ADC + i, buf.readUnsignedShortLE());
                    }
                }

                if (BitUtil.check(mask, 10)) {
                    buf.skipBytes(4);
                }
                if (BitUtil.check(mask, 11)) {
                    buf.skipBytes(4);
                }
                if (BitUtil.check(mask, 12)) {
                    buf.skipBytes(2);
                }
                if (BitUtil.check(mask, 13)) {
                    buf.skipBytes(2);
                }

                if (BitUtil.check(mask, 14)) {
                    position.setNetwork(new Network(CellTower.from(buf.readUnsignedShortLE(),
                            buf.readUnsignedByte(), buf.readUnsignedShortLE(), buf.readUnsignedShortLE(),
                            buf.readUnsignedByte())));
                    buf.readUnsignedByte();
                }

                if (BitUtil.check(mask, 0)) {
                    positions.add(position);
                }
            }

            buf.readerIndex(structEnd);
        }

        // Send response
        if (type == MSG_ASYNC_STACK && channel != null) {
            ByteBuf response = Unpooled.buffer(8 + 2 + 2 + 1);
            response.writeLongLE(Long.parseLong(imei));
            response.writeShortLE(2);
            response.writeByte(MSG_STACK_COFIRM);
            response.writeByte(confirmKey);

            int checksum = 0;
            for (int i = 0; i < response.writerIndex(); i++) {
                checksum += response.getUnsignedByte(i);
            }
            response.writeByte(checksum);

            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
    }

    return positions;
}