Example usage for io.netty.buffer ByteBuf readSlice

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

Introduction

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

Prototype

public abstract ByteBuf readSlice(int length);

Source Link

Document

Returns a new slice of this buffer's sub-region starting at the current readerIndex and increases the readerIndex by the size of the new slice (= length ).

Usage

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    buf.skipBytes(1); // header

    String id = ByteBufUtil.hexDump(buf.readSlice(6));
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
    if (deviceSession == null) {
        return null;
    }/*from  w w  w . j  a v a 2  s  . c om*/

    int type = buf.readUnsignedShort();
    buf.readUnsignedShort(); // length

    if (type == 0x2086 || type == 0x2084 || type == 0x2082) {

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

        buf.readUnsignedByte(); // data type
        buf.readUnsignedShort(); // trip id

        position.setTime(decodeDate(buf));

        position.setLatitude(decodeCoordinate(BcdUtil.readInteger(buf, 8)));
        position.setLongitude(decodeCoordinate(BcdUtil.readInteger(buf, 9)));

        int flags = buf.readUnsignedByte();
        position.setValid(BitUtil.check(flags, 0));
        if (!BitUtil.check(flags, 1)) {
            position.setLatitude(-position.getLatitude());
        }
        if (!BitUtil.check(flags, 2)) {
            position.setLongitude(-position.getLongitude());
        }

        position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
        position.setCourse(buf.readUnsignedByte() * 2);

        position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
        position.set(Position.KEY_RSSI, buf.readUnsignedByte());
        position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 1000);
        position.set(Position.KEY_STATUS, buf.readUnsignedInt());

        // additional data

        return position;

    } else if (type == 0x3088) {

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

        getLastLocation(position, null);

        buf.readUnsignedShort(); // trip id
        buf.skipBytes(8); // imei
        buf.skipBytes(8); // imsi

        position.set("tripStart", decodeDate(buf).getTime());
        position.set("tripEnd", decodeDate(buf).getTime());
        position.set("drivingTime", buf.readUnsignedShort());

        position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedInt());
        position.set(Position.KEY_ODOMETER_TRIP, buf.readUnsignedInt());

        position.set("maxSpeed", UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
        position.set("maxRpm", buf.readUnsignedShort());
        position.set("maxTemp", buf.readUnsignedByte() - 40);
        position.set("hardAccelerationCount", buf.readUnsignedByte());
        position.set("hardBrakingCount", buf.readUnsignedByte());

        for (String speedType : Arrays.asList("over", "high", "normal", "low")) {
            position.set(speedType + "SpeedTime", buf.readUnsignedShort());
            position.set(speedType + "SpeedDistance", buf.readUnsignedInt());
            position.set(speedType + "SpeedFuel", buf.readUnsignedInt());
        }

        position.set("idleTime", buf.readUnsignedShort());
        position.set("idleFuel", buf.readUnsignedInt());

        position.set("hardCorneringCount", buf.readUnsignedByte());
        position.set("overspeedCount", buf.readUnsignedByte());
        position.set("overheatCount", buf.readUnsignedShort());
        position.set("laneChangeCount", buf.readUnsignedByte());
        position.set("emergencyRefueling", buf.readUnsignedByte());

        return position;

    }

    return null;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    buf.skipBytes(1); // '[' header
    manufacturer = buf.readSlice(2).toString(StandardCharsets.US_ASCII);
    buf.skipBytes(1); // '*' delimiter

    int idIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*');
    String id = buf.readSlice(idIndex - buf.readerIndex()).toString(StandardCharsets.US_ASCII);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
    if (deviceSession == null) {
        return null;
    }//from w ww  .j av a2  s  . co  m

    buf.skipBytes(1); // '*' delimiter

    String index = null;
    int contentIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*');
    if (contentIndex + 5 < buf.writerIndex() && buf.getByte(contentIndex + 5) == '*'
            && buf.toString(contentIndex + 1, 4, StandardCharsets.US_ASCII).matches("\\p{XDigit}+")) {
        int indexLength = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '*') - buf.readerIndex();
        hasIndex = true;
        index = buf.readSlice(indexLength).toString(StandardCharsets.US_ASCII);
        buf.skipBytes(1); // '*' delimiter
    }

    buf.skipBytes(4); // length
    buf.skipBytes(1); // '*' delimiter

    buf.writerIndex(buf.writerIndex() - 1); // ']' ignore ending

    contentIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
    if (contentIndex < 0) {
        contentIndex = buf.writerIndex();
    }

    String type = buf.readSlice(contentIndex - buf.readerIndex()).toString(StandardCharsets.US_ASCII);

    if (contentIndex < buf.writerIndex()) {
        buf.readerIndex(contentIndex + 1);
    }

    if (type.equals("INIT")) {

        sendResponse(channel, id, index, "INIT,1");

    } else if (type.equals("LK")) {

        sendResponse(channel, id, index, "LK");

        if (buf.isReadable()) {
            String[] values = buf.toString(StandardCharsets.US_ASCII).split(",");
            if (values.length >= 3) {
                Position position = new Position(getProtocolName());
                position.setDeviceId(deviceSession.getDeviceId());

                getLastLocation(position, null);

                position.set(Position.KEY_BATTERY_LEVEL, Integer.parseInt(values[2]));

                return position;
            }
        }

    } else if (type.equals("UD") || type.equals("UD2") || type.equals("UD3") || type.equals("AL")
            || type.equals("WT")) {

        Position position = decodePosition(deviceSession, buf.toString(StandardCharsets.US_ASCII));

        if (type.equals("AL")) {
            if (position != null) {
                position.set(Position.KEY_ALARM, Position.ALARM_SOS);
            }
            sendResponse(channel, id, index, "AL");
        }

        return position;

    } else if (type.equals("TKQ")) {

        sendResponse(channel, id, index, "TKQ");

    } else if (type.equals("PULSE") || type.equals("heart") || type.equals("bphrt")) {

        if (buf.isReadable()) {

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

            getLastLocation(position, new Date());

            String[] values = buf.toString(StandardCharsets.US_ASCII).split(",");
            int valueIndex = 0;

            if (type.equals("bphrt")) {
                position.set("pressureHigh", values[valueIndex++]);
                position.set("pressureLow", values[valueIndex++]);
            }
            position.set(Position.KEY_HEART_RATE, Integer.parseInt(values[valueIndex]));

            return position;

        }

    } else if (type.equals("img")) {

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

        getLastLocation(position, null);

        int timeIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
        buf.readerIndex(timeIndex + 12 + 2);
        position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(id, buf, "jpg"));

        return position;

    } else if (type.equals("TK")) {

        if (buf.readableBytes() == 1) {
            byte result = buf.readByte();
            if (result != '1') {
                LOGGER.warn(type + "," + result);
            }
            return null;
        }

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

        getLastLocation(position, null);

        position.set(Position.KEY_AUDIO, Context.getMediaManager().writeFile(id, buf, "amr"));

        return position;

    }

    return null;
}

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

License:Apache License

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

    ByteBuf buf = (ByteBuf) msg;

    byte[] format = null;
    if (formats.size() > 1) {
        format = formats.get(buf.getUnsignedByte(buf.readerIndex()));
    } else if (!formats.isEmpty()) {
        format = formats.values().iterator().next();
    }/*  w w w.  j  a  v  a2s  .c o  m*/

    if (format == null) {
        return null;
    }

    Position position = new Position(getProtocolName());

    for (byte tag : format) {
        switch (tag) {
        case 0x03:
            DeviceSession deviceSession = getDeviceSession(channel, remoteAddress,
                    String.valueOf(buf.readUnsignedInt()));
            if (deviceSession == null) {
                return null;
            }
            position.setDeviceId(deviceSession.getDeviceId());
            break;
        case 0x04:
            position.set(Position.KEY_EVENT, buf.readUnsignedByte());
            break;
        case 0x05:
            position.set(Position.KEY_INDEX, buf.readUnsignedShort());
            break;
        case 0x06:
            position.setTime(new Date(buf.readUnsignedInt() * 1000));
            break;
        case 0x07:
            position.setLatitude(buf.readInt() * 0.000001);
            break;
        case 0x08:
            position.setLongitude(buf.readInt() * 0.000001);
            break;
        case 0x09:
            position.setAltitude(buf.readShort() * 0.1);
            break;
        case 0x0a:
            position.setCourse(buf.readShort() * 0.1);
            break;
        case 0x0b:
            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte()));
            break;
        case 0x10:
            position.set(Position.KEY_ODOMETER_TRIP, buf.readUnsignedInt());
            break;
        case 0x12:
            position.set(Position.KEY_HDOP, buf.readUnsignedByte() * 0.1);
            break;
        case 0x13:
            position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
            break;
        case 0x14:
            position.set(Position.KEY_RSSI, buf.readShort());
            break;
        case 0x16:
            position.set(Position.KEY_BATTERY, buf.readUnsignedByte() * 0.1);
            break;
        case 0x17:
            position.set(Position.KEY_POWER, buf.readUnsignedByte() * 0.1);
            break;
        case 0x57:
            position.set(Position.KEY_OBD_SPEED, UnitsConverter.knotsFromKph(buf.readUnsignedShort()));
            break;
        case 0x65:
            position.set(Position.KEY_VIN, buf.readSlice(17).toString(StandardCharsets.US_ASCII));
            break;
        case 0x73:
            position.set(Position.KEY_VERSION_FW, buf.readSlice(16).toString(StandardCharsets.US_ASCII).trim());
            break;
        default:
            buf.skipBytes(getTagLength(tag));
            break;
        }
    }

    if (position.getLatitude() != 0 && position.getLongitude() != 0) {
        position.setValid(true);
    } else {
        getLastLocation(position, position.getDeviceTime());
    }

    return position;
}

From source file:org.waarp.openr66.protocol.localhandler.packet.DataPacket.java

License:Open Source License

/**
 * @param headerLength/*from   w w w .j av a  2s.  co  m*/
 * @param middleLength
 * @param endLength
 * @param buf
 * @return the new DataPacket from buffer
 * @throws OpenR66ProtocolPacketException
 */
public static DataPacket createFromBuffer(int headerLength, int middleLength, int endLength, ByteBuf buf)
        throws OpenR66ProtocolPacketException {
    if (headerLength - 1 <= 0) {
        throw new OpenR66ProtocolPacketException("Not enough data");
    }
    if (middleLength <= 0) {
        throw new OpenR66ProtocolPacketException("Not enough data");
    }
    int packetRank = buf.readInt();
    ByteBuf data = buf.readSlice(middleLength);
    data.retain();
    ByteBuf key;
    if (endLength > 0) {
        key = buf.readSlice(endLength);
        key.retain();
    } else {
        key = Unpooled.EMPTY_BUFFER;
    }
    return new DataPacket(packetRank, data, key);
}

From source file:org.wso2.carbon.mss.internal.router.TestHandler.java

License:Open Source License

@Path("/chunk")
@POST//from   ww  w.ja va  2 s. c  om
public void chunk(HttpRequest request, HttpResponder responder) throws IOException {
    // Echo the POST body of size 1 byte chunk
    ByteBuf content = ((FullHttpRequest) request).content();
    ChunkResponder chunker = responder.sendChunkStart(HttpResponseStatus.OK, null);
    while (content.isReadable()) {
        chunker.sendChunk(content.readSlice(1));
    }
    chunker.close();
}

From source file:qunar.tc.qmq.delay.receiver.ReceivedDelayMessageProcessor.java

License:Apache License

private RawMessageExtend doDeserializeRawMessagesExtend(ByteBuf body) {
    body.markReaderIndex();/*from w w w.j  a v a 2s.  c  o m*/
    int headerStart = body.readerIndex();
    long bodyCrc = body.readLong();
    MessageHeader header = deserializeMessageHeader(body);
    header.setBodyCrc(bodyCrc);
    int bodyLen = body.readInt();
    int headerLen = body.readerIndex() - headerStart;
    int totalLen = headerLen + bodyLen;

    body.resetReaderIndex();
    ByteBuf messageBuf = body.readSlice(totalLen);
    // client config error,prefer to send after ten second
    long scheduleTime = System.currentTimeMillis() + 10000;
    if (Flags.isDelay(header.getFlag())) {
        scheduleTime = header.getExpireTime();
    }

    return new RawMessageExtend(header, messageBuf, messageBuf.readableBytes(), scheduleTime);
}

From source file:qunar.tc.qmq.netty.DecodeHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list)
        throws Exception {
    if (in.readableBytes() < RemotingHeader.MIN_HEADER_SIZE + RemotingHeader.LENGTH_FIELD)
        return;/* w  w w.  j  a v  a2  s  . c  om*/

    int magicCode = in.getInt(in.readerIndex() + RemotingHeader.LENGTH_FIELD);
    if (DEFAULT_MAGIC_CODE != magicCode) {
        throw new IOException("Illegal Data, MagicCode=" + Integer.toHexString(magicCode));
    }

    in.markReaderIndex();
    int total = in.readInt();
    if (in.readableBytes() < total) {
        in.resetReaderIndex();
        return;
    }

    short headerSize = in.readShort();
    RemotingHeader remotingHeader = decodeHeader(in);

    int bodyLength = total - headerSize - RemotingHeader.HEADER_SIZE_LEN;

    RemotingCommand remotingCommand = new RemotingCommand();
    //because netty(lower version) has memory leak when ByteBuf cross thread
    //We can ensure server use high version netty, bu we can't ensure client
    if (isServer) {
        ByteBuf bodyData = in.readSlice(bodyLength);
        bodyData.retain();
        remotingCommand.setBody(bodyData);
    } else {
        ByteBuf bodyData = Unpooled.buffer(bodyLength, bodyLength);
        in.readBytes(bodyData, bodyLength);
        remotingCommand.setBody(bodyData);
    }
    remotingCommand.setHeader(remotingHeader);
    list.add(remotingCommand);
}

From source file:qunar.tc.qmq.processor.SendMessageProcessor.java

License:Apache License

private RawMessage deserializeRawMessageWithCrc(ByteBuf body) {
    long bodyCrc = body.readLong();

    int headerStart = body.readerIndex();
    body.markReaderIndex();/*from  w  w  w  .j  a va  2  s.co m*/
    MessageHeader header = deserializeMessageHeader(body);
    header.setBodyCrc(bodyCrc);
    int bodyLen = body.readInt();
    int headerLen = body.readerIndex() - headerStart;

    int totalLen = headerLen + bodyLen;
    body.resetReaderIndex();
    ByteBuf messageBuf = body.readSlice(totalLen);
    return new RawMessage(header, messageBuf, totalLen);
}

From source file:starnubserver.servers.starbound.TCPProxyServerPacketDecoder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w ww.  jav a 2  s . c  o m
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (state()) {
    case READ_PACKET_ID: {
        packetIDIndex = in.readerIndex();
        byte packetId = in.getByte(packetIDIndex);
        packet = PACKET_POOL.get(packetId);
        checkpoint(DecoderState.READ_VLQ);
    }
    case READ_VLQ: {
        clearVLQ();
        int tempIndexMarker = packetIDIndex + 1;
        while (vlqLength <= 10) {
            int tmpByte = in.getByte(tempIndexMarker);
            payloadLength = (payloadLength << 7) | (tmpByte & 0x7f);
            vlqLength++;
            if ((tmpByte & 0x80) == 0) {
                break;
            }
            tempIndexMarker++;
        }
        if ((payloadLength & 1) == 0x00) {
            payloadLength = payloadLength >> 1;
        } else {
            payloadLength = -((payloadLength >> 1) + 1);
        }
        compressed = payloadLength < 0;
        if (compressed) {
            payloadLength = -payloadLength;
        }
        checkpoint(DecoderState.READ_PAYLOAD);
    }
    case READ_PAYLOAD: {
        if (packet != null) {
            HashSet<EventSubscription> hashSet = PACKET_EVENT_ROUTER.getEVENT_SUBSCRIPTION_MAP()
                    .get(packet.getClass());
            /* Handle Packet if there is an events handler for it, else do not create objects */
            if (hashSet != null) {
                in.skipBytes(1 + vlqLength);
                if (compressed) {
                    packet.read(Unpooled.wrappedBuffer(1, decompress(in.readBytes(payloadLength).array())));
                } else {
                    packet.read(in.readBytes(payloadLength));
                }
                for (EventSubscription<Packet> packetEventSubscription : hashSet) {
                    if (packet.isRecycle()) {
                        break;
                    }
                    packetEventSubscription.getEVENT_HANDLER().onEvent(packet);
                }
                /* Write packet out, if not recycling */
                if (!packet.isRecycle()) {
                    packet.routeToDestination();
                } else {
                    packet.resetRecycle();
                }
            } else {
                destinationCTX.writeAndFlush(in.readSlice(1 + vlqLength + payloadLength).retain(),
                        destinationCTX.voidPromise());
            }
        } else {
            destinationCTX.writeAndFlush(in.readSlice(1 + vlqLength + payloadLength).retain(),
                    destinationCTX.voidPromise());
        }
        checkpoint(DecoderState.READ_PACKET_ID);
        break;
    }
    default:
        throw new Error("Error Decoding - Reached the unreachable void.");
    }
}