Example usage for io.netty.buffer ByteBuf nioBuffer

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

Introduction

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

Prototype

public abstract ByteBuffer nioBuffer();

Source Link

Document

Exposes this buffer's readable bytes as an NIO ByteBuffer .

Usage

From source file:org.springframework.core.codec.support.JsonObjectDecoder.java

License:Apache License

@Override
public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType type, MimeType mimeType,
        Object... hints) {// w w  w . j a va2s .  com

    return Flux.from(inputStream).flatMap(new Function<DataBuffer, Publisher<? extends DataBuffer>>() {

        int openBraces;
        int index;
        int state;
        boolean insideString;
        ByteBuf input;
        Integer writerIndex;

        @Override
        public Publisher<? extends DataBuffer> apply(DataBuffer b) {
            List<DataBuffer> chunks = new ArrayList<>();
            if (this.input == null) {
                this.input = Unpooled.copiedBuffer(b.asByteBuffer());
                this.writerIndex = this.input.writerIndex();
            } else {
                this.input = Unpooled.copiedBuffer(this.input, Unpooled.copiedBuffer(b.asByteBuffer()));
                this.writerIndex = this.input.writerIndex();
            }
            if (this.state == ST_CORRUPTED) {
                this.input.skipBytes(this.input.readableBytes());
                return Flux.error(new IllegalStateException("Corrupted stream"));
            }
            if (this.writerIndex > maxObjectLength) {
                // buffer size exceeded maxObjectLength; discarding the complete buffer.
                this.input.skipBytes(this.input.readableBytes());
                reset();
                return Flux.error(new IllegalStateException("object length exceeds " + maxObjectLength + ": "
                        + this.writerIndex + " bytes discarded"));
            }
            for (/* use current index */; this.index < this.writerIndex; this.index++) {
                byte c = this.input.getByte(this.index);
                if (this.state == ST_DECODING_NORMAL) {
                    decodeByte(c, this.input, this.index);

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

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

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

                        // skip trailing spaces.
                        int idxNoSpaces = this.index - 1;
                        while (idxNoSpaces >= this.input.readerIndex()
                                && Character.isWhitespace(this.input.getByte(idxNoSpaces))) {

                            idxNoSpaces--;
                        }

                        ByteBuf json = extractObject(this.input, this.input.readerIndex(),
                                idxNoSpaces + 1 - this.input.readerIndex());

                        if (json != null) {
                            chunks.add(allocator.wrap(json.nioBuffer()));
                        }

                        this.input.readerIndex(this.index + 1);

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

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

            if (this.input.readableBytes() == 0) {
                this.index = 0;
            }
            return Flux.fromIterable(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 input, int index) {
            if ((c == '{' || c == '[') && !this.insideString) {
                this.openBraces++;
            } else if ((c == '}' || c == ']') && !this.insideString) {
                this.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 (!this.insideString) {
                    this.insideString = true;
                    // If the double quote wasn't escaped then this is the end of a string.
                } else if (input.getByte(index - 1) != '\\') {
                    this.insideString = false;
                }
            }
        }

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

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

From source file:org.springframework.http.codec.json.JsonObjectDecoder.java

License:Apache License

@Override
public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType,
        Map<String, Object> hints) {

    return Flux.from(inputStream).flatMap(new Function<DataBuffer, Publisher<? extends DataBuffer>>() {

        int openBraces;
        int index;
        int state;
        boolean insideString;
        ByteBuf input;//  ww  w. j  a  v  a2 s .co  m
        Integer writerIndex;

        @Override
        public Publisher<? extends DataBuffer> apply(DataBuffer buffer) {
            List<DataBuffer> chunks = new ArrayList<>();
            if (this.input == null) {
                this.input = Unpooled.copiedBuffer(buffer.asByteBuffer());
                DataBufferUtils.release(buffer);
                this.writerIndex = this.input.writerIndex();
            } else {
                this.index = this.index - this.input.readerIndex();
                this.input = Unpooled.copiedBuffer(this.input, Unpooled.copiedBuffer(buffer.asByteBuffer()));
                DataBufferUtils.release(buffer);
                this.writerIndex = this.input.writerIndex();
            }
            if (this.state == ST_CORRUPTED) {
                this.input.skipBytes(this.input.readableBytes());
                return Flux.error(new IllegalStateException("Corrupted stream"));
            }
            if (this.writerIndex > maxObjectLength) {
                // buffer size exceeded maxObjectLength; discarding the complete buffer.
                this.input.skipBytes(this.input.readableBytes());
                reset();
                return Flux.error(new IllegalStateException("object length exceeds " + maxObjectLength + ": "
                        + this.writerIndex + " bytes discarded"));
            }
            DataBufferFactory dataBufferFactory = buffer.factory();
            for (/* use current index */; this.index < this.writerIndex; this.index++) {
                byte c = this.input.getByte(this.index);
                if (this.state == ST_DECODING_NORMAL) {
                    decodeByte(c, this.input, this.index);

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

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

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

                        // skip trailing spaces.
                        int idxNoSpaces = this.index - 1;
                        while (idxNoSpaces >= this.input.readerIndex()
                                && Character.isWhitespace(this.input.getByte(idxNoSpaces))) {

                            idxNoSpaces--;
                        }

                        ByteBuf json = extractObject(this.input, this.input.readerIndex(),
                                idxNoSpaces + 1 - this.input.readerIndex());

                        if (json != null) {
                            chunks.add(dataBufferFactory.wrap(json.nioBuffer()));
                        }

                        this.input.readerIndex(this.index + 1);

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

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

            return Flux.fromIterable(chunks);
        }

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

        private void decodeByte(byte c, ByteBuf input, int index) {
            if ((c == '{' || c == '[') && !this.insideString) {
                this.openBraces++;
            } else if ((c == '}' || c == ']') && !this.insideString) {
                this.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 (!this.insideString) {
                    this.insideString = true;
                    // If the double quote wasn't escaped then this is the end of a string.
                } else if (input.getByte(index - 1) != '\\') {
                    this.insideString = false;
                }
            }
        }

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

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

From source file:org.springframework.messaging.rsocket.MetadataEncoder.java

License:Apache License

private DataBuffer asDataBuffer(ByteBuf byteBuf) {
    if (bufferFactory() instanceof NettyDataBufferFactory) {
        return ((NettyDataBufferFactory) bufferFactory()).wrap(byteBuf);
    } else {/*from w  w  w.jav  a2 s  .  c  o m*/
        DataBuffer buffer = bufferFactory().wrap(byteBuf.nioBuffer());
        byteBuf.release();
        return buffer;
    }
}

From source file:org.springframework.messaging.tcp.reactor.AbstractNioBufferReactorNettyCodec.java

License:Apache License

@Override
public Collection<Message<P>> decode(ByteBuf inputBuffer) {
    ByteBuffer nioBuffer = inputBuffer.nioBuffer();
    int start = nioBuffer.position();
    List<Message<P>> messages = decodeInternal(nioBuffer);
    inputBuffer.skipBytes(nioBuffer.position() - start);
    return messages;
}

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  www. ja v  a 2  s  .  co 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.stem.client.MetaStoreClient.java

License:Apache License

private ByteBuffer buildMeta(int fatFileIndex, int offset, int length) {
    ByteBuf b = Unpooled.buffer(12);
    b.writeInt(fatFileIndex);//from   w w w  . ja  va 2  s. c om
    b.writeInt(offset);
    b.writeInt(length);

    return b.nioBuffer();
}

From source file:org.traccar.database.MediaManager.java

License:Apache License

public String writeFile(String uniqueId, ByteBuf buf, String extension) {
    if (path != null) {
        int size = buf.readableBytes();
        String name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "." + extension;
        try (FileOutputStream output = new FileOutputStream(createFile(uniqueId, name));
                FileChannel fileChannel = output.getChannel()) {
            ByteBuffer byteBuffer = buf.nioBuffer();
            int written = 0;
            while (written < size) {
                written += fileChannel.write(byteBuffer);
            }//from   w ww  .j  a  v  a  2 s  . c  o  m
            fileChannel.force(false);
            return name;
        } catch (IOException e) {
            LOGGER.warn("Save media file error", e);
        }
    }
    return null;
}

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

License:Apache License

private Position decodeTelemetry(Channel channel, SocketAddress remoteAddress, DeviceSession deviceSession,
        ByteBuf buf) {/*from  w ww.j  ava 2s.c om*/

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

    position.setTime(new Date(1009843200000L + buf.readUnsignedIntLE() * 1000)); // seconds since 2002
    position.setLatitude(buf.readIntLE() * 0.0000001);
    position.setLongitude(buf.readIntLE() * 0.0000001);

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

    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE()));
    buf.readUnsignedShortLE(); // max speed

    position.set(Position.KEY_INPUT, buf.readUnsignedShortLE());
    buf.readUnsignedIntLE(); // di 3 count
    buf.readUnsignedIntLE(); // di 4 count

    for (int i = 0; i < 5; i++) {
        position.set(Position.PREFIX_ADC + (i + 1), buf.readUnsignedShortLE());
    }

    position.setCourse(buf.readUnsignedShortLE());

    position.set(Position.KEY_STATUS, buf.readUnsignedShortLE());
    position.set(Position.KEY_EVENT, buf.readUnsignedShortLE());
    position.set(Position.KEY_DRIVER_UNIQUE_ID, buf.readLongLE());

    int index = buf.readUnsignedShortLE();

    buf.readUnsignedShortLE(); // checksum

    if (channel != null) {
        ByteBuf response = Unpooled.buffer();
        response.writeInt(0xF1F1F1F1); // sync
        response.writeByte(MSG_TELEMETRY_CONFIRM);
        response.writeShortLE(2); // length
        response.writeShortLE(index);
        response.writeShort(Checksum.crc16(Checksum.CRC16_XMODEM, response.nioBuffer()));
        channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
    }

    return position;
}

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

License:Apache License

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

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

    buf.skipBytes(4); // sync
    int type = buf.readUnsignedByte();
    buf.readUnsignedShortLE(); // length

    switch (type) {
    case MSG_LOGIN_REQUEST:
        String imei = ByteBufUtil.hexDump(buf.readBytes(8));
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
        if (deviceSession == null) {
            return null;
        }
        int fuelConst = buf.readUnsignedShortLE();
        int tripConst = buf.readUnsignedShortLE();
        if (channel != null) {
            ByteBuf response = Unpooled.buffer();
            response.writeInt(0xF1F1F1F1); // sync
            response.writeByte(MSG_LOGIN_CONFIRM);
            response.writeShortLE(12); // length
            response.writeBytes(ByteBufUtil.decodeHexDump(imei));
            response.writeShortLE(fuelConst);
            response.writeShortLE(tripConst);
            response.writeShort(Checksum.crc16(Checksum.CRC16_XMODEM, response.nioBuffer()));
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
        return null;
    case MSG_TELEMETRY_1:
    case MSG_TELEMETRY_2:
    case MSG_TELEMETRY_3:
        deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }
        return decodeTelemetry(channel, remoteAddress, deviceSession, buf);
    default:
        return null;
    }
}

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

License:Apache License

@Override
protected Object encodeCommand(Command command) {

    if (command.getType().equals(Command.TYPE_OUTPUT_CONTROL)) {
        ByteBuf buf = Unpooled.buffer();

        buf.writeLongLE(Long.parseLong(getUniqueId(command.getDeviceId())));
        buf.writeShortLE(1 + 1 + 3 + 1); // length
        buf.writeByte(BceProtocolDecoder.MSG_OUTPUT_CONTROL);
        buf.writeByte(command.getInteger(Command.KEY_INDEX) == 1 ? 0x0A : 0x0B);
        buf.writeByte(0xFF); // index
        buf.writeByte(0x00); // form id
        buf.writeShortLE(Integer.parseInt(command.getString(Command.KEY_DATA)) > 0 ? 0x0055 : 0x0000);
        buf.writeByte(Checksum.sum(buf.nioBuffer()));

        return buf;
    } else {//from  ww  w . j a v a  2s.  c o m
        return null;
    }
}