Java Code Examples for io.netty.buffer.ByteBuf.isReadable()

The following are Jave code examples for showing how to use isReadable() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: angel   File: GetUDFResponse.java   Source Code and License Vote up 6 votes
@Override
public void deserialize(ByteBuf buf) {
  super.deserialize(buf);
  if (buf.isReadable()) {
    int size = buf.readInt();
    byte[] data = new byte[size];
    buf.readBytes(data);
    String partResultClassName = new String(data);
    try {
      partResult = (PartitionGetResult) Class.forName(partResultClassName).newInstance();
      partResult.deserialize(buf);
    } catch (Exception e) {
      LOG.fatal("deserialize PartitionAggrResult falied, ", e);
    }
  }
}
 
Example 2
Project: talchain   File: HandshakeHandler.java   Source Code and License Vote up 6 votes
private byte[] readEIP8Packet(ByteBuf buffer, byte[] plainPacket) {

        int size = bigEndianToShort(plainPacket);
        if (size < plainPacket.length)
            throw new IllegalArgumentException("AuthResponse packet size is too low");

        int bytesLeft = size - plainPacket.length + 2;
        byte[] restBytes = new byte[bytesLeft];

        if (!buffer.isReadable(restBytes.length))
            return null;

        buffer.readBytes(restBytes);

        byte[] fullResponse = new byte[size + 2];
        System.arraycopy(plainPacket, 0, fullResponse, 0, plainPacket.length);
        System.arraycopy(restBytes, 0, fullResponse, plainPacket.length, restBytes.length);

        return fullResponse;
    }
 
Example 3
Project: neoscada   File: SyslogCodec.java   Source Code and License Vote up 6 votes
private String[] decodeProcess ( final ByteBuf msg )
{
    // split by colon
    final int spaceIndex = msg.bytesBefore ( COLON );
    if ( spaceIndex < 0 )
    {
        throw new CodecException ( "Unable to find process name" );
    }

    final String process = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII );
    msg.skipBytes ( 1 ); // COLON
    if ( msg.isReadable () )
    {
        msg.skipBytes ( 1 ); // SPACE
    }

    final Matcher m = PROCESS_PATTERN.matcher ( process );
    if ( m.matches () )
    {
        return new String[] { m.group ( 1 ), m.group ( 2 ) };
    }

    return new String[] { process };
}
 
Example 4
Project: AppCoins-ethereumj   File: HandshakeHandler.java   Source Code and License Vote up 6 votes
private byte[] readEIP8Packet(ByteBuf buffer, byte[] plainPacket) {

        int size = bigEndianToShort(plainPacket);
        if (size < plainPacket.length)
            throw new IllegalArgumentException("AuthResponse packet size is too low");

        int bytesLeft = size - plainPacket.length + 2;
        byte[] restBytes = new byte[bytesLeft];

        if (!buffer.isReadable(restBytes.length))
            return null;

        buffer.readBytes(restBytes);

        byte[] fullResponse = new byte[size + 2];
        System.arraycopy(plainPacket, 0, fullResponse, 0, plainPacket.length);
        System.arraycopy(restBytes, 0, fullResponse, plainPacket.length, restBytes.length);

        return fullResponse;
    }
 
Example 5
Project: rskj   File: HandshakeHandler.java   Source Code and License Vote up 6 votes
private byte[] readEIP8Packet(ByteBuf buffer, byte[] plainPacket) {

        int size = bigEndianToShort(plainPacket);
        if (size < plainPacket.length) {
            throw new IllegalArgumentException("AuthResponse packet size is too low");
        }

        int bytesLeft = size - plainPacket.length + 2;
        byte[] restBytes = new byte[bytesLeft];

        if (!buffer.isReadable(restBytes.length)) {
            return null;
        }

        buffer.readBytes(restBytes);

        byte[] fullResponse = new byte[size + 2];
        System.arraycopy(plainPacket, 0, fullResponse, 0, plainPacket.length);
        System.arraycopy(restBytes, 0, fullResponse, plainPacket.length, restBytes.length);

        return fullResponse;
    }
 
Example 6
Project: L2J-Global   File: Crypt.java   Source Code and License Vote up 6 votes
@Override
public void decrypt(ByteBuf buf)
{
	if (!_isEnabled)
	{
		onPacketReceive(buf);
		return;
	}
	
	int a = 0;
	while (buf.isReadable())
	{
		final int b = buf.readByte() & 0xFF;
		buf.setByte(buf.readerIndex() - 1, b ^ _inKey[(buf.readerIndex() - 1) & 15] ^ a);
		a = b;
	}
	
	shiftKey(_inKey, buf.writerIndex());
	
	onPacketReceive(buf);
}
 
Example 7
Project: angel   File: PartitionGetParam.java   Source Code and License Vote up 5 votes
@Override
public void deserialize(ByteBuf buf) {
  matrixId = buf.readInt();
  if (buf.isReadable()) {
    if (partKey == null) {
      partKey = new PartitionKey();
    }

    partKey.deserialize(buf);
  }
}
 
Example 8
Project: UnknownPandaServer   File: PacketCodec.java   Source Code and License Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        throw new RuntimeException("Object is not a *ByteBuf");
    }

    ByteBuf data = (ByteBuf) msg;
    PacketSerializer serializer = new PacketSerializer(data);

    while (data.isReadable()) {
        packetCounter.incrementAndGet();
        int length = PacketSerializer.readVarInt(data);

        int packetID = serializer.readVarInt();
        Supplier<? extends Packet> packetSupplier = protocol.getServerboundPacketSupplier(packetID);

        if (packetSupplier == null) {
            UnknownPandaServer.getLogger().info("------ new Packet ------");
            UnknownPandaServer.getLogger().info("PacketCnt: " + packetCounter.get());
            UnknownPandaServer.getLogger().info("PacketID: 0x" + Integer.toHexString(packetID) + " w/ numeric: " + packetID);
            UnknownPandaServer.getLogger().info("Length: " + length);
            UnknownPandaServer.getLogger().info("Supplier: Unknown");
            serializer.clear();
            return;
        }

        Packet packet = packetSupplier.get();
        packet.packetId = packetID;
        packet.receive(serializer);

        super.channelRead(channelHandlerContext, packet);
    }

    data.release();
}
 
Example 9
Project: FlexMC   File: MessageSplitter.java   Source Code and License Vote up 5 votes
@Override
protected void decode( ChannelHandlerContext channelHandlerContext, ByteBuf input, List<Object> output ) throws Exception {
    input.markReaderIndex();

    byte[] bytes = new byte[3];
    for ( int i = 0; i < bytes.length; i++ ) {
        if ( !input.isReadable() ) {
            input.resetReaderIndex();
            return;
        }
        bytes[i] = input.readByte();
        if ( bytes[i] >= 0 ) {
            ByteBuf buf = Unpooled.wrappedBuffer( bytes );
            try {
                int j = Message.readVarInt( buf );
                if ( input.readableBytes() < j ) {
                    input.resetReaderIndex();
                    return;
                }
                output.add( input.readBytes( j ) );
                return;
            } finally {
                buf.release();
            }
        }
    }
    throw new CorruptedFrameException( "length wider than 21-bit" );
}
 
Example 10
Project: Quavo   File: ByteBufUtils.java   Source Code and License Vote up 5 votes
/**
 * Converts data from a {@link ByteBuf} into a readable jag string.
 *
 * @param buffer The {@link ByteBuf}.
 * @return The string.
 */
public static String readJagString(ByteBuf buffer) {
	StringBuilder bldr = new StringBuilder();
	byte b;
	buffer.readByte();
	while (buffer.isReadable() && (b = buffer.readByte()) != STRING_TERMINATOR) {
		bldr.append((char) b);
	}
	return bldr.toString();
}
 
Example 11
Project: Quavo   File: HandshakeDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (!in.isReadable() || in.readableBytes() < 4) {
		return;
	}

	out.add(new HandshakeRequest(this, in.readInt()));// version
}
 
Example 12
Project: L2J-Global   File: CryptCodec.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out)
{
	// Check if there are any data to encrypt.
	if (!msg.isReadable())
	{
		return;
	}
	
	msg.resetReaderIndex();
	_crypt.encrypt(msg);
	msg.resetReaderIndex();
	out.writeBytes(msg);
}
 
Example 13
Project: CustomWorldGen   File: FMLHandshakeMessage.java   Source Code and License Vote up 5 votes
@Override
public void fromBytes(ByteBuf buffer)
{
    this.hasMore = buffer.readBoolean();
    this.name = new ResourceLocation(ByteBufUtils.readUTF8String(buffer));

    int length = ByteBufUtils.readVarInt(buffer, 3);
    ids = Maps.newHashMap();

    for (int i = 0; i < length; i++)
    {
        ids.put(new ResourceLocation(ByteBufUtils.readUTF8String(buffer)), ByteBufUtils.readVarInt(buffer, 3));
    }

    length = ByteBufUtils.readVarInt(buffer, 3);
    substitutions = Sets.newHashSet();

    for (int i = 0; i < length; i++)
    {
        substitutions.add(new ResourceLocation(ByteBufUtils.readUTF8String(buffer)));
    }
    dummied = Sets.newHashSet();
    // if the dummied list isn't present - probably an older server
    if (!buffer.isReadable()) return;
    length = ByteBufUtils.readVarInt(buffer, 3);

    for (int i = 0; i < length; i++)
    {
        dummied.add(new ResourceLocation(ByteBufUtils.readUTF8String(buffer)));
    }
    //if (!buffer.isReadable()) return; // In case we expand
}
 
Example 14
Project: mqttserver   File: MqttMessageDecoder.java   Source Code and License Vote up 5 votes
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf buf,
		List<Object> out) throws Exception {
	if (buf.readableBytes() < 2) {
		return;
	}
	buf.markReaderIndex();
	buf.readByte(); // read away header
	int msgLength = 0;
	int multiplier = 1;
	int digit;
	int lengthSize = 0;
	do {
		lengthSize++;
		digit = buf.readByte();
		msgLength += (digit & 0x7f) * multiplier;
		multiplier *= 128;
		if ((digit & 0x80) > 0 && !buf.isReadable()) {
			buf.resetReaderIndex();
			return;
		}
	} while ((digit & 0x80) > 0);
	if (buf.readableBytes() < msgLength) {
		buf.resetReaderIndex();
		return;
	}
	byte[] data = new byte[1 + lengthSize + msgLength];
	buf.resetReaderIndex();
	buf.readBytes(data);
	MessageInputStream mis = new MessageInputStream(
			new ByteArrayInputStream(data));
	Message msg = mis.readMessage();
	mis.close();

	out.add(msg);
}
 
Example 15
Project: Quavo   File: GamePacketDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (!in.isReadable() || !player.getChannel().isRegistered()) {
		return;
	}
	int opcode = in.readUnsignedByte();
	Optional<PacketDecoderIdentifier> data = PacketDecoderIdentifier.getPacket(opcode);
	if (data.isPresent()) {
		PacketDecoderIdentifier packet = data.get();

		int size = packet.getSize();
		if (packet.getType() == PacketType.VARIABLE_BYTE) {
			if (in.readableBytes() < 1) {
				return;
			}
			size = in.readUnsignedByte();
		} else if (packet.getType() == PacketType.VARIABLE_SHORT) {
			if (in.readableBytes() < 2) {
				return;
			}
			size = in.readUnsignedShort();
		}

		if (in.readableBytes() >= size) {
			if (size < 0) {
				return;
			}

			byte[] bytes = new byte[size];
			in.readBytes(bytes, 0, size);
			out.add(new GamePacketRequest(this, player, packet.getId(), new GamePacketReader(Unpooled.wrappedBuffer(bytes))));
		}

	} else {
		System.out.println("No data present for incoming packet: " + opcode + ".");
		in.readBytes(new byte[in.readableBytes()]);
	}
}
 
Example 16
Project: http-proxy-netty   File: HttpProxyClientHeader.java   Source Code and License Vote up 5 votes
private String readLine(ByteBuf in) {
    while (in.isReadable()) {
        byte b = in.readByte();
        byteBuf.writeByte(b);
        lineBuf.append((char) b);
        int len = lineBuf.length();
        if (len >= 2 && lineBuf.substring(len - 2).equals("\r\n")) {
            String line = lineBuf.substring(0, len - 2);
            lineBuf.delete(0, len);
            return line;
        }
    }
    return null;
}
 
Example 17
Project: athena   File: JsonRpcReaderUtil.java   Source Code and License Vote up 5 votes
/**
 * Filter the invalid characters before decoding.
 * @param in input of bytes
 * @param lastReadBytes the bytes for last decoding incomplete record
 */
private static void fliterCharaters(ByteBuf in) {
    while (in.isReadable()) {
        int ch = in.getByte(in.readerIndex());
        if ((ch != ' ') && (ch != '\n') && (ch != '\t') && (ch != '\r')) {
            break;
        } else {
            in.readByte();
        }
    }
}
 
Example 18
Project: Quavo   File: WorldLoginDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (!in.isReadable()) {
		return;
	}

	ByteBuf buffer = ByteBufUtils.encipherRSA(in, EXPONENT, MODULUS);
	int id = buffer.readByte();
	if (id != 1) {
		return;
	}
	int clearanceId = buffer.readByte();
	int[] clientKeys = new int[4];
	for (int index = 0; index < clientKeys.length; index++) {
		clientKeys[index] = buffer.readInt();
	}
	LoginClearance clearance = LoginClearance.getType(clearanceId).get().read(buffer);
	String password = ByteBufUtils.readString(buffer);
	buffer = ByteBufUtils.decipherXTEA(in, clientKeys);
	String username = ByteBufUtils.readString(buffer);
	DisplayMode mode = DisplayMode.getDisplayMode(buffer.readByte()).get();
	int width = buffer.readShort();
	int height = buffer.readShort();
	DisplayInformation display = new DisplayInformation(mode, width, height);
	buffer.skipBytes(24);
	String token = ByteBufUtils.readString(buffer);
	buffer.readInt();
	MachineInformation machineInformation = MachineInformation.decode(buffer);
	buffer.readInt();
	buffer.readInt();
	buffer.readInt();
	buffer.readInt();
	buffer.readByte();
	int[] crc = new int[16];
	for (int index = 0; index < crc.length; index++) {
		crc[index] = buffer.readInt();
	}
	int[] serverKeys = new int[4];
	for (int index = 0; index < serverKeys.length; index++) {
		serverKeys[index] = clientKeys[index] + 50;
	}
	IsaacRandomPair isaacPair = new IsaacRandomPair(new IsaacRandom(serverKeys), new IsaacRandom(clientKeys));

	out.add(new WorldLoginRequest(this, type, username, password, clearance, display, machineInformation, crc, token, isaacPair));
}
 
Example 19
Project: BaseClient   File: MessageDeserializer2.java   Source Code and License Vote up 4 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws Exception
{
    p_decode_2_.markReaderIndex();
    byte[] abyte = new byte[3];

    for (int i = 0; i < abyte.length; ++i)
    {
        if (!p_decode_2_.isReadable())
        {
            p_decode_2_.resetReaderIndex();
            return;
        }

        abyte[i] = p_decode_2_.readByte();

        if (abyte[i] >= 0)
        {
            PacketBuffer packetbuffer = new PacketBuffer(Unpooled.wrappedBuffer(abyte));

            try
            {
                int j = packetbuffer.readVarIntFromBuffer();

                if (p_decode_2_.readableBytes() >= j)
                {
                    p_decode_3_.add(p_decode_2_.readBytes(j));
                    return;
                }

                p_decode_2_.resetReaderIndex();
            }
            finally
            {
                packetbuffer.release();
            }

            return;
        }
    }

    throw new CorruptedFrameException("length wider than 21-bit");
}