Example usage for io.netty.buffer ByteBuf readUnsignedByte

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

Introduction

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

Prototype

public abstract short readUnsignedByte();

Source Link

Document

Gets an unsigned byte at the current readerIndex and increases the readerIndex by 1 in this buffer.

Usage

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private ASPathAttribute decodeASPathAttribute(ByteBuf buffer, ASType asType) {
    ASPathAttribute attr = new ASPathAttribute(asType);

    while (buffer.isReadable()) {
        if (buffer.readableBytes() < 2)
            throw new MalformedASPathAttributeException();

        int segmentType = buffer.readUnsignedByte();
        int pathLength = buffer.readUnsignedByte();
        int pathOctetLength = (pathLength * (asType == ASType.AS_NUMBER_4OCTETS ? 4 : 2));

        if (buffer.readableBytes() < pathOctetLength)
            throw new MalformedASPathAttributeException();

        PathSegment segment = new PathSegment(asType);

        try {/*from   w  w  w.  j av  a  2s . c  om*/
            segment.setPathSegmentType(PathSegmentTypeCodec.fromCode(segmentType));
        } catch (IllegalArgumentException e) {
            log.error("cannot convert AS_PATH type", e);

            throw new MalformedASPathAttributeException();
        }

        for (int i = 0; i < pathLength; i++) {
            if (asType == ASType.AS_NUMBER_4OCTETS)
                segment.getAses().add((int) buffer.readUnsignedInt());
            else
                segment.getAses().add(buffer.readUnsignedShort());
        }

        attr.getPathSegments().add(segment);
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private OriginPathAttribute decodeOriginPathAttribute(ByteBuf buffer) {
    OriginPathAttribute attr = new OriginPathAttribute();

    if (buffer.readableBytes() != 1)
        throw new AttributeLengthException();

    try {//from w w w  . j  a  va 2s.  com
        attr.setOrigin(OriginCodec.fromCode(buffer.readUnsignedByte()));
    } catch (IllegalArgumentException e) {
        log.error("cannot convert ORIGIN code", e);

        throw new InvalidOriginException();
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private MultiProtocolReachableNLRI decodeMpReachNlriPathAttribute(ByteBuf buffer) {
    MultiProtocolReachableNLRI attr = new MultiProtocolReachableNLRI();

    try {//  w  w  w . j a  v  a  2s  . c om
        attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
        attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

        int nextHopLength = buffer.readUnsignedByte();

        if (nextHopLength > 0) {
            byte[] nextHop = new byte[nextHopLength];

            buffer.readBytes(nextHop);
            attr.setNextHopAddress(nextHop);
        }

        buffer.readByte(); // reserved

        while (buffer.isReadable()) {
            attr.getNlris().add(NLRICodec.decodeNLRI(buffer));
        }
    } catch (RuntimeException e) {
        log.error("failed to decode MP_REACH_NLRI path attribute", e);

        throw new OptionalAttributeErrorException();
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private MultiProtocolUnreachableNLRI decodeMpUnreachNlriPathAttribute(ByteBuf buffer) {
    MultiProtocolUnreachableNLRI attr = new MultiProtocolUnreachableNLRI();

    try {// w  ww.  ja  va  2 s .c  om
        attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
        attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

        while (buffer.isReadable()) {
            attr.getNlris().add(NLRICodec.decodeNLRI(buffer));
        }
    } catch (RuntimeException e) {
        log.error("failed to decode MP_UNREACH_NLRI path attribute", e);

        throw new OptionalAttributeErrorException();
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private List<PathAttribute> decodePathAttributes(ByteBuf buffer) {
    List<PathAttribute> attributes = new LinkedList<PathAttribute>();

    while (buffer.isReadable()) {
        buffer.markReaderIndex();//w ww . j  av  a 2  s. c  om

        try {
            int flagsType = buffer.readUnsignedShort();
            boolean optional = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_OPTIONAL_BIT) != 0);
            boolean transitive = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TRANSITIVE_BIT) != 0);
            boolean partial = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_PARTIAL_BIT) != 0);
            int typeCode = (flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MASK);
            int valueLength = 0;

            if ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_EXTENDED_LENGTH_BIT) != 0)
                valueLength = buffer.readUnsignedShort();
            else
                valueLength = buffer.readUnsignedByte();

            ByteBuf valueBuffer = buffer.readSlice(valueLength);

            PathAttribute attr = null;

            switch (typeCode) {
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ATOMIC_AGGREGATE:
                attr = decodeAtomicAggregatePathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_COMMUNITIES:
                attr = decodeCommunityPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_LOCAL_PREF:
                attr = decodeLocalPrefPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MULTI_EXIT_DISC:
                attr = decodeMultiExitDiscPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_NEXT_HOP:
                attr = decodeNextHopPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGIN:
                attr = decodeOriginPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_REACH_NLRI:
                attr = decodeMpReachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_UNREACH_NLRI:
                attr = decodeMpUnreachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGINATOR_ID:
                attr = decodeOriginatorIDPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_CLUSTER_LIST:
                attr = decodeClusterListPathAttribute(valueBuffer);
                break;
            default: {
                byte[] value = new byte[valueBuffer.readableBytes()];

                valueBuffer.readBytes(value);
                attr = new UnknownPathAttribute(typeCode, value);
            }
                break;
            }
            attr.setOptional(optional);
            attr.setTransitive(transitive);
            attr.setPartial(partial);

            attributes.add(attr);
        } catch (AttributeException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);
            ex.setOffendingAttribute(packet);

            throw ex;
        } catch (IndexOutOfBoundsException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);

            throw new AttributeLengthException(packet);
        }

    }

    return attributes;
}

From source file:org.clitherproject.clither.server.net.PacketDecoder.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from  www.  j av  a2 s . c o  m
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    ByteBuf buf = frame.content().order(ByteOrder.BIG_ENDIAN);
    if (buf.capacity() < 1) {
        // Discard empty messages
        return;
    }

    buf.resetReaderIndex();
    int packetId = buf.readUnsignedByte();
    Packet packet = PacketRegistry.SERVERBOUND.constructPacket(packetId);

    if (packet == null) {
        return;
    }

    ClitherServer.log.finest("Received packet " + " (" + packet.getClass().getSimpleName() + ") from "
            + ctx.channel().remoteAddress());

    packet.readData(buf);
    out.add(packet);
}

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);//  ww w. j a va2  s .  c  o  m
        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.message.InterrogationCommand.java

License:Open Source License

public static InterrogationCommand parse(final ProtocolOptions options, final byte length,
        final ASDUHeader header, final ByteBuf data) {
    final InformationObjectAddress informationObjectAddress = InformationObjectAddress.parse(options, data);
    final short qualifierOfInterrogation = data.readUnsignedByte();
    final InterrogationCommand result = new InterrogationCommand(header, informationObjectAddress,
            qualifierOfInterrogation);/*  w w w .ja v  a  2s .com*/
    return result;
}

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 .  j  a v a2 s .co 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.evilco.emulator.extension.chip8.Chip8Emulator.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  ww.j  a v a 2s.c  o  m*/
 */
@Override
public void load(ByteBuf romBuffer) throws RomException {
    getLogger().debug("ROM contains " + romBuffer.readableBytes() + " bytes of data.");

    // copy ROM to memory
    try {
        long index = 0x200;

        while ((romBuffer.readableBytes() > 0 && this.memory.isValidAddress((index)))) {
            this.memory.set(index, romBuffer.readUnsignedByte());
            index++;
        }
    } catch (MemoryException ex) {
        throw new RomLoaderException(ex);
    }

    // verify
    if (romBuffer.readableBytes() > 0)
        throw new InvalidRomSizeException(
                "Found an extra of " + romBuffer.readableBytes() + " bytes at the end of ROM file.");
}