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.mikesilversides.mod1.ServerTest.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    //ctx.write(msg);
    ByteBuf in = (ByteBuf) msg;
    System.out.println("returned msg = " + in.toString(io.netty.util.CharsetUtil.UTF_8));
    in.release();/*from  ww  w . j ava  2 s. c  om*/
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override/*www. ja  v  a 2  s . c  om*/
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:com.netflix.iep.http.ByteBufsTest.java

License:Apache License

@Test
public void json() throws Exception {
    byte[] data = "[{\"a\":1},{\"a\":2},{\"a\":3},{\"a\":4},{\"a\":5}]".getBytes("UTF-8");
    obs(data).compose(ByteBufs.json()).toBlocking().forEach(new Action1<ByteBuf>() {
        private int i = 0;

        @Override//from w w  w  .j ava 2s.c  om
        public void call(ByteBuf byteBuf) {
            String obj = byteBuf.toString(Charset.forName("UTF-8"));
            Assert.assertEquals(String.format("{\"a\":%d}", ++i), obj);
        }
    });
}

From source file:com.netflix.iep.http.ByteBufsTest.java

License:Apache License

@Test(expected = TooLongFrameException.class)
public void linesFailure() throws Exception {
    byte[] data = "1\n22\r\n3\r4".getBytes("UTF-8");
    obs(data).compose(ByteBufs.lines(1)).toBlocking().forEach(new Action1<ByteBuf>() {
        private int i = 0;

        @Override// ww  w .  ja v a 2 s  .c  om
        public void call(ByteBuf byteBuf) {
            String obj = byteBuf.toString(Charset.forName("UTF-8"));
            Assert.assertEquals(String.format("%d", ++i), obj);
        }
    });
}

From source file:com.netflix.iep.http.RxHttpTest.java

License:Apache License

@Test
public void simplePost() throws Exception {
    int code = 200;
    statusCode.set(code);/*from   w  w  w  . j  ava  2s  .c o m*/
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final StringBuilder builder = new StringBuilder();
    rxHttp.post(uri("/echo"), "text/plain", "foo bar".getBytes())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
                @Override
                public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> res) {
                    Assert.assertEquals(200, res.getStatus().code());
                    return res.getContent();
                }
            }).toBlocking().forEach(new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    builder.append(byteBuf.toString(Charset.defaultCharset()));
                }
            });

    Assert.assertEquals("foo bar", builder.toString());

    assertEquals(expected, statusCounts);
}

From source file:com.netflix.iep.http.RxHttpTest.java

License:Apache License

@Test
public void gzipPost() throws Exception {
    //set(client + ".niws.client.ReadTimeout", "1000");
    int code = 200;
    statusCode.set(code);//from www. ja  v  a 2  s . c o m
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    StringBuilder content = new StringBuilder();
    for (int i = 0; i < 500; ++i) {
        content.append(i).append(", ");
    }
    String body = content.toString();

    final StringBuilder builder = new StringBuilder();
    rxHttp.post(uri("/echo"), "text/plain", body.getBytes())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
                @Override
                public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> res) {
                    Assert.assertEquals(200, res.getStatus().code());
                    return res.getContent();
                }
            }).toBlocking().forEach(new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    builder.append(byteBuf.toString(Charset.defaultCharset()));
                }
            });

    Assert.assertEquals(body, builder.toString());

    assertEquals(expected, statusCounts);
}

From source file:com.netflix.iep.http.RxHttpTest.java

License:Apache License

@Test
public void postForm() throws Exception {
    int code = 200;
    statusCode.set(code);/*from   w w w . j a  v  a 2 s .  c om*/
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final StringBuilder builder = new StringBuilder();
    rxHttp.postForm(uri("/echo?foo=bar&name=John+Doe&pct=%2042%25"))
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() {
                @Override
                public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> res) {
                    Assert.assertEquals(200, res.getStatus().code());
                    return res.getContent();
                }
            }).toBlocking().forEach(new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    builder.append(byteBuf.toString(Charset.defaultCharset()));
                }
            });

    assertEquals(expected, statusCounts);
    Assert.assertEquals("foo=bar&name=John+Doe&pct=%2042%25", builder.toString());
}

From source file:com.netflix.iep.http.ServerSentEvent.java

License:Apache License

/**
 * Parse a server sent event line from the ByteBuf.
 *//*ww w.ja v a 2 s  .c  o  m*/
public static ServerSentEvent parse(ByteBuf buf) {
    return parse(buf.toString(Charset.forName("UTF-8")));
}

From source file:com.netflix.prana.http.api.TestUtils.java

License:Apache License

public static String getResponse(HttpClientRequest<ByteBuf> request, HttpClient<ByteBuf, ByteBuf> client) {
    return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {
        @Override/*from   www. ja  va2 s  . c o  m*/
        public Observable<String> call(HttpClientResponse<ByteBuf> response) {
            return response.getContent().map(new Func1<ByteBuf, String>() {
                @Override
                public String call(ByteBuf byteBuf) {
                    return byteBuf.toString(Charset.defaultCharset());
                }
            });
        }
    }).onErrorFlatMap(new Func1<OnErrorThrowable, Observable<String>>() {
        @Override
        public Observable<String> call(OnErrorThrowable onErrorThrowable) {
            throw onErrorThrowable;
        }
    }).toBlocking().first();
}

From source file:com.netflix.ribbon.examples.rx.AbstractRxMovieClient.java

License:Apache License

protected Observable<Void> searchCatalog() {
    List<String> searches = new ArrayList<String>(2);
    Collections.addAll(searches, "findById", "findRawMovieById", "findMovie(name, category)");

    return Observable.concat(Observable.from(triggerRecommendationsSearch()))
            .flatMap(new Func1<ByteBuf, Observable<List<Movie>>>() {
                @Override//  w ww  . j  a  v  a  2 s  . c om
                public Observable<List<Movie>> call(ByteBuf byteBuf) {
                    List<Movie> movies = new ArrayList<Movie>();
                    String lines = byteBuf.toString(Charset.defaultCharset());
                    for (String line : NEW_LINE_SPLIT_RE.split(lines)) {
                        movies.add(Movie.from(line));
                    }
                    return Observable.just(movies);
                }
            }).zipWith(searches, new Func2<List<Movie>, String, Void>() {
                @Override
                public Void call(List<Movie> movies, String query) {
                    System.out.println(format("    %s=%s", query, movies));
                    return null;
                }
            });
}