Example usage for io.netty.buffer ByteBuf readUnsignedShort

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

Introduction

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

Prototype

public abstract int readUnsignedShort();

Source Link

Document

Gets an unsigned 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

From source file:org.eclipse.neoscada.protocol.iec60870.apci.APDUDecoder.java

License:Open Source License

private APCIBase decode(ByteBuf controlFields, final ByteBuf data) {
    logger.trace("Control Fields: {}", ByteBufUtil.hexDump(controlFields));

    controlFields = controlFields.order(ByteOrder.LITTLE_ENDIAN);

    final byte first = controlFields.getByte(0);
    if ((first & 0x01) == 0) {
        // I format
        final int sendSequenceNumber = controlFields.readUnsignedShort() >> 1;
        final int receiveSequenceNumber = controlFields.readUnsignedShort() >> 1;
        logger.debug("S: {}, R: {}", sendSequenceNumber, receiveSequenceNumber);
        return new InformationTransfer(sendSequenceNumber, receiveSequenceNumber, data);
    } else if ((first & 0x03) == 1) {
        // S format
        controlFields.skipBytes(2);/*from  w w  w . j a va  2 s .com*/
        final int receiveSequenceNumber = controlFields.readUnsignedShort() >> 1;
        return new Supervisory(receiveSequenceNumber);
    } else if ((first & 0x03) == 3) {
        // U format
        final Function function = convertFunction(controlFields.readUnsignedByte());
        return new UnnumberedControl(function);
    }

    // this should actually never happen

    throw new DecoderException("Invalid control fields");
}

From source file:org.eclipse.neoscada.protocol.iec60870.asdu.types.TypeHelper.java

License:Open Source License

public static long parseTimestamp(final ProtocolOptions options, final ByteBuf data) {
    final int ms = data.readUnsignedShort();

    int minutes = data.readUnsignedByte();
    minutes = minutes & 0b00111111; // mask out IV and RES1

    int hours = data.readUnsignedByte();
    hours = hours & 0b00011111; // mask out SU and RES2

    final int dayOfMonth = data.readUnsignedByte() & 0b00011111; // directly mask out dayOfWeek

    final int month = data.readUnsignedByte() & 0b00001111; // directly mask out RES3
    int year = data.readUnsignedByte() & 0b01111111; // directly mask out RES4

    /*/*w w w.java 2s .  c o m*/
     * This would be the right spot for another rant on time formats ...
     * ... we simply add 2000 here since:
     * a) we assume that the software and the other side run "now" and don't
     *    transmit historical data from before 2000.
     * b) we also assume this software will be changed some time before 2114
     *    to handle this case ... so either upgrade to a different protocol by then
     *    or start your project fixing this issue by 2070 ;-)
     */
    year = year + 2000;

    final Calendar c = new GregorianCalendar(options.getTimeZone());
    c.set(year, month - 1, dayOfMonth, hours, minutes, ms / 1_000);
    c.set(Calendar.MILLISECOND, ms % 1_000);
    return c.getTimeInMillis();
}

From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.CollectdPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, DatagramPacket packet, List<Object> out) throws Exception {
    long start = System.currentTimeMillis();
    ByteBuf content = packet.content();
    List<Part> parts = new ArrayList<>(100);
    for (;;) {/* w ww.j  a  v  a2  s  .com*/
        if (!hasReadableBytes(content, 4)) {
            break;
        }
        short partTypeId = content.readShort();
        PartType partType = PartType.findById(partTypeId);
        int partLength = content.readUnsignedShort();
        int valueLength = partLength - 4;
        if (!hasReadableBytes(content, valueLength)) {
            break;
        }
        if (partType == null) {
            content.skipBytes(valueLength);
            continue;
        }
        Part part;
        switch (partType) {
        case HOST:
        case PLUGIN:
        case PLUGIN_INSTANCE:
        case TYPE:
        case INSTANCE:
            part = new StringPart(partType, readStringPartContent(content, valueLength));
            break;
        case TIME:
        case TIME_HIGH_RESOLUTION:
        case INTERVAL:
        case INTERVAL_HIGH_RESOLUTION:
            part = new NumericPart(partType, readNumericPartContent(content));
            break;
        case VALUES:
            part = new ValuePart(partType, readValuePartContent(content, valueLength));
            break;
        default:
            part = null;
            content.skipBytes(valueLength);
        }
        //noinspection ConstantConditions
        if (part != null) {
            logger.trace("Decoded part: {}", part);
            parts.add(part);
        }
    }

    if (logger.isTraceEnabled()) {
        long stop = System.currentTimeMillis();
        logger.trace("Decoded datagram in {} ms", stop - start);
    }

    if (parts.size() > 0) {
        CollectdPacket collectdPacket = new CollectdPacket(parts);
        out.add(collectdPacket);
    } else {
        logger.debug("No parts decoded, no CollectdPacket output");
    }
}

From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.CollectdPacketDecoder.java

License:Apache License

private Values readValuePartContent(ByteBuf content, int length) {
    int beginIndex = content.readerIndex();
    int total = content.readUnsignedShort();
    List<DataType> dataTypes = new ArrayList<>(total);
    for (int i = 0; i < total; i++) {
        byte sampleTypeId = content.readByte();
        dataTypes.add(DataType.findById(sampleTypeId));
    }/* www .  ja v a  2 s .  c o m*/
    List<Number> data = new ArrayList<>(total);
    for (DataType dataType : dataTypes) {
        switch (dataType) {
        case COUNTER:
        case ABSOLUTE:
            byte[] valueBytes = new byte[8];
            content.readBytes(valueBytes);
            data.add(new BigInteger(1, valueBytes));
            break;
        case DERIVE:
            data.add(content.readLong());
            break;
        case GAUGE:
            data.add(Double.longBitsToDouble(ByteBufUtil.swapLong(content.readLong())));
            break;
        default:
            logger.debug("Skipping unknown data type: {}", dataType);
        }
    }
    // Skip any additionnal bytes
    int readCount = content.readerIndex() - beginIndex;
    if (length > readCount) {
        content.skipBytes(readCount - length);
    }
    return new Values(dataTypes, data);
}

From source file:org.inspirenxe.server.network.codec.handshake.HandshakeCodec.java

License:MIT License

@Override
public HandshakeMessage decode(ByteBuf buf) throws IOException {
    final int version = ByteBufUtils.readVarInt(buf);
    final String address = ByteBufUtils.readUTF8(buf);
    final short port = (short) buf.readUnsignedShort();
    final HandshakeState state = HandshakeState.get(ByteBufUtils.readVarInt(buf));
    return new HandshakeMessage(version, address, port, state);
}

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

License:Apache License

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

    if (colorBuf == null) {
        if (!in.isReadable(12)) {
            return false;
        }/*  ww  w.ja  v  a 2  s .c  o  m*/
        in.skipBytes(2);
        firstColor = in.readUnsignedShort();
        numberOfColor = in.readUnsignedShort();
        int size = numberOfColor - firstColor;
        colorBuf = Unpooled.buffer(size * 6, size * 6);
    }
    colorBuf.writeBytes(in);

    if (!colorBuf.isWritable()) {
        return out.add(new ColourMapEntriesEvent(firstColor, numberOfColor, colorBuf));
    }
    return false;
}

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 a va 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.FramebufferUpdateRectDecoder.java

License:Apache License

private boolean readRect(ChannelHandlerContext ctx, ByteBuf m, List<Object> out) {
    if (!m.isReadable(12)) {
        return false;
    }//from w  w  w  . j  a v  a  2s.c  o m
    int x = m.readUnsignedShort();
    int y = m.readUnsignedShort();
    int w = m.readUnsignedShort();
    int h = m.readUnsignedShort();
    int enc = m.readInt();

    rect = new FrameRect(x, y, w, h, Encoding.valueOf(enc));
    currentRect++;
    logger.debug("{}of{} - ({}) {}", currentRect, numberRects, rect, enc);

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

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient33Decoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (state()) {
    case SEC_TYPES:
        int type = in.readInt();
        SecurityType securityType = SecurityType.valueOf(type);
        logger.debug("supported security type: {}", securityType);
        checkpoint(securityType == SecurityType.VNC_Auth ? State.VNC_AUTH : State.SERVER_INIT);
        out.add(new SecurityTypesEvent(false, securityType));
        break;/*  ww w  . ja  va2s .  c  om*/
    case VNC_AUTH:
        byte[] challenge = new byte[16];
        in.readBytes(challenge);
        out.add(new VncAuthSecurityMessage(challenge));
        checkpoint(State.SEC_RESULT);
        break;
    case SEC_RESULT:
        int secResult = in.readInt();
        logger.debug("server login {}", secResult == 0 ? "succeed" : "failed");
        if (secResult == 1) {
            int length = in.readInt();
            if (length == 0) {
                out.add(new SecurityResultEvent(false, new ProtocolException("decode error message failed")));
                return;
            }
            byte[] text = new byte[length];
            in.readBytes(text);
            out.add(new SecurityResultEvent(false, new SecurityException(new String(text, ASCII))));
            return;
        }
        out.add(new SecurityResultEvent(true));
        checkpoint(State.SERVER_INIT);
        break;
    case SERVER_INIT:
        ServerInitEvent initMsg = new ServerInitEvent();

        initMsg.setFrameBufferWidth(in.readUnsignedShort());
        initMsg.setFrameBufferHeight(in.readUnsignedShort());

        initMsg.setPixelFormat(parsePixelFormat(in));

        byte[] name = new byte[in.readInt()];
        in.readBytes(name);

        initMsg.setServerName(new String(name, ASCII));
        out.add(initMsg);
        break;
    default:
        break;
    }
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient33Decoder.java

License:Apache License

protected PixelFormat parsePixelFormat(ByteBuf m) {

    PixelFormat pf = new PixelFormat();

    pf.setBitPerPixel(m.readUnsignedByte());
    pf.setDepth(m.readUnsignedByte());/*from  w  w w.  j a  v a  2s  .  c om*/
    pf.setBigEndian(m.readUnsignedByte() == 1);
    pf.setTrueColor(m.readUnsignedByte() == 1);
    pf.setRedMax(m.readUnsignedShort());
    pf.setGreenMax(m.readUnsignedShort());
    pf.setBlueMax(m.readUnsignedShort());

    pf.setRedShift(m.readUnsignedByte());
    pf.setGreenShift(m.readUnsignedByte());
    pf.setBlueShift(m.readUnsignedByte());
    m.skipBytes(3);

    return pf;
}