Example usage for io.netty.buffer ByteBuf isReadable

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

Introduction

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

Prototype

public abstract boolean isReadable();

Source Link

Document

Returns true if and only if (this.writerIndex - this.readerIndex) is greater than 0 .

Usage

From source file:com.myftpserver.handler.ReceiveFileHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (bos == null) {
        User user = fs.getUser();/*from   w  ww.  jav  a 2s  . c  o m*/
        if (user.getUploadSpeedLitmit() == 0L)
            logger.info("File upload speed is limited by connection speed");
        else {
            ctx.channel().pipeline().addFirst("TrafficShapingHandler",
                    new ChannelTrafficShapingHandler(0L, user.getUploadSpeedLitmit() * 1024));
            logger.info("File upload speed limit:" + user.getUploadSpeedLitmit() + " kB/s");
        }
        ctx.channel().closeFuture().addListener(this);
        tempFile = File.createTempFile("temp-file-name", ".tmp");
        fs.setUploadTempFile(tempFile);
        bos = new BufferedOutputStream(new FileOutputStream(tempFile));
    }
    ByteBuf in = (ByteBuf) msg;
    //logger.debug("ReceiveFileHandler channelRead buffer capacity="+in.capacity()+",readable byte count="+in.readableBytes());
    try {
        while (in.isReadable()) {
            in.readBytes(bos, in.readableBytes());
        }
        bos.flush();
    } finally {
        in.release();
    }
}

From source file:com.navercorp.nbasearc.gcp.RedisDecoder.java

License:Apache License

private boolean hasFrame(ByteBuf in) {
    if (in.isReadable() == false) {
        return false;
    }//from   w  ww .  j  ava  2  s . co  m

    lookasideBufferLength = Math.min(in.readableBytes(), lookasideBuffer.length);
    in.readBytes(lookasideBuffer, 0, lookasideBufferLength);
    lookasideBufferReaderIndex = 0;
    in.readerIndex(in.readerIndex() - lookasideBufferLength);

    byte b = lookasideBuffer[lookasideBufferReaderIndex++];
    in.skipBytes(1);
    if (b == MINUS_BYTE) {
        return processError(in);
    } else if (b == ASTERISK_BYTE) {
        return processMultiBulkReply(in);
    } else if (b == COLON_BYTE) {
        return processInteger(in);
    } else if (b == DOLLAR_BYTE) {
        return processBulkReply(in);
    } else if (b == PLUS_BYTE) {
        return processStatusCodeReply(in);
    } else {
        throw new JedisConnectionException("Unknown reply: " + (char) b);
    }
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception {
    ByteBuf clientPrefaceString = Http2CodecUtil.connectionPrefaceBuf();
    int prefaceRemaining = clientPrefaceString.readableBytes();
    int bytesRead = min(in.readableBytes(), prefaceRemaining);

    // If the input so far doesn't match the preface, break the connection.
    if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(), clientPrefaceString,
            clientPrefaceString.readerIndex(), bytesRead)) {
        String receivedBytes = hexDump(in, in.readerIndex(),
                min(in.readableBytes(), clientPrefaceString.readableBytes()));
        throw connectionError(PROTOCOL_ERROR,
                "HTTP/2 client preface string missing or corrupt. " + "Hex dump for received bytes: %s",
                receivedBytes);/*from   w  w  w  . j  av  a 2s . co  m*/
    }
    in.skipBytes(bytesRead);
    clientPrefaceString.skipBytes(bytesRead);

    if (!clientPrefaceString.isReadable()) {
        // Entire preface has been read.
        clientPrefaceString.release();
        return true;
    }
    return false;
}

From source file:com.oskm.netty.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO Auto-generated method stub
    ByteBuf in = (ByteBuf) msg;

    try {//from  w w  w . j a  v  a 2  s . co m
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        ReferenceCountUtil.release(msg);

    }
}

From source file:com.phei.netty.nio.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//from w ww.  j  av a 2s  .  c o  m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<CharSequence, CharSequence> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.quavo.osrs.network.protocol.codec.connection.ConnectionDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable()) {
        return;//w ww.  j a va 2  s  . c  o m
    }

    ConnectionType.getType(in.readUnsignedByte()).ifPresent(type -> out.add(new ConnectionRequest(this, type)));// id
}

From source file:com.quavo.osrs.network.protocol.codec.game.GamePacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || !player.getChannel().isRegistered()) {
        return;/*w w w  .j av  a  2 s. c  o m*/
    }
    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()]);
    }
}

From source file:com.quavo.osrs.network.protocol.codec.handshake.HandshakeDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || in.readableBytes() < 4) {
        return;//from   w  ww  . j  a v a2s . c  o  m
    }

    out.add(new HandshakeRequest(this, in.readInt()));// version
}

From source file:com.quavo.osrs.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || in.readableBytes() < 8) {
        return;// w  ww  .j a  v a  2 s. c  o m
    }

    LoginType.getType(in.readByte()).filter(a -> in.readShort() == in.readableBytes())
            .ifPresent(a -> out.add(new LoginRequest(this, a, in.readInt())));
}

From source file:com.quavo.osrs.network.protocol.codec.login.world.WorldLoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable()) {
        return;/*from www  . java2  s.  c  om*/
    }

    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));
}