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:org.greencheek.caching.herdcache.memcached.elasticacheconfig.server.StringBasedServerHandler.java

License:Apache License

private void sendAll(final ChannelHandlerContext ctx) {
    long delayFor = delay;
    for (ByteBuf message : this.msg) {
        ByteBuf messageCopy = message.copy();
        String messageCopyStr = messageCopy.toString(Charset.forName("UTF-8"));
        if (messageCopyStr.contains("${REMOTE_ADDR}")) {
            messageCopyStr = messageCopyStr.replace("${REMOTE_ADDR}", ctx.channel().remoteAddress().toString());
        }//from w  ww.j  a v  a  2s  . co  m

        final ByteBuf messageToSend = stringToByteBuf(messageCopyStr);

        if (delay < 1) {
            ctx.writeAndFlush(messageToSend);
        } else {
            ctx.channel().eventLoop().schedule(new Runnable() {
                @Override
                public void run() {
                    ctx.writeAndFlush(messageToSend);
                }
            }, delayFor, delayUnit);
        }
        delayFor += delay;
    }
}

From source file:org.greencheek.caching.herdcache.memcached.elasticacheconfig.server.StringBasedServerHandler.java

License:Apache License

private void sendOne(final ChannelHandlerContext ctx) {
    final ByteBuf message = this.msg[index.getAndIncrement() % this.msg.length];

    ByteBuf messageCopy = message.copy();
    String messageCopyStr = messageCopy.toString(Charset.forName("UTF-8"));
    if (messageCopyStr.contains("${REMOTE_ADDR}")) {
        messageCopyStr = messageCopyStr.replace("${REMOTE_ADDR}", ctx.channel().remoteAddress().toString());
    }//  w w  w .j  a v a  2s.  c o  m

    final ByteBuf messageToSend = stringToByteBuf(messageCopyStr);

    if (delay < 1) {
        ctx.writeAndFlush(messageToSend);
    } else {
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                ctx.writeAndFlush(messageToSend);
            }
        }, delay, delayUnit);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.DemuxHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, @SuppressWarnings("rawtypes") List out)
        throws Exception {

    if (msg.readableBytes() < 5) {
        msg.clear();/* w  w  w. jav a  2s . c o m*/
        ctx.close();
        return;
    }
    ChannelPipeline pipeline = ctx.pipeline();

    String data = msg.toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled()) {
        logger.debug("Incoming: [" + data + "]");
    }

    boolean done = false;

    if (data.contains("type=metric")) {
        pipeline.addLast(new SyslogEventDecoder());
        pipeline.addLast("forwarder", new RestForwardingHandler(configuration));
        pipeline.remove(this);
        done = true;
    } else if (!data.contains("=")) {
        String[] items = data.split(" |\\n");
        if (items.length % 3 == 0) {
            pipeline.addLast("encoder", new GraphiteEventDecoder());
            pipeline.addLast("forwarder", forwardingHandler);
            pipeline.remove(this);
            done = true;
        }
    }
    if (!done) {
        logger.warn("Unknown input [" + data + "], ignoring");
        msg.clear();
        ctx.close();
    }
}

From source file:org.hawkular.metrics.clients.ptrans.graphite.GraphiteEventDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {

    if (msg.readableBytes() < 1) {
        return; // Nothing to do
    }/*from   w w w  .  ja  v a 2s. c o  m*/

    String data = msg.toString(CharsetUtil.UTF_8);

    data = data.trim();

    String[] lines = data.split("\\n");
    if (lines.length == 0) {
        return;
    }
    List<SingleMetric> metricList = new ArrayList<>(lines.length);

    for (String line : lines) {
        String[] items = line.split(" ");
        if (items.length != 3) {
            logger.debug("Unknown data format for [" + data + "], skipping");
            return;
        }

        long secondsSinceEpoch = Long.parseLong(items[2]);
        long timestamp = secondsSinceEpoch * 1000L;
        SingleMetric metric = new SingleMetric(items[0], timestamp, Double.parseDouble(items[1]));
        metricList.add(metric);
    }
    out.add(metricList);
}

From source file:org.hawkular.metrics.clients.ptrans.statsd.StatsdDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    ByteBuf buf = msg.content();

    if (buf.readableBytes() < 3) {
        // Not enough data - nothing to do.
        buf.clear();/*  www. j  a  va  2s  .c o  m*/
        ctx.close();
        return;
    }

    String packet = buf.toString(CharsetUtil.UTF_8).trim();
    if (!packet.contains(":")) {
        buf.clear();
        ctx.close();
        return;
    }

    String name = packet.substring(0, packet.indexOf(":"));
    String remainder = packet.substring(packet.indexOf(":") + 1);
    String valString;
    String type;
    if (remainder.contains("|")) {
        valString = remainder.substring(0, remainder.indexOf("|"));
        type = remainder.substring(remainder.indexOf("|") + 1);
    } else {
        valString = remainder;
        type = "";
    }
    Double value = Double.valueOf(valString);
    SingleMetric singleMetric = new SingleMetric(name, System.currentTimeMillis(), value,
            MetricType.from(type));
    out.add(singleMetric);
}

From source file:org.hawkular.metrics.clients.ptrans.syslog.DecoderUtil.java

License:Apache License

public static void decodeTheBuffer(ByteBuf data, List<Object> out) {

    if (data.readableBytes() < 1) {
        return; // Nothing to do
    }/*w w  w.j  a va  2  s  . co m*/

    String s = data.toString(CharsetUtil.UTF_8).trim();

    Matcher matcher = statsDPattern.matcher(s);
    if (matcher.matches()) {
        // StatsD packet
        String source = matcher.group(1);
        String val = matcher.group(2);
        List<SingleMetric> metrics = new ArrayList<>(1);
        SingleMetric metric = new SingleMetric(source, System.currentTimeMillis(), Double.valueOf(val));
        metrics.add(metric);
        return;
    }

    // Not statsD, so consider syslog. But first check if the message has the right format
    if (!s.contains("type=metric")) {
        return;
    }

    String text = extractPayload(s);

    if (text.contains("type=metric")) {

        text = text.trim();

        long now = System.currentTimeMillis();

        String[] entries = text.split(" ");

        List<SingleMetric> metrics = new ArrayList<>(entries.length);

        String cartName = null;
        if (text.contains("cart=")) {
            int pos = text.indexOf("cart=");
            cartName = text.substring(pos + 5, text.indexOf(' ', pos));
        }

        for (String entry : entries) {
            if (entry.equals("type=metric") || entry.startsWith("cart=")) {
                continue;
            }
            String[] keyVal = entry.split("=");
            double value = 0;
            try {
                value = Double.parseDouble(keyVal[1]);
                String source = keyVal[0];
                if (cartName != null) {
                    source = cartName + "." + source;
                }
                SingleMetric metric = new SingleMetric(source, now, value);
                metrics.add(metric);
            } catch (NumberFormatException e) {
                if (logger.isTraceEnabled()) {
                    logger.debug("Unknown number format for " + entry + ", skipping");
                }
            }
        }
        out.add(metrics);
    }
}

From source file:org.ireland.jnetty.JNettyServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);/*from   w w  w  . j  av a 2  s  . co m*/
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        List<Map.Entry<String, String>> headers = request.headers().entries();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : request.headers().entries()) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.data();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            writeResponse(ctx, trailer);
        }
    }
}

From source file:org.jboss.aerogear.webpush.netty.WebPushFrameListener.java

License:Apache License

private PushMessage buildPushMessage(final String subId, final ByteBuf data, final Http2Stream stream) {
    final String pushMessageId = UUID.randomUUID().toString();
    final Optional<String> receiptToken = stream.getProperty(pushReceiptPropertyKey);
    final Optional<Integer> ttl = stream.getProperty(ttlPropertyKey);
    return new DefaultPushMessage(pushMessageId, subId, receiptToken, data.toString(UTF_8), ttl);
}

From source file:org.kwh.tcp.server.ServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;
    try {/*from w  w  w .jav a 2  s .c o  m*/
        logger.info("New packet received");
        String receivedContent = in.toString(io.netty.util.CharsetUtil.US_ASCII);
        // send back message to the datalogger to notify it the bytes were
        // correctly received
        byte[] response = "@888\n".getBytes();
        final ByteBuf buffer = ctx.alloc().buffer(response.length);
        buffer.writeBytes(response);
        ctx.writeAndFlush(buffer);
        Consumer cons = new Consumer(receivedContent);
        es.submit(cons);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        in.release();
    }
}

From source file:org.lanternpowered.pingy.PingyProperties.java

License:MIT License

public void loadFavicon(Path directory) throws IOException {
    if (this.favicon.isEmpty()) {
        return;//from   ww  w  .j  a  va2s. co m
    }
    final Path faviconPath = directory.resolve(this.favicon);
    if (!Files.exists(faviconPath)) {
        throw new IOException("Favicon file does not exist.");
    }
    final BufferedImage image;
    try {
        image = ImageIO.read(faviconPath.toFile());
    } catch (IOException e) {
        throw new IOException("Unable to read the favicon file.");
    }
    if (image.getWidth() != 64) {
        throw new IOException("Favicon must be 64 pixels wide.");
    }
    if (image.getHeight() != 64) {
        throw new IOException("Favicon must be 64 pixels high.");
    }
    final ByteBuf buf = Unpooled.buffer();
    try {
        ImageIO.write(image, "PNG", new ByteBufOutputStream(buf));
        final ByteBuf base64 = Base64.encode(buf);

        try {
            this.faviconData = "data:image/png;base64," + base64.toString(StandardCharsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}