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.ixortalk.nifi.processors.gettcp.TcpClientHandler.java

License:Apache License

/**
 *
 * When data becomes available on the socket, it will trigger the method below.
 * We'll read from the buffer until we find the delimiter.
 * When we find the delimiter, we'll offer it to the queue so that it can be subsequently polled by the processor.
 * The delimiter will not be offered as part of the message (TODO: make this optional)
 *
 * In case we fail to convert a byte from the buffer we log an error, but continue processing.
 *
 * @param channelHandlerContext//from w  w w. j a v  a 2  s.co m
 * @param o
 * @throws Exception
 */
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
    ByteBuf in = (ByteBuf) o;

    try {
        while (in.isReadable()) {
            byte b = in.readByte();

            if (log.isTraceEnabled()) {
                log.trace("Read byte " + ByteUtils.byteToHex(b));
            }

            if (b == delimiter) {
                if (log.isTraceEnabled()) {
                    log.trace("Found delimiter, offering message : " + message.toString());
                }

                socketMessagesReceived.offer(message.toString());
                message = new StringBuffer();
            } else {
                try {
                    message.append(new String(new byte[] { b }, "UTF-8"));
                } catch (Exception e) {
                    log.error("Error occured while converting byte to string.", e);
                }
            }
        }
    } catch (Exception e) {
        log.error("Error occured while reading channel", e);
    }
}

From source file:com.kingmed.dp.lisclient.demo.DiscardServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    try {//from  w  w  w  .  ja va 2 s  .  c o m
        while (in.isReadable()) {
            System.out.println((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.kradac.karview.netty.EchoServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    this.c = ctx.channel();
    ByteBuf buf = (ByteBuf) msg;
    String auxdata = "";
    while (buf.isReadable()) {
        byte aux = buf.readByte();
        char charVal = (char) aux;
        int valEnt = charVal;
        if (valEnt < 10) {
            auxdata += valEnt;/*from w  w w  .  ja v  a  2  s.c  om*/
        } else if (valEnt == 10 || valEnt == 13) {
            auxdata += "@";
        } else {
            auxdata += charVal;
        }
    }
    this.data = auxdata;
    buf.clear();
    System.out.println("Trama que llega: " + this.data);
    if (this.data.indexOf("0@80") == 0) {
        System.out.println("Trama SKP+ +param: [" + auxdata + "]");
        u.sendToFile(3, "skp+", this.data);
        tramaMinuto(this.data.substring(5));
    } else if (this.data.indexOf("0@8000001") == 0) {
        System.out.println("Trama Conexin SKP+: [" + auxdata + "]");
        u.sendToFile(2, "skp+", this.data);
        tramaConecxion(u.clearDataConnection(this.data));
        tipoEquipoGPRS = 1;
    } else if (this.data.indexOf("0@80") == 0) {
        System.out.println("Trama Conexin SKP: [" + auxdata + "]");
        u.sendToFile(2, "skp", this.data);
        tramaConecxion(u.clearDataConnection(this.data));
        tipoEquipoGPRS = 2;
    } else if (this.data.indexOf("0150") == 0) {
        u.sendToFile(5, "skp", data);
        if (registered) {
            System.out.println(
                    "Respuesta Comando [5] [" + data + "], Equipo: [" + v.getIdEquipo().getEquipo() + "]");
            processResponseComand(this.data.substring(5));
        } else {
            System.out.println("Respuesta Comando [5] [" + data + "], Equipo: [Desconocido]");
            System.out.println(
                    "Dato Enviado a Tabla de Invalidos por no estar registrado en el sistema [Desconocido].");
            dijc.create(new DatoInvalidos(3, new Date(), e.getEquipo(), this.data));
        }
        //            System.out.println("Respuesta Cmd: [" + auxdata + "]");
        //            processResponseComand(this.data.substring(5));
    } else if (this.data.indexOf("0420") == 0) {
        System.out.println("Trama SKP: [" + data + "]");
        u.sendToFile(3, "skp", this.data);
        procesarSKP(this.data.substring(5));
    } else if (this.data.indexOf("0@8 488") == 0) { // 0@8 488 
        System.out.println("Trama SKP+ -param: [" + auxdata + "]");
        u.sendToFile(3, "skp", this.data);
        tramaMinuto(this.data.substring(9));
    } else {
        if (this.data.indexOf("0@80") == 0) {
            System.out.println("Aqui");
        } else if (this.data.indexOf("0@80") == 0) {

        } else if (this.data.indexOf("0 @80") == 0) {
            System.err.println("Trama sin Procesar: [" + auxdata + "]");
            if (registered) {
                dijc.create(new DatoInvalidos(1, new Date(), e.getEquipo(), this.data));
                System.out.println("entra aqui 1");
            } else {
                System.out.println("entra aqui 2");
                dijc.create(new DatoInvalidos(1, new Date(), "", this.data));
            }
        }
    }
}

From source file:com.kradac.karview.netty.MyDecoder.java

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() < 2) {
        return;/*from   w ww. j ava 2 s .com*/
    }
    bb.markReaderIndex();
    int length = bb.readChar();
    if (length > 150) {
        String data = "";
        while (bb.isReadable()) {
            data += (char) bb.readByte();
        }
        bb.clear();
        if (data.contains("OK") || data.contains("handshake")) {
            if (data.contains("handshake")) {
                chc.channel().write("0%%at");
            }
            if (data.contains("OK")) {
                System.out.println("Respuesta de Comando AT [" + data + "]");
            }
        } else {
            System.err.println("Datos incorrectos enviados al Servidor [" + data + "]");
            chc.channel().disconnect();
        }
    }
    if (bb.readableBytes() < length - 2) {
        bb.resetReaderIndex();
        return;
    }
    in.writeBytes(bb);//Escribimos los bytes
    in.discardReadBytes();//
    in.retain();
    list.add(in);
    bb.clear();//vaciamos el byteBuf
}

From source file:com.l2jmobius.commons.network.codecs.CryptCodec.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
    // Check if there are any data to encrypt.
    if (!msg.isReadable()) {
        return;/*from w  ww  .j a  v a  2 s .c o  m*/
    }

    msg.resetReaderIndex();
    _crypt.encrypt(msg);
    msg.resetReaderIndex();
    out.writeBytes(msg);
}

From source file:com.l2jmobius.commons.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;/*from w  w  w  . ja v a2 s .  c om*/
    }

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

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

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

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            // LOGGER.warning(incomingPacket + ": Connection at invalid state: " + connectionState + " Required States: " + 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:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void encrypt(ByteBuf buf) {
    if (!_isEnabled) {
        _isEnabled = true;/*from w w  w.  java2s .  c om*/
        onPacketSent(buf);
        return;
    }

    onPacketSent(buf);

    int a = 0;
    while (buf.isReadable()) {
        final int b = buf.readByte() & 0xFF;
        a = b ^ _outKey[(buf.readerIndex() - 1) & 15] ^ a;
        buf.setByte(buf.readerIndex() - 1, a);
    }

    shiftKey(_outKey, buf.writerIndex());
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void decrypt(ByteBuf buf) {
    if (!_isEnabled) {
        onPacketReceive(buf);//  w  ww  . j  av  a  2s.c om
        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);
}

From source file:com.lambdaworks.redis.protocol.CommandHandlerTest.java

License:Apache License

@Test
public void shouldIgnoreNonReadableBuffers() throws Exception {

    ByteBuf byteBufMock = mock(ByteBuf.class);
    when(byteBufMock.isReadable()).thenReturn(false);

    sut.channelRead(context, byteBufMock);

    verify(byteBufMock, never()).release();
}

From source file:com.linecorp.armeria.client.encoding.ZlibStreamDecoder.java

License:Apache License

private byte[] fetchDecoderOutput() {
    CompositeByteBuf decoded = Unpooled.compositeBuffer();
    for (;;) {//  w w  w .  j a  va2s.  c  o  m
        ByteBuf buf = decoder.readInbound();
        if (buf == null) {
            break;
        }
        if (!buf.isReadable()) {
            buf.release();
            continue;
        }
        decoded.addComponent(true, buf);
    }
    byte[] ret = ByteBufUtil.getBytes(decoded);
    decoded.release();
    return ret;
}