Example usage for io.netty.buffer ByteBuf readableBytes

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

Introduction

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

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:at.yawk.accordion.netty.Framer.java

License:Mozilla Public License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    // length of this message
    int length = msg.readableBytes();
    if (length > MAXIMUM_MESSAGE_LENGTH) {
        throw new IOException("Message too long: " + length + " bytes");
    }//from ww w .j  av  a 2 s  .com
    out.ensureWritable(2 + length);

    // write
    out.writeShort(length);
    msg.readBytes(out, length);
}

From source file:at.yawk.accordion.netty.Framer.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    if (msg.readableBytes() < 2) {
        // no (full) length header received yet, wait
        return;//from w ww. java 2  s  . c  o  m
    }

    // mark so we can reset here if the message isn't complete yet
    msg.markReaderIndex();
    int messageLength = msg.readUnsignedShort();
    if (messageLength > msg.readableBytes()) {
        // length header received but message not yet complete, wait
        msg.resetReaderIndex();
        return;
    }

    // message complete, queue for handling
    ByteBuf message = msg.readBytes(messageLength);
    out.add(message);
}

From source file:at.yawk.dbus.protocol.codec.BodyEncoder.java

@Override
protected void encode(ChannelHandlerContext ctx, DbusMessage msg, List<Object> out) throws Exception {
    MessageHeader header = msg.getHeader();
    // note: we still modify the header below
    out.add(header);//from w  ww. j a  va 2s .  c o m

    MessageBody body = msg.getBody();
    if (body != null && !body.getArguments().isEmpty()) {
        List<TypeDefinition> types = new ArrayList<>(body.getArguments().size());
        ByteBuf bodyBuffer = ctx.alloc().buffer().order(Local.OUTBOUND_ORDER);
        AlignableByteBuf aligned = AlignableByteBuf.fromAlignedBuffer(bodyBuffer, 8);
        for (DbusObject arg : body.getArguments()) {
            types.add(arg.getType());
            arg.serialize(aligned);
        }

        header.addHeader(HeaderField.SIGNATURE, SignatureObject.create(types));
        header.setMessageBodyLength(bodyBuffer.readableBytes());
        out.add(bodyBuffer);
        log.trace("Body: {}", body);
    }
    log.trace("Header: {}", header);
}

From source file:at.yawk.dbus.protocol.codec.MessageHeaderCodec.java

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf rawBuf, List<Object> out) throws Exception {
    if (toRead != 0) {
        if (rawBuf.readableBytes() < toRead) {
            return;
        }//from ww w .  j  a  v  a  2  s. c  om
        ByteBuf slice = rawBuf.slice().order(byteOrder);
        slice.writerIndex(slice.readerIndex() + toRead);
        slice.retain();
        AlignableByteBuf decoding = AlignableByteBuf.decoding(slice);
        log.trace("INBOUND {}", decoding);
        out.add(decoding);

        rawBuf.readerIndex(rawBuf.readerIndex() + toRead);
        toRead = 0;
    }

    if (rawBuf.readableBytes() < MIN_HEADER_LENGTH) {
        return;
    }

    rawBuf.markReaderIndex();
    byte endianness = rawBuf.readByte();
    ByteOrder order;
    switch (endianness) {
    case 'l':
        order = ByteOrder.LITTLE_ENDIAN;
        break;
    case 'B':
        order = ByteOrder.BIG_ENDIAN;
        break;
    default:
        throw new DecoderException("Unknown byte order byte " + endianness);
    }

    AlignableByteBuf buf = AlignableByteBuf.decoding(rawBuf.resetReaderIndex().order(order));

    buf.getBuffer().markReaderIndex();
    buf.readByte(); // skip endianness byte we read above

    @Nullable
    MessageType type = MessageType.byId(buf.readByte());
    byte flags = buf.readByte();
    byte majorProtocolVersion = buf.readByte();
    if (majorProtocolVersion != PROTOCOL_VERSION) {
        throw new DecoderException("Unsupported major protocol version " + majorProtocolVersion);
    }
    long bodyLength = buf.readUnsignedInt();
    int serial = buf.readInt();

    MessageHeader header = new MessageHeader();
    header.setByteOrder(order);
    header.setMessageType(type);
    header.setNoReplyExpected((flags & NO_REPLY_EXPECTED) != 0);
    header.setNoAutoStart((flags & NO_AUTO_START) != 0);
    header.setAllowInteractiveAuthorization((flags & ALLOW_INTERACTIVE_AUTHORIZATION) != 0);
    header.setMajorProtocolVersion(majorProtocolVersion);
    header.setMessageBodyLength(bodyLength);
    header.setSerial(serial);
    header.setHeaderFields(new EnumMap<>(HeaderField.class));

    ArrayObject headers = (ArrayObject) tryDecode(HEADER_FIELD_LIST_TYPE, buf);
    if (headers == null) {
        // not enough data
        buf.getBuffer().resetReaderIndex();
        return;
    }
    for (DbusObject struct : headers.getValues()) {
        HeaderField field = HeaderField.byId(struct.get(0).byteValue());
        if (field != null) {
            DbusObject value = struct.get(1).getValue();
            if (!value.getType().equals(field.getType())) {
                throw new DecoderException("Invalid header type on " + field + ": got " + value.getType()
                        + " but expected " + field.getType());
            }
            header.getHeaderFields().put(field, value);
        }
    }

    if (type != null) {
        checkRequiredHeaderFieldsPresent(header);
    }

    if (!buf.canAlignRead(8)) {
        buf.getBuffer().resetReaderIndex();
        return;
    }
    buf.alignRead(8);

    toRead = Math.toIntExact(header.getMessageBodyLength());
    byteOrder = order;
    out.add(header);
}

From source file:at.yawk.dbus.protocol.DbusUtil.java

public static String printHex(ByteBuf buf) {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    return printHex(bytes);
}

From source file:at.yawk.votifier.VoteDecrypter.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable < MESSAGE_SIZE) {
        // the message must be exactly 256 bytes long
        return;/*from  w ww .java 2  s .com*/
    }

    byte[] encrypted = new byte[MESSAGE_SIZE];
    in.readBytes(encrypted);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encrypted);
    out.add(Unpooled.wrappedBuffer(decrypted));
}

From source file:basic.TimeClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);//  www.  j av a 2s.  c  om
    String body = new String(req, "UTF-8");
    System.out.println("Now is : " + body);
}

From source file:basic.TimeServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);//from   w  ww.  j  a  v  a  2 s . c o  m
    String body = new String(req, "UTF-8");
    System.out.println("The time server receive order : " + body);
    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
            ? new java.util.Date(System.currentTimeMillis()).toString()
            : "BAD ORDER";
    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.write(resp);
}

From source file:bftsmart.communication.client.netty.NettyTOMMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {

    // Wait until the length prefix is available.
    if (buffer.readableBytes() < Integer.BYTES) {
        return;// w w  w . j a va  2  s .  c  o  m
    }

    int dataLength = buffer.getInt(buffer.readerIndex());

    //Logger.println("Receiving message with "+dataLength+" bytes.");

    // Wait until the whole data is available.
    if (buffer.readableBytes() < dataLength + Integer.BYTES) {
        return;
    }

    // Skip the length field because we know it already.
    buffer.skipBytes(Integer.BYTES);

    int size = buffer.readInt();
    byte[] data = new byte[size];
    buffer.readBytes(data);

    byte[] signature = null;
    size = buffer.readInt();

    if (size > 0) {
        signature = new byte[size];
        buffer.readBytes(signature);
    }

    DataInputStream dis = null;
    TOMMessage sm = null;

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        dis = new DataInputStream(bais);
        sm = new TOMMessage();
        sm.rExternal(dis);
        sm.serializedMessage = data;

        if (signature != null) {
            sm.serializedMessageSignature = signature;
            sm.signed = true;
        }

        if (!isClient) {
            rl.readLock().lock();
            if (!sessionTable.containsKey(sm.getSender())) {
                rl.readLock().unlock();

                NettyClientServerSession cs = new NettyClientServerSession(context.channel(), sm.getSender());

                rl.writeLock().lock();
                sessionTable.put(sm.getSender(), cs);
                logger.debug("Active clients: " + sessionTable.size());
                rl.writeLock().unlock();

            } else {
                rl.readLock().unlock();
            }
        }
        logger.debug("Decoded reply from " + sm.getSender() + " with sequence number " + sm.getSequence());
        list.add(sm);
    } catch (Exception ex) {

        logger.error("Failed to decode TOMMessage", ex);
    }
    return;
}

From source file:blazingcache.client.CacheEntry.java

License:Apache License

/**
 * Creates the entry and refcount of the given ByteBuf is not incremented
 *
 * @param key/*  ww  w . ja v  a  2s  . co m*/
 * @param lastGetTimeNanos
 * @param serializedData
 * @param expiretime
 * @param deserialized
 */
CacheEntry(RawString key, long lastGetTimeNanos, ByteBuf serializedData, long expiretime, Object deserialized) {
    this.key = key;
    this.lastGetTime = lastGetTimeNanos;
    this.putTime = lastGetTimeNanos;
    this.buf = serializedData;
    this.expiretime = expiretime;
    this.dataLength = serializedData.readableBytes();
    this.reference = deserialized != null ? new SoftReference<>(deserialized) : null;
}