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:com.heliosapm.streams.opentsdb.KafkaRPCTest.java

License:Apache License

protected void send(final Set<StreamedMetricValue> metrics) {
    final ByteBuf buff = BufferManager.getInstance().buffer(metrics.size() * 128);

    try {/*w  w  w  .  j a  v a2 s . com*/

        for (StreamedMetricValue smv : metrics) {
            smv.intoByteBuf(buff);
        }
        log("Sent Buff Size:" + buff.readableBytes());
        final int vsize = producer.send(new ProducerRecord<String, ByteBuf>("tsdb.metrics.binary", buff)).get()
                .serializedValueSize();
        log("Sent Value Size:" + vsize);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            buff.release();
        } catch (Exception x) {
            /* No Op */}
    }
}

From source file:com.heliosapm.streams.opentsdb.KafkaRTPublisher.java

License:Apache License

/**
 * {@inheritDoc}//from   ww  w.ja  va 2  s . co m
 * @see com.heliosapm.streams.chronicle.MessageListener#onMetric(io.netty.buffer.ByteBuf)
 */
@Override
public int onMetric(final ByteBuf buf) {
    log.debug("OnMetric Buffer: {} bytes", buf.readableBytes());
    try {
        int totalCount = 0;
        try {
            final Iterator<StreamedMetricValue> iter = StreamedMetricValue.streamedMetricValues(true, buf, true)
                    .iterator();
            while (iter.hasNext()) {
                final StreamedMetricValue smv = iter.next();
                kafkaSender
                        .send(new ProducerRecord<String, StreamedMetricValue>(topicName, smv.metricKey(), smv));
                totalCount++;
            }
        } catch (Exception ex) {
            log.error("OnMetric Error", ex);
        }
        return totalCount;
    } finally {
        try {
            buf.release();
        } catch (Exception ex) {
            /* No Op */}
    }
}

From source file:com.heliosapm.streams.tracing.writers.NetWriter.java

License:Apache License

/**
 * {@inheritDoc}//from w  w  w  . ja  va 2 s .c om
 * @see com.heliosapm.streams.tracing.AbstractMetricWriter#onMetrics(io.netty.buffer.ByteBuf)
 */
@Override
public void onMetrics(final ByteBuf metrics) {
    if (metrics == null || metrics.readableBytes() < 5)
        return;
    final int size = metrics.getInt(1);
    if (!connectionsAvailable.get()) {
        // FIXME: drop counter
        return;
    }

    boolean complete = false;
    for (Channel ch : channels) {
        final ChannelFuture cf = ch.writeAndFlush(metrics).syncUninterruptibly();
        if (cf.isSuccess()) {
            complete = true;
            break;
        }
    }
    if (!complete) {
        this.failedMetrics.add(size);
    }
}

From source file:com.heliosapm.tsdblite.handlers.http.TSDBHttpRequest.java

License:Apache License

private static HttpResponse response(final HttpResponseStatus status, final String... msgs) {
    final ByteBuf buf = join(msgs);
    if (buf.readableBytes() == 0) {
        return new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    }/*from   w  ww. jav  a 2s  .  c o  m*/
    final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf);
    resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, buf.readableBytes());
    resp.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain");
    return resp;
}

From source file:com.heliosapm.tsdblite.handlers.http.TSDBHttpRequest.java

License:Apache License

/**
 * Indicates if the request has a readable content body
 * @return true if the request has a readable content body, false otherwise
 *///from   w  ww. j  a v  a  2s .c om
public boolean hasContent() {
    if (request instanceof FullHttpRequest) {
        final ByteBuf content = ((FullHttpRequest) request).content();
        if (content == null)
            return false;
        if (content.readableBytes() < 1)
            return false;
        return true;
    }
    return false;
}

From source file:com.heliosapm.tsdblite.handlers.ProtocolSwitch.java

License:Apache License

/**
 * {@inheritDoc}/* w w  w  . ja va 2  s  .  c  om*/
 * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
 */
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        log.info("No ProtocolSwitch. Bytes: {}", in.readableBytes());
        return;
    }
    final int magic1 = in.getUnsignedByte(in.readerIndex());
    final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
    if (detectGzip && isGzip(magic1, magic2)) {
        enableGzip(ctx);
        log.info("Enabled GZip on channel [{}]", ctx.channel().id().asShortText());
    } else if (isHttp(magic1, magic2)) {
        switchToHttp(ctx);
        log.info("Switched to HTTP on channel [{}]", ctx.channel().id().asShortText());
    } else if (isText(magic1, magic2)) {
        switchToPlainText(ctx);
        log.info("Switched to PlainText on channel [{}]", ctx.channel().id().asShortText());
    } else {
        log.error("No protocol recognized on [{}]", ctx.channel().id().asLongText());
        in.clear();
        ctx.close();
    }
}

From source file:com.heliosapm.webrpc.jsonservice.JSONRequest.java

License:Apache License

/**
 * Creates a new JSONRequest//from   ww  w . java 2s  .  co  m
 * @param channel The channel the request came in on
 * @param jsonContent The buffer containing the json content to build the request from
 * @return a new JSONRequest
 */
public static JSONRequest newJSONRequest(final Channel channel, final ByteBuf jsonContent) {
    if (jsonContent == null || jsonContent.readableBytes() < 2)
        throw new IllegalArgumentException("The passed json content was null or empty");
    try {
        final JsonNode jsonNode = JSONOps.parseToNode(jsonContent);
        return new JSONRequest(channel, jsonNode.get("t").asText(), jsonNode.get("rid").asLong(-1L), -1L,
                jsonNode.get("svc").asText(), jsonNode.get("op").asText(), jsonNode);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JsonNode from passed buffer [" + jsonContent + "]", e);
    }

}

From source file:com.hiido.eagle.hes.transfer.FileTransferServer.java

License:Apache License

protected FileStoreInfo createAndStoreFile(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    int filePathSize = in.readInt();
    String fileName = new String(in.readBytes(filePathSize).array());
    long fileSize = in.readLong();

    String localPath = TransferServerConfig.class.getResource("/").getPath() + fileName;
    logger.info("Start to handler the file [{}] with size [{}b] which be writen to local disk [{}]", fileName,
            fileSize, localPath);/*w w w  .ja  v  a2 s.com*/

    long currFileSize = in.readableBytes();
    ByteBuffer buf = ByteBuffer.allocate((int) currFileSize);
    in.readBytes(buf);

    RandomAccessFile accessfile = new RandomAccessFile(localPath, "rw");
    FileChannel fileChannel = accessfile.getChannel();
    fileChannel.write(buf);
    return new FileStoreInfo(accessfile, fileChannel, fileName, fileSize, currFileSize);
}

From source file:com.hiido.eagle.hes.transfer.FileTransferServer.java

License:Apache License

protected void storeFile(ChannelHandlerContext ctx, Object msg, FileStoreInfo fileStoreInfo) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    fileStoreInfo.incrCurrFileSize(in.readableBytes());
    fileStoreInfo.getFileChannel().write(in.nioBuffer());
}

From source file:com.hipishare.chat.test.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    int len = buf.readableBytes();
    byte[] temp = new byte[len];
    ByteBuffer bb = ByteBuffer.allocate(len);
    buf.readBytes(temp);/*from   www.  j a  v  a 2 s .c  o m*/
    bb.put(temp);
    String message = new String(bb.array());
    if ("ping".equals(message)) {
        buf = Unpooled.copiedBuffer(("[id=" + ctx.channel().id() + "]" + "ok").getBytes());
        ctx.writeAndFlush(buf);
    }
}