Example usage for io.netty.buffer ByteBuf toString

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

Introduction

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

Prototype

public abstract String toString(Charset charset);

Source Link

Document

Decodes this buffer's readable bytes into a string with the specified character set name.

Usage

From source file:com.heliosapm.streams.metrichub.HubManager.java

License:Apache License

public RequestCompletion evaluate(final QueryContext queryContext, final RequestBuilder requestBuilder,
        final String expression) {
    try {/*  w  ww  . ja v a  2 s . c  o m*/
        final JsonGenerator jg = requestBuilder.renderHeader();
        final ChannelPool pool = channelPool();
        final Channel channel = pool.acquire().get();
        final CompletableFuture<RequestCompletion> completionFuture = new CompletableFuture<RequestCompletion>();

        evaluate(queryContext, expression).flush().consume(lmt -> {
            final RequestCompletion rc = new RequestCompletion(queryContext.getTimeout(), pool);
            if (channel.pipeline().get("completion") != null) {
                try {
                    channel.pipeline().remove("completion");
                } catch (Exception ex) {
                }
            }
            channel.pipeline().addLast("completion", rc);
            completionFuture.complete(rc);
            final ByteBuf bb = requestBuilder.merge(jg, lmt);
            if (log.isDebugEnabled())
                log.debug("CREQUEST:\n{}", bb.toString(UTF8));
            final HttpRequest httpRequest = buildHttpRequest(bb);
            log.info("Flushed request. Size: {} bytes", bb.readableBytes());
            channel.writeAndFlush(httpRequest);
        });
        return completionFuture.get();
    } catch (Exception ex) {
        throw new RuntimeException("eval error", ex);
    }
}

From source file:com.heliosapm.streams.metrichub.RequestBuilder.java

License:Apache License

public ByteBuf merge(final JsonGenerator jg, final List<TSMeta> metas) {
    merges++;/*from   w  w w . j a v a2  s  .c om*/
    final ByteBufOutputStream os = (ByteBufOutputStream) jg.getOutputTarget();
    final ByteBuf buff = os.buffer();
    //System.err.println("MetaBatch:" + metas.size() + ", Merges:" + merges);
    try {
        int cnt = 0;
        for (final TSMeta tsMeta : metas) {
            if (tsMeta == null)
                continue;
            jg.writeStartObject(); // start of query
            jg.writeStringField("aggregator", aggregator.name().toLowerCase());
            if (rateOptions != null) {
                jg.writeStringField("rate", "true"); // FIXME
            }
            if (downSampling != null) {
                jg.writeStringField("downsample", downSampling);
            }

            jg.writeArrayFieldStart("tsuids");
            jg.writeString(tsMeta.getTSUID());
            jg.writeEndArray(); // end of tsuids
            jg.writeEndObject(); // end of query
            cnt++;
        } // end of TSMetas
        log.info("Wrote {} TSDUID Queries", cnt);
        jg.writeEndArray(); // end of queries array
        jg.writeEndObject(); // end of request
        jg.flush();
        os.flush();
        jg.close();
        os.close();
        log.info("TSDB Request:\n{}", buff.toString(UTF8));
        return buff;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.heliosapm.streams.metrichub.serialization.JSONChannelBufferSerializer.java

License:Apache License

/**
 * {@inheritDoc}// www.j  a  va  2s.  c o  m
 * @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.heliosapm.streams.onramp.StringMetricHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from   w ww . j  a  v a2  s. co m*/
 * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 */
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    final String v = msg.toString(UTF8).toLowerCase();
    try {
        final StreamedMetricValue smv;
        if (v.indexOf("put ") == 0) {
            // it's a put command, telnet style:  put <metric-name> <timestamp> <value> <tag1=value1>...<tagn=valuen>
            smv = StreamedMetricValue.fromOpenTSDBString(v);
        } else {
            // It's a stringed StreamedMetricValue: [<value-type>,]<timestamp>, [<value>,] <metric-name>, <host>, <app> [,<tagkey1>=<tagvalue1>,<tagkeyn>=<tagvaluen>]
            smv = StreamedMetricValue.fromString(v).forValue();
        }
        log.debug("Ingested UDP Metric: [{}]", smv);
        mf.send(smv);
    } catch (Exception ex) {
        log.error("Failed to handle metric text line: [{}]", v, ex);
    }
}

From source file:com.heliosapm.streams.onramp.TextLineRpcHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from  w w w . j av a2 s  .c o m*/
 * @see io.netty.handler.codec.MessageToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)
 */
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf buff, final List<Object> out)
        throws Exception {
    final String v = buff.toString(UTF8);
    log.debug("Received Message: [{}]", v);
    mf.send(v);
    out.add(buff.retain());
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitMetaInputHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    log.info(msg.toString(UTF8));
    //      if(log.isTraceEnabled()) {
    //         log.trace(msg.toString(UTF8));
    //      }      
    //      metricCache.submit(
    //            JSON.parseToObject(msg, Trace.class)
    //      );/*w  w w . j  a va 2s  . c o m*/
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitTraceInputHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(msg.toString(UTF8));
    }//from   w ww.ja  va 2  s . c  o  m
    //log.info(msg.toString(UTF8));
    final JsonNode node = JSON.parseToNode(msg, UTF8);

    if (node.has("metric")) {
        if (node.has("timestamp")) {
            metricCache.submit(JSON.parseToObject(node, Trace.class));
        }
    } else if (node.has("Metric")) {
        //         final ObjectName on = metaObjectName(node);
        //         final String name = metaObject(node);
        //         final Map<String, String> metaNvps = JSON.from(node);
        System.out.println(JSON.serializeToString(node));
        //         log.info("META: [{}] : [{}]", name, metaNvps);
        //         if(on!=null) {         
        //            metricCache.submit(on, metaNvps.get("Name"), metaNvps.get("Value"));
        //         }
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NO_CONTENT);
    ctx.writeAndFlush(response);

    //HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    // response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");             
}

From source file:com.heliosapm.tsdblite.handlers.text.WordSplitter.java

License:Apache License

/**
 * {@inheritDoc}/*  w ww.  j  a va 2 s  .co  m*/
 * @see io.netty.handler.codec.MessageToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)
 */
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf msg, final List<Object> out)
        throws Exception {
    out.add(splitString(msg.toString(CHARSET), ' '));
}

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

License:Apache License

/**
 * {@inheritDoc}/* ww  w  .  j  a  va 2 s .  c  om*/
 * @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.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        System.out.println(req);/*w ww.ja  v a 2  s. c o  m*/

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf buf = content.content();
        System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
        buf.release();
        System.out.println(ChannelMap.channelMap);
        Channel channel = ChannelMap.channelMap.get("null0");
        if (channel != null) {

            System.out.println(channel.id().asLongText());
            JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short) 1, (short) 1, (short) 1, (short) 1,
                    new int[] { 1, 2, 3, 4, 5 });
            //System.out.println(jmtisMsg);
            System.out.println(ctx.channel().id().asLongText());
            channel.writeAndFlush(jmtisMsg);
            channel.write(jmtisMsg);
            channel.flush();
        } else {
            System.out.println("there is no active channel.......");
        }
        //JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short)1, (short)1, (short)1, (short)1, new int[]{1, 2, 3, 4, 5});
        //System.out.println(jmtisMsg);
        //channel.write(jmtisMsg);

    }
}