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:openbns.commons.net.codec.sts.HttpObjectDecoder.java

License:Apache License

private static void skipControlCharacters(ByteBuf buffer) {
    for (;;) {/*from   w w  w. ja v a 2s . c om*/
        char c = (char) buffer.readUnsignedByte();
        if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
            buffer.readerIndex(buffer.readerIndex() - 1);
            break;
        }
    }
}

From source file:org.aotorrent.common.protocol.peer.HandshakeRequest.java

License:Apache License

public HandshakeRequest(ByteBuf message) throws UnsupportedEncodingException {
    int protocolStringLength = message.readUnsignedByte();
    byte[] protocolStringBytes = new byte[protocolStringLength];

    message.readBytes(protocolStringLength);

    this.protocolString = new String(protocolStringBytes, Torrent.DEFAULT_TORRENT_ENCODING);

    this.reserved = new byte[8];

    message.readBytes(this.reserved);

    this.infoHash = new byte[Torrent.INFO_HASH_LENGTH];

    message.readBytes(this.infoHash);

    this.peerId = new byte[Torrent.PEER_ID_LENGTH];

    message.readBytes(this.peerId);
}

From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlockAwareSegmentInputStreamImpl.java

License:Apache License

private int readEntries() throws IOException {
    checkState(bytesReadOffset >= DataBlockHeaderImpl.getDataStartOffset());
    checkState(bytesReadOffset < blockSize);

    // once reach the end of entry buffer, read more, if there is more
    if (bytesReadOffset < dataBlockFullOffset && entriesByteBuf.isEmpty()
            && startEntryId + blockEntryCount <= ledger.getLastAddConfirmed()) {
        entriesByteBuf = readNextEntriesFromLedger(startEntryId + blockEntryCount, ENTRIES_PER_READ);
    }/*from  w  w  w .j  av  a2  s  .co m*/

    if (!entriesByteBuf.isEmpty() && bytesReadOffset + entriesByteBuf.get(0).readableBytes() <= blockSize) {
        // always read from the first ByteBuf in the list, once read all of its content remove it.
        ByteBuf entryByteBuf = entriesByteBuf.get(0);
        int ret = entryByteBuf.readUnsignedByte();
        bytesReadOffset++;

        if (entryByteBuf.readableBytes() == 0) {
            entryByteBuf.release();
            entriesByteBuf.remove(0);
            blockEntryCount++;
        }

        return ret;
    } else {
        // no space for a new entry or there are no more entries
        // set data block full, return end padding
        if (dataBlockFullOffset == blockSize) {
            dataBlockFullOffset = bytesReadOffset;
        }
        return BLOCK_END_PADDING[(bytesReadOffset++ - dataBlockFullOffset) % BLOCK_END_PADDING.length];
    }
}

From source file:org.ballerinalang.net.grpc.CompositeContent.java

License:Open Source License

public int readUnsignedByte() {
    ReadOperation op = new ReadOperation() {
        @Override//from   ww w.  j  ava 2  s .c o  m
        int readInternal(ByteBuf buffer, int length) {

            return buffer.readUnsignedByte();
        }
    };
    execute(op, 1);
    return op.value;
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {

    byteBuf.markReaderIndex();//from w  ww.  ja  v a 2  s.  c  om
    boolean repliedPing = true;

    try {
        short packetId = byteBuf.readUnsignedByte();
        if (packetId == 254) {
            int length = byteBuf.readableBytes();
            AsyncServerPingEvent asyncServerPingEvent = EventFactory
                    .callAsyncServerPingEvent(this.server.createServerPing());
            if (asyncServerPingEvent.getPing() != null) {
                switch (length) {
                case 0:
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("%s%d%d",
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                case 1:
                    if (byteBuf.readUnsignedByte() != 1) {
                        return;
                    }
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                default:
                    boolean checkFlag = byteBuf.readUnsignedByte() == 1;
                    checkFlag &= byteBuf.readUnsignedByte() == 250;
                    checkFlag &= "MC|PingHost".equals(
                            new String(byteBuf.readBytes(byteBuf.readShort() * 2).array(), Charsets.UTF_16));

                    int checkShort = byteBuf.readShort();

                    checkFlag &= byteBuf.readUnsignedByte() >= 73;
                    checkFlag &= 3 + byteBuf.readBytes(byteBuf.readShort() * 2).array().length
                            + 4 == checkShort;
                    checkFlag &= byteBuf.readInt() <= '\uffff';
                    checkFlag &= byteBuf.readableBytes() == 0;

                    if (!checkFlag) {
                        return;
                    }

                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                }
            } else {
                this.close(channelHandlerContext);
            }
            repliedPing = false;
        } else if (packetId == 0x02 && byteBuf.isReadable()) {
            this.sendPingAndClose(channelHandlerContext, this.toArray(ChatColor.RED + "Outdated Client"));
            repliedPing = false;
        }
    } catch (Exception e) {
        return;
    } finally {
        if (repliedPing) {
            byteBuf.resetReaderIndex();
            channelHandlerContext.channel().pipeline().remove("legacy_ping");
            channelHandlerContext.fireChannelRead(byteBuf.retain());
        }
    }
}

From source file:org.bgp4j.netty.NLRICodec.java

License:Apache License

/**
 * Decode a network-layer reachability information from a byte buffer
 * // w w  w  .j  ava2s.  co  m
 * @param buffer byte buffer
 * @return decoded network layer reachability information
 */
public static NetworkLayerReachabilityInformation decodeNLRI(ByteBuf buffer) {
    NetworkLayerReachabilityInformation nlri = new NetworkLayerReachabilityInformation();
    int prefixLength = buffer.readUnsignedByte();
    byte[] prefixBytes = null;

    if (prefixLength > 0) {
        prefixBytes = new byte[NetworkLayerReachabilityInformation
                .calculateOctetsForPrefixLength(prefixLength)];

        buffer.readBytes(prefixBytes);
    }
    nlri.setPrefix(prefixLength, prefixBytes);

    return nlri;
}

From source file:org.bgp4j.netty.protocol.BGPv4PacketDecoder.java

License:Apache License

public BGPv4Packet decodePacket(ByteBuf buffer) {
    int type = buffer.readUnsignedByte();
    BGPv4Packet packet = null;/*from ww w  .jav  a 2 s.com*/

    switch (type) {
    case BGPv4Constants.BGP_PACKET_TYPE_OPEN:
        packet = openPacketDecoder.decodeOpenPacket(buffer);
        break;
    case BGPv4Constants.BGP_PACKET_TYPE_UPDATE:
        packet = updatePacketDecoder.decodeUpdatePacket(buffer);
        break;
    case BGPv4Constants.BGP_PACKET_TYPE_NOTIFICATION:
        packet = decodeNotificationPacket(buffer);
        break;
    case BGPv4Constants.BGP_PACKET_TYPE_KEEPALIVE:
        packet = decodeKeepalivePacket(buffer);
        break;
    case BGPv4Constants.BGP_PACKET_TYPE_ROUTE_REFRESH:
        packet = routeRefreshPacketDecoder.decodeRouteRefreshPacket(buffer);
        break;
    default:
        throw new BadMessageTypeException(type);
    }

    return packet;
}

From source file:org.bgp4j.netty.protocol.BGPv4PacketDecoder.java

License:Apache License

/**
 * decode the NOTIFICATION network packet. The NOTIFICATION packet must be at least 2 octets large at this point.
 * //from   ww w .j a  va 2  s  .c o  m
 * @param buffer the buffer containing the data. 
 * @return
 */
private BGPv4Packet decodeNotificationPacket(ByteBuf buffer) {
    NotificationPacket packet = null;

    ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_NOTIFICATION, -1);

    int errorCode = buffer.readUnsignedByte();
    int errorSubcode = buffer.readUnsignedByte();

    switch (errorCode) {
    case BGPv4Constants.BGP_ERROR_CODE_MESSAGE_HEADER:
        packet = decodeMessageHeaderNotificationPacket(buffer, errorSubcode);
        break;
    case BGPv4Constants.BGP_ERROR_CODE_OPEN:
        packet = openPacketDecoder.decodeOpenNotificationPacket(buffer, errorSubcode);
        break;
    case BGPv4Constants.BGP_ERROR_CODE_UPDATE:
        packet = updatePacketDecoder.decodeUpdateNotification(buffer, errorSubcode);
        break;
    case BGPv4Constants.BGP_ERROR_CODE_HOLD_TIMER_EXPIRED:
        packet = new HoldTimerExpiredNotificationPacket();
        break;
    case BGPv4Constants.BGP_ERROR_CODE_FINITE_STATE_MACHINE_ERROR:
        packet = new FiniteStateMachineErrorNotificationPacket();
        break;
    case BGPv4Constants.BGP_ERROR_CODE_CEASE:
        packet = decodeCeaseNotificationPacket(buffer, errorSubcode);
        break;
    }

    return packet;
}

From source file:org.bgp4j.netty.protocol.BGPv4PacketDecoder.java

License:Apache License

/**
 * decode the NOTIFICATION network packet for error code "Message Header Error". 
 * //from   w  w  w . ja v  a 2s .  co  m
 * @param buffer the buffer containing the data. 
 * @return
 */
private NotificationPacket decodeMessageHeaderNotificationPacket(ByteBuf buffer, int errorSubcode) {
    NotificationPacket packet = null;

    switch (errorSubcode) {
    case MessageHeaderErrorNotificationPacket.SUBCODE_CONNECTION_NOT_SYNCHRONIZED:
        packet = new ConnectionNotSynchronizedNotificationPacket();
        break;
    case MessageHeaderErrorNotificationPacket.SUBCODE_BAD_MESSAGE_LENGTH:
        packet = new BadMessageLengthNotificationPacket(buffer.readUnsignedShort());
        break;
    case MessageHeaderErrorNotificationPacket.SUBCODE_BAD_MESSAGE_TYPE:
        packet = new BadMessageTypeNotificationPacket(buffer.readUnsignedByte());
        break;
    }

    return packet;
}

From source file:org.bgp4j.netty.protocol.BGPv4PacketDecoder.java

License:Apache License

/**
 * decode the NOTIFICATION network packet for error code "Cease". 
 * //from  w ww.j  av  a2 s . com
 * @param buffer the buffer containing the data. 
 * @return
 */
private NotificationPacket decodeCeaseNotificationPacket(ByteBuf buffer, int errorSubcode) {
    NotificationPacket packet = null;

    switch (errorSubcode) {
    default:
        log.info("cannot handle cease notification subcode {}", errorSubcode);
    case CeaseNotificationPacket.SUBCODE_UNSPECIFIC:
        packet = new UnspecifiedCeaseNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_MAXIMUM_NUMBER_OF_PREFIXES_REACHED:
        packet = new MaximumNumberOfPrefixesReachedNotificationPacket();

        try {
            AddressFamily afi = AddressFamily.fromCode(buffer.readUnsignedShort());
            SubsequentAddressFamily safi = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte());
            int prefixUpperBounds = (int) buffer.readUnsignedInt();

            packet = new MaximumNumberOfPrefixesReachedNotificationPacket(afi, safi, prefixUpperBounds);
        } catch (RuntimeException e) {
            log.info("cannot decode specific reason for CEASE maximum number of prefixes reached notification",
                    e);
        }
        break;
    case CeaseNotificationPacket.SUBCODE_ADMINSTRATIVE_SHUTDOWN:
        packet = new AdministrativeShutdownNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_PEER_DECONFIGURED:
        packet = new PeerDeconfiguredNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_ADMINSTRATIVE_RESET:
        packet = new AdministrativeResetNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_CONNECTION_REJECTED:
        packet = new ConnectionRejectedNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_OTHER_CONFIGURATION_CHANGE:
        packet = new OtherConfigurationChangeNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_CONNECTION_COLLISION_RESOLUTION:
        packet = new ConnectionCollisionResolutionNotificationPacket();
        break;
    case CeaseNotificationPacket.SUBCODE_OUT_OF_RESOURCES:
        packet = new OutOfResourcesNotificationPacket();
        break;
    }

    return packet;
}