Example usage for io.netty.buffer ByteBuf readableBytes

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

Introduction

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

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:com.ibasco.agql.protocols.valve.source.query.logger.SourceLogListenHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    ByteBuf data = msg.content();
    if (data.readableBytes() > 6 && data.readIntLE() == -1) {
        byte[] raw = new byte[data.readableBytes() - 2];
        data.readBytes(raw);/*from  w w  w .jav a 2s  . c  om*/
        data.skipBytes(2);
        //Pass to the callback
        if (logEventCallback != null)
            logEventCallback.accept(new SourceLogEntry(new String(raw, Charsets.UTF_8), msg.sender()));
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.packets.response.SourceInfoResponsePacket.java

License:Open Source License

@Override
public SourceServer toObject() {
    ByteBuf data = getPayloadBuffer();

    SourceServer server = new SourceServer();

    //Start Decoding
    server.setNetworkVersion(data.readByte());
    server.setName(readString(data));//from w w w .  j a  v a2s  . co  m
    server.setMapName(readString(data));
    server.setGameDirectory(readString(data));
    server.setGameDescription(readString(data));
    server.setAppId(data.readShortLE());
    server.setNumOfPlayers(data.readByte());
    server.setMaxPlayers(data.readByte());
    server.setNumOfBots(data.readByte());
    server.setDedicated(data.readByte() == 1);
    server.setOperatingSystem((char) data.readByte());
    server.setPasswordProtected(data.readByte() == 1);
    server.setSecure(data.readByte() == 1);
    server.setGameVersion(readString(data));

    if (data.readableBytes() > 0) {
        byte extraDataFlag = data.readByte();

        if ((extraDataFlag & EDF_GAME_PORT) != 0) {
            data.readShortLE(); //discard, we already know which port based on the sender address
        }

        if ((extraDataFlag & EDF_SERVER_ID) != 0) {
            //this.info.put("serverId", Long.reverseBytes((this.contentData.getInt() << 32) | this.contentData.getInt()));
            server.setServerId(data.readLongLE());
        }

        if ((extraDataFlag & EDF_SOURCE_TV) != 0) {
            server.setTvPort(data.readShortLE());
            server.setTvName(readString(data));
        }

        if ((extraDataFlag & EDF_SERVER_TAGS) != 0) {
            server.setServerTags(readString(data));
        }

        if ((extraDataFlag & EDF_GAME_ID) != 0) {
            server.setGameId(data.readLongLE());
            //this.info.put("gameId", Long.reverseBytes((this.contentData.getInt() << 32) | this.contentData.getInt()));
        }
    }

    return server;
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java

License:Open Source License

@Override
public <T extends SourceServerPacket> T construct(ByteBuf data) {
    //Mark Index/*  w w w . ja v a  2s  .  c o  m*/
    data.markReaderIndex();

    try {
        //Reset the index
        data.readerIndex(0);

        //Verify size
        if (data.readableBytes() < 5)
            throw new IllegalStateException(
                    "Cannot continue processing buffer with less than or equal to 4 bytes");

        //Read protocol header
        int protocolHeader = data.readIntLE();

        //Check if this is a split packet
        if (protocolHeader == 0xFFFFFFFE)
            throw new IllegalStateException("Cannot construct a response from a partial/split packet.");

        //Verify that we have a valid header
        if (protocolHeader != 0xFFFFFFFF)
            throw new IllegalStateException("Protocol header not supported.");

        //Read packet header
        byte packetHeader = data.readByte();

        //Read payload
        byte[] payload = new byte[data.readableBytes()];
        data.readBytes(payload);

        //Verify if packet header is valid
        SourceServerPacket packet = createResponsePacketFromHeader(packetHeader);

        //If packet is empty, means the supplied packet header is not supported
        if (packet == null)
            return null;

        packet.setProtocolHeader(ByteUtils.byteArrayFromInteger(protocolHeader));
        packet.setHeader(packetHeader);
        packet.setPayload(payload);

        return (T) packet;
    } finally {
        data.resetReaderIndex();
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java

License:Open Source License

/**
 * Convert a source packet instance to it's byte representation
 *
 * @param packet The {@link SourceServerPacket} to convert
 *
 * @return Returns the deconstructed packet in byte array form
 *///from   w  ww.  j av  a2  s  .co  m
@Override
public byte[] deconstruct(SourceServerPacket packet) {
    if (packet == null)
        throw new IllegalArgumentException("Invalid packet specified in the arguments.");

    byte[] payload = packet.getPayload();
    byte[] protocolHeader = packet.getProtocolHeader();
    byte[] packetHeader = packet.getPacketHeader();

    int payloadSize = payload != null ? payload.length : 0;
    int protocolHeaderSize = protocolHeader != null ? protocolHeader.length : 0;
    int packetHeaderSize = packetHeader != null ? packetHeader.length : 0;
    int packetSize = protocolHeaderSize + packetHeaderSize + payloadSize;

    //Allocate our buffer
    final ByteBuf buf = createBuffer(packetSize);
    byte[] data;

    try {
        //Include Protocol Header if available
        if (protocolHeaderSize > 0)
            buf.writeBytes(protocolHeader);

        //Include Packet Header
        if (packetHeaderSize > 0)
            buf.writeBytes(packetHeader);

        //Include Payload (if available)
        if (payloadSize > 0)
            buf.writeBytes(payload);

        //Store the buffer into a byte array
        data = new byte[buf.readableBytes()];
        if (data.length > 0) {
            buf.readBytes(data);
        }
    } finally {
        buf.release();
    }

    log.debug("Constructing '{}' with total of {} bytes of data", packet.getClass().getSimpleName(),
            data.length);

    //Return the backing array representation
    return data;
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w w w  .j av a  2 s.  c om
public <T extends SourceRconPacket> T construct(ByteBuf data) {
    try {
        if (data.readableBytes() < 14) {
            log.warn("Packet is less than 10 bytes. Unsupported packet.");
            if (log.isDebugEnabled())
                log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data));
            return null;
        }

        //Remember the reader index
        data.markReaderIndex();

        //Read from the listen
        data.readerIndex(0);
        int size = data.readIntLE();
        int id = data.readIntLE();
        int type = data.readIntLE();

        String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString();

        SourceRconResponsePacket packet = getResponsePacket(type);

        if (packet != null) {
            //Ok, we have a valid response packet. Lets keep reading.
            packet.setId(id);
            packet.setSize(size);
            packet.setType(type);
            packet.setBody(body);
            return (T) packet;
        }
    } finally {
        //Reset the index
        data.resetReaderIndex();
    }
    return null;
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java

License:Open Source License

@Override
public byte[] deconstruct(SourceRconPacket packet) {
    //1) size = int (4 bytes)
    //2) id = int (4 bytes)
    //3) type = int (4 bytes)
    //4) body = string (length + 1 null byte)
    //5) trailer = null byte

    int id = packet.getId();
    int type = packet.getType();
    final String body = StringUtils.defaultString(packet.getBody());
    int packetSize = 10 + body.length();
    final ByteBuf buf = createBuffer(packetSize);
    byte[] data;/* ww w  .j  av  a  2 s .  co  m*/
    try {
        buf.writeIntLE(packetSize);
        buf.writeIntLE(id);
        buf.writeIntLE(type);
        buf.writeBytes(body.getBytes());
        buf.writeByte(0);
        buf.writeByte(0);
        data = new byte[buf.readableBytes()];
        buf.readBytes(data);
    } finally {
        buf.release();
    }
    return data;
}

From source file:com.ibasco.agql.protocols.valve.steam.master.MasterServerPacketBuilder.java

License:Open Source License

@Override
public <T extends MasterServerPacket> T construct(ByteBuf data) {
    //Mark Index/* w w  w . j ava 2s  .  c o m*/
    data.markReaderIndex();
    try {
        //Reset the index
        data.readerIndex(0);
        //Verify size
        if (data.readableBytes() <= 6)
            throw new IllegalStateException(
                    "Cannot continue processing buffer with less than or equal to 6 bytes");
        //Read header
        byte[] header = new byte[6];
        data.readBytes(header);
        //Read payload
        byte[] payload = new byte[data.readableBytes()];
        data.readBytes(payload);
        //Verify if packet header is valid
        MasterServerResponsePacket packet = new MasterServerResponsePacket();
        packet.setHeader(header);
        packet.setPayload(payload);
        return (T) packet;
    } finally {
        data.resetReaderIndex();
    }
}

From source file:com.ibasco.agql.protocols.valve.steam.master.MasterServerPacketBuilder.java

License:Open Source License

@Override
public byte[] deconstruct(MasterServerPacket packet) {
    if (packet == null)
        throw new IllegalArgumentException("Invalid packet specified in the arguments.");

    byte[] payload = packet.getPayload();
    byte[] packetHeader = packet.getPacketHeader();

    int payloadSize = payload != null ? payload.length : 0;
    int packetHeaderSize = packetHeader != null ? packetHeader.length : 0;
    int packetSize = packetHeaderSize + payloadSize;

    //Allocate our buffer
    final ByteBuf buf = createBuffer(packetSize);
    byte[] data;/*from w ww  . java  2s  .  c o  m*/

    try {
        //Include Packet Header
        if (packetHeaderSize > 0)
            buf.writeBytes(packetHeader);
        //Include Payload (if available)
        if (payloadSize > 0)
            buf.writeBytes(payload);
        //Store the buffer into a byte array
        data = new byte[buf.readableBytes()];
        if (data.length > 0) {
            buf.readBytes(data);
        }
    } finally {
        buf.release();
    }

    log.debug("Constructing '{}' with total of {} bytes of data", packet.getClass().getSimpleName(),
            data.length);

    //Return the backing array representation
    return data;
}

From source file:com.ibasco.agql.protocols.valve.steam.master.packets.MasterServerRequestPacket.java

License:Open Source License

@Override
public byte[] getPayload() {
    String filterString = this.filter.toString();
    int payloadSize = (3 + filterString.length() + (this.startIp.length()));
    final ByteBuf payload = PooledByteBufAllocator.DEFAULT.buffer(payloadSize);
    try {//ww  w  .j a v a  2  s  .co m
        payload.writeByte(getRegion());
        payload.writeBytes(getStartIp().getBytes());
        payload.writeByte(0); //terminating byte
        payload.writeBytes(filterString.getBytes());
        byte[] payloadBytes = new byte[payload.readableBytes()];
        payload.readBytes(payloadBytes);
        return payloadBytes;
    } finally {
        payload.release();
    }
}

From source file:com.ibasco.agql.protocols.valve.steam.master.packets.MasterServerResponsePacket.java

License:Open Source License

@Override
public Vector<InetSocketAddress> toObject() {
    ByteBuf data = getPayloadBuffer();

    //Clear the list
    servers.clear();//ww w .j  a  v  a 2  s.c  o m

    int firstOctet, secondOctet, thirdOctet, fourthOctet, portNumber;

    //Process the content containing list of source ips
    do {
        //Clear string
        ip.setLength(0);

        firstOctet = data.readByte() & 0xFF;
        secondOctet = data.readByte() & 0xFF;
        thirdOctet = data.readByte() & 0xFF;
        fourthOctet = data.readByte() & 0xFF;
        portNumber = data.readShort() & 0xFFFF;

        //Build our ip string
        ip.append(firstOctet).append(".").append(secondOctet).append(".").append(thirdOctet).append(".")
                .append(fourthOctet);

        //Add to the list
        servers.add(new InetSocketAddress(ip.toString(), portNumber));

        //Append port number
        ip.append(":").append(portNumber);
    } while (data.readableBytes() > 0);

    return servers;
}