Example usage for io.netty.buffer ByteBuf clear

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

Introduction

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

Prototype

public abstract ByteBuf clear();

Source Link

Document

Sets the readerIndex and writerIndex of this buffer to 0 .

Usage

From source file:com.heliosapm.webrpc.serialization.JSONChannelBufferSerializer.java

License:Apache License

/**
 * {@inheritDoc}//from  w w  w . j av a 2 s  . com
 * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
 * FIXME: Need a way to stream the data in the ChannelBuffer as converting to a byte[] or String will scorch heap usage.
 */
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    if (value instanceof ByteBuf) {
        ByteBuf buff = (ByteBuf) value;
        //System.err.println(buff.toString(UTF8_CHARSET));         
        jgen.writeString(buff.toString(UTF8_CHARSET));
        buff.clear();
    } else {
        provider.defaultSerializeValue(value, jgen);
    }
}

From source file:com.hzmsc.scada.Jmtis.server.PortUnificationServerHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    System.out.println(in.getUnsignedByte(in.readerIndex()) + "..........................");
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        return;//  w ww.  jav a  2 s .  c o  m
    }

    if (isSsl(in)) {
        enableSsl(ctx);
    } else {
        final int magic1 = in.getUnsignedByte(in.readerIndex());
        final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
        if (isGzip(magic1, magic2)) {
            enableGzip(ctx);
        } else if (isHttp(magic1, magic2)) {
            switchToHttp(ctx);
        } else if (isJMAC(magic1, magic2)) {
            switchToJMAC(ctx);
        } else {
            // Unknown protocol; discard everything and close the connection.
            in.clear();
            ctx.close();
        }
    }
}

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;//  www  .j av  a2s  .  com
        } 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  w  w. j  ava  2 s  .c  o m*/
    }
    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.PacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, IOutgoingPacket packet, ByteBuf out) {
    if (out.order() != _byteOrder) {
        out = out.order(_byteOrder);//from w w w.  j  ava  2s  .  c o m
    }

    try {
        if (packet.write(new PacketWriter(out))) {
            if (out.writerIndex() > _maxPacketSize) {
                throw new IllegalStateException("Packet (" + packet + ") size (" + out.writerIndex()
                        + ") is bigger than the limit (" + _maxPacketSize + ")");
            }
        } else {
            // Avoid sending the packet
            out.clear();
        }
    } catch (Throwable e) {
        LOGGER.log(Level.WARNING, "Failed sending Packet(" + packet + ")", e);
        // Avoid sending the packet if some exception happened
        out.clear();
    }
}

From source file:com.lambdaworks.redis.codec.StringCodec.java

License:Apache License

/**
 * Compatibility implementation.//from  www.  j  av a  2  s . c o m
 * 
 * @param key
 * @return
 */
private ByteBuffer encodeAndAllocateBuffer(String key) {
    if (key == null) {
        return ByteBuffer.wrap(EMPTY);
    }

    CharsetEncoder encoder = CharsetUtil.encoder(charset);
    ByteBuffer buffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * key.length()));

    ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer);
    byteBuf.clear();
    encode(key, byteBuf);
    buffer.limit(byteBuf.writerIndex());

    return buffer;
}

From source file:com.spotify.ffwd.protobuf.ProtobufDecoder.java

License:Apache License

private void decodeOne(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    final int version = (int) in.getUnsignedInt(0);
    final long totalLength = in.getUnsignedInt(4);

    if (totalLength > MAX_FRAME_SIZE) {
        log.error("Received frame with length (" + totalLength + ") larger than maximum allowed ( "
                + MAX_FRAME_SIZE + ")");
        in.clear();
        return;//from   w  w  w . j a v  a  2 s.c o  m
    }

    // datagram underflow
    if (in.readableBytes() < totalLength) {
        log.error("Received frame of shorter length (" + in.readableBytes() + ") than reported (" + totalLength
                + ")");
        in.clear();
        return;
    }

    in.skipBytes(8);

    final Object frame;

    switch (version) {
    case 0:
        frame = decodeFrame0(in);
        break;
    default:
        throw new IllegalArgumentException("Unsupported protocol version: " + version);
    }

    if (frame != null) {
        out.add(frame);
    }
}

From source file:com.tesora.dve.db.mysql.DBTypeBasedUtilsTest.java

License:Open Source License

@Test
public void mysqlReadWriteTest() throws Exception {
    ByteBuf cb = Unpooled.buffer(100).order(ByteOrder.LITTLE_ENDIAN);

    int len;/*from w  w  w. j a va  2 s  .c om*/
    for (Pair<MyFieldType, Object> expValue : expValuesMysql) {
        cb.clear();
        len = 0;
        if (expValue.getSecond() instanceof Byte)
            len = 1;
        DataTypeValueFunc dtvf = DBTypeBasedUtils.getMysqlTypeFunc(expValue.getFirst(), len, 0);
        dtvf.writeObject(cb, expValue.getSecond());
        assertEqualData(expValue.getSecond(), dtvf.readObject(cb));
    }
}

From source file:com.tesora.dve.db.mysql.DBTypeBasedUtilsTest.java

License:Open Source License

@Test
public void sqlReadWriteTest() throws Exception {
    ByteBuf cb = Unpooled.buffer(100).order(ByteOrder.LITTLE_ENDIAN);

    for (Pair<Integer, Object> expValue : expValuesSQL) {
        cb.clear();
        DataTypeValueFunc dtvf = DBTypeBasedUtils.getSQLTypeFunc(expValue.getFirst());
        dtvf.writeObject(cb, expValue.getSecond());
        assertEqualData(expValue.getSecond(), dtvf.readObject(cb));
    }/*from w  ww . java  2s  .  com*/
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuCryptUtils.java

License:Open Source License

public static final long readRing(ByteBuf converter, short[] shift) {
    for (int i = 0; i < shift.length; i++) {
        converter.writeByte(shift[i]);//from  w  ww .  j  a va2  s .c o m
    }

    long uInt = converter.readInt();
    converter.clear();
    return uInt;
}