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:org.jfxvnc.net.rfb.codec.decoder.FramebufferUpdateRectDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf m, List<Object> out) throws Exception {

    if (state == State.INIT) {
        logger.debug("init readable {} bytes", m.readableBytes());
        if (!m.isReadable()) {
            return false;
        }/*w w  w .  ja  va  2  s  . c o m*/
        if (m.getByte(0) != ServerEvent.FRAMEBUFFER_UPDATE.getType()) {
            logger.error("no FBU type!!! {}", m.getByte(0));
            ctx.pipeline().fireChannelReadComplete();
            return false;
        }
        if (!m.isReadable(4)) {
            return false;
        }
        m.skipBytes(2); // padding
        numberRects = m.readUnsignedShort();
        currentRect = 0;
        logger.debug("number of rectangles: {}", numberRects);
        if (numberRects < 1) {
            return true;
        }
        state = State.NEW_RECT;
    }

    if (state == State.NEW_RECT) {
        if (!readRect(ctx, m, out)) {
            return false;
        }
        state = State.READ_RECT;
    }

    FrameRectDecoder dec = frameRectDecoder.get(rect.getEncoding());
    if (dec == null) {
        throw new ProtocolException("Encoding not supported: " + rect.getEncoding());
    }
    dec.setRect(rect);
    if (!dec.decode(ctx, m, out)) {
        return false;
    }

    if (currentRect == numberRects) {
        state = State.INIT;
        ctx.pipeline().fireUserEventTriggered(ProtocolState.FBU_REQUEST);
        return true;
    }

    if (!readRect(ctx, m, out)) {
        state = State.NEW_RECT;
    }
    return false;
}

From source file:org.jfxvnc.net.rfb.codec.decoder.FrameDecoderHandler.java

License:Apache License

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

    FrameDecoder decoder;
    switch (state) {
    case NEXT:
        serverEvent = ServerEvent.valueOf(in.getUnsignedByte(0));
        decoder = frameDecoder.get(serverEvent);

        if (decoder == null) {
            logger.error("not handled server message type: {} ({})", serverEvent, in.getUnsignedByte(0));
            in.skipBytes(in.readableBytes());
            return;
        }
        if (!decoder.decode(ctx, in, out)) {
            state = State.FRAME;
        }
    case FRAME:
        decoder = frameDecoder.get(serverEvent);

        if (decoder == null) {
            logger.error("not handled server message type: {} ({})", serverEvent, in.getUnsignedByte(0));
            in.skipBytes(in.readableBytes());
            return;
        }
        if (decoder.decode(ctx, in, out)) {
            state = State.NEXT;
        }
        break;
    default:
        logger.warn("unknown state: {}", state);
        break;
    }
}

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.RawRectDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (framebuffer == null) {
        framebuffer = Unpooled.unreleasableBuffer(ctx.alloc().buffer(capacity));
    } else if (framebuffer.capacity() != capacity) {
        framebuffer.capacity(capacity);/* w w w  .  j a v a2s. c o  m*/
    }

    if (framebuffer.isWritable() && in.isReadable()) {
        logger.trace("readable/writable {}/{}", in.readableBytes(), framebuffer.writableBytes());
        framebuffer.writeBytes(in, Math.min(in.readableBytes(), framebuffer.writableBytes()));
    }
    if (!framebuffer.isWritable()) {
        logger.trace("read {} raw bytes completed", framebuffer.readableBytes());
        sendRect(out);
        framebuffer.clear();
        return true;
    }
    return false;
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient33Decoder.java

License:Apache License

protected void decodeErrorMessage(ChannelHandlerContext ctx, ByteBuf in) {
    if (!in.isReadable()) {
        ctx.fireExceptionCaught(new ProtocolException("decode error message failed"));
        return;// w  w  w .j a  v a 2s  .c o  m
    }

    byte[] reason = new byte[actualReadableBytes()];
    in.readBytes(reason);
    String error = new String(reason, ASCII);
    ctx.fireExceptionCaught(new ProtocolException(error.trim()));
}

From source file:org.kuali.test.proxyserver.TestProxyServer.java

License:Educational Community License

/**
 *
 * @param content/*from w  w  w  .  j  ava  2  s .co m*/
 * @return
 */
public static byte[] getHttpPostContent(ByteBuf content) {
    byte[] retval = null;
    if (content.isReadable()) {
        content.retain();
        ByteBuffer nioBuffer = content.nioBuffer();
        retval = new byte[nioBuffer.remaining()];
        nioBuffer.get(retval);
        content.release();
    }

    return retval;
}

From source file:org.l2junity.network.codecs.PacketDecoder.java

License:Open Source License

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

    if (in.order() != _byteOrder) {
        in = in.order(_byteOrder);
    }

    try {
        final short packetId = in.readUnsignedByte();
        if (packetId >= _incomingPackets.length) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IIncomingPackets<T> incomingPacket = _incomingPackets[packetId];
        if (incomingPacket == null) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            LOGGER.warn("{}: Connection at invalid state: {} Required States: {}", incomingPacket,
                    connectionState, incomingPacket.getConnectionStates());
            return;
        }

        final IIncomingPacket<T> packet = incomingPacket.newIncomingPacket();
        if ((packet != null) && packet.read(_client, new PacketReader(in))) {
            out.add(packet);
        }
    } finally {
        // We always consider that we read whole packet.
        in.readerIndex(in.writerIndex());
    }
}

From source file:org.legacy.network.protocol.handshake.HandshakeDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (buffer.isReadable()) {
        if (ctx.pipeline().get(HandshakeDecoder.class) != null) {
            ctx.pipeline().remove(this);
        }//  www .  j  a  va 2s  . com
        int opcode = buffer.readUnsignedByte() & 0xFF;
        switch (opcode) {
        case 15:
            int size = buffer.readUnsignedByte();
            if (buffer.readableBytes() < size) {
                ctx.channel().close();
                return;
            }
            int major_version = buffer.readInt();
            int minor_version = buffer.readInt();
            if (major_version != Framework.MAJOR_VERSION || minor_version != Framework.MINOR_VERSION) {
                buffer.writeByte(6);
                ctx.channel().close();
                return;
            }
            String ondemand_token = BufferUtils.readBufferedString(buffer);
            if (!ondemand_token.equals(Framework.ONDEMAND_SESSION_TOKEN)) {
                ctx.channel().close();
                return;
            }
            ByteBuf buf = Unpooled.buffer();
            buf.writeByte(0);
            for (int element : Framework.CRC_UPDATE_KEYS) {
                buf.writeInt(element);
            }
            ctx.channel().write(buf);
            ctx.pipeline().addBefore("channel-handler", "decoder", new OnDemandDecoder());
            break;
        default:
            LegacyLogger.fireWarnMessage(this, "Unknown Handshake Opcode: " + opcode);
        }
    }
}

From source file:org.legacy.utility.BufferUtils.java

License:Open Source License

/**
 * Reads a string used from the {@link ChannelBuffer}.
 * @param in The {@link ChannelBuffer}.//www . j  a  v  a 2  s  .  co m
 * @return The string.
 */
public static String readBufferedString(ByteBuf in) {
    StringBuilder string = new StringBuilder();
    byte b;
    while (in.isReadable() && (b = in.readByte()) != 0) {
        string.append((char) b);
    }
    return string.toString();
}

From source file:org.msgpack.rpc.loop.netty.MessagePackStreamDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> paramList) throws Exception {

    if (msg.isReadable()) {
        ByteBuffer buffer = msg.nioBuffer();
        Unpacker unpacker = msgpack.createBufferUnpacker(buffer);
        int lastPos = 0;
        try {//from  w  ww  .j a v  a  2 s  . co  m
            while (buffer.position() < buffer.limit()) {
                Value v = unpacker.readValue();
                paramList.add(v);
                lastPos = buffer.position();
            }
            msg.skipBytes(lastPos);
        } catch (EOFException e) {
            msg.skipBytes(lastPos);
        }
    }
}

From source file:org.nmrfx.server.ServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;
    try {// w w w  . ja  v  a 2 s .co  m
        while (in.isReadable()) { // (1)
            char ch = (char) in.readByte();
            System.out.print(ch);
            System.out.flush();
            if (ch == '\n') {
                consumer.accept(sBuilder.toString());
                sBuilder.setLength(0);
            } else {
                sBuilder.append(ch);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg); // (2)
    }
}