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.netflix.ribbon.examples.rx.common.Movie.java

License:Apache License

public static Movie from(ByteBuf byteBuf) {
    return from(byteBuf.toString(Charset.defaultCharset()));
}

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

License:Apache License

private Observable<Void> handleUpdateRecommendationsForUser(HttpServerRequest<ByteBuf> request,
        final HttpServerResponse<ByteBuf> response) {
    System.out.println("HTTP request -> update recommendations for user: " + request.getPath());
    final String userId = userIdFromPath(request.getPath());
    if (userId == null) {
        response.setStatus(HttpResponseStatus.BAD_REQUEST);
        return response.close();
    }/* www .j a va 2  s .  c o  m*/
    return request.getContent().flatMap(new Func1<ByteBuf, Observable<Void>>() {
        @Override
        public Observable<Void> call(ByteBuf byteBuf) {
            String movieId = byteBuf.toString(Charset.defaultCharset());
            System.out.println(format("    updating: {user=%s, movie=%s}", userId, movieId));
            synchronized (this) {
                Set<String> recommendations;
                if (userRecommendations.containsKey(userId)) {
                    recommendations = userRecommendations.get(userId);
                } else {
                    recommendations = new ConcurrentSet<String>();
                    userRecommendations.put(userId, recommendations);
                }
                recommendations.add(movieId);
            }
            response.setStatus(HttpResponseStatus.OK);
            return response.close();
        }
    });
}

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

License:Apache License

private Observable<Void> handleRegisterMovie(HttpServerRequest<ByteBuf> request,
        final HttpServerResponse<ByteBuf> response) {
    System.out.println("Http request -> register movie: " + request.getPath());
    return request.getContent().flatMap(new Func1<ByteBuf, Observable<Void>>() {
        @Override//from   w w w. ja  va  2  s. co  m
        public Observable<Void> call(ByteBuf byteBuf) {
            String formatted = byteBuf.toString(Charset.defaultCharset());
            System.out.println("    movie: " + formatted);
            try {
                Movie movie = Movie.from(formatted);
                movies.put(movie.getId(), movie);
                response.setStatus(HttpResponseStatus.CREATED);
            } catch (Exception e) {
                System.err.println("Invalid movie content");
                e.printStackTrace();
                response.setStatus(HttpResponseStatus.BAD_REQUEST);
            }
            return response.close();
        }
    });
}

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

License:Apache License

private Movie[] handleGetMoviesReply(Observable<HttpClientResponse<ByteBuf>> httpGet) {
    return httpGet.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Movie[]>>() {
        @Override//from ww w  .  j  ava 2s.  c  o  m
        public Observable<Movie[]> call(HttpClientResponse<ByteBuf> httpClientResponse) {
            return httpClientResponse.getContent().map(new Func1<ByteBuf, Movie[]>() {
                @Override
                public Movie[] call(ByteBuf byteBuf) {
                    String[] lines = byteBuf.toString(Charset.defaultCharset()).split("\n");
                    Movie[] movies = new Movie[lines.length];
                    for (int i = 0; i < movies.length; i++) {
                        movies[i] = Movie.from(lines[i]);
                    }
                    return movies;
                }
            });
        }
    }).toBlocking().first();
}

From source file:com.netflix.ribbon.http.TemplateBuilderTest.java

License:Apache License

@Test
public void testCacheKeyTemplates() {
    HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("test").build();

    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("testCacheKeyTemplates", ByteBuf.class)
            .withUriTemplate("/foo/{id}").withMethod("GET")
            .withCacheProvider("/cache/{id}", new FakeCacheProvider("/cache/5")).build();

    RibbonRequest<ByteBuf> request = template.requestBuilder().withRequestProperty("id", 5).build();
    ByteBuf result = request.execute();
    assertEquals("/cache/5", result.toString(Charset.defaultCharset()));
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

private static String toStringBlocking(RibbonRequest<ByteBuf> request) {
    return request.toObservable().map(new Func1<ByteBuf, String>() {
        @Override//  w w  w.j  av  a 2 s  .co  m
        public String call(ByteBuf t1) {
            return t1.toString(Charset.defaultCharset());
        }

    }).toBlocking().single();
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testCommand() throws IOException, InterruptedException, ExecutionException {
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    MockResponse response = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
            .setBody(content);//from   w w w  . j a  v  a 2s .c  o  m

    server.enqueue(response);
    server.enqueue(response);
    server.enqueue(response);
    server.play();

    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient",
            ClientOptions.create().withMaxAutoRetriesNextServer(3).withReadTimeout(300000)
                    .withConfigurationBasedServerList(
                            "localhost:12345, localhost:10092, localhost:" + server.getPort()));
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/")
            .withMethod("GET").build();

    RibbonRequest<ByteBuf> request = template.requestBuilder().build();

    String result = request.execute().toString(Charset.defaultCharset());
    assertEquals(content, result);
    // repeat the same request
    ByteBuf raw = request.execute();
    result = raw.toString(Charset.defaultCharset());
    raw.release();
    assertEquals(content, result);

    result = request.queue().get().toString(Charset.defaultCharset());
    assertEquals(content, result);
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testCommandWithMetaData() throws IOException, InterruptedException, ExecutionException {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    for (int i = 0; i < 6; i++) {
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
                .setBody(content));/*w ww .  ja  v  a2s  . com*/
    }
    server.play();

    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create()
            .withConfigurationBasedServerList("localhost:" + server.getPort()).withMaxAutoRetriesNextServer(3));

    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test").withUriTemplate("/")
            .withMethod("GET").withCacheProvider("somekey", new CacheProvider<ByteBuf>() {
                @Override
                public Observable<ByteBuf> get(String key, Map<String, Object> vars) {
                    return Observable.error(new Exception("Cache miss"));
                }
            }).build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    final AtomicBoolean success = new AtomicBoolean(false);
    RequestWithMetaData<ByteBuf> metaRequest = request.withMetadata();
    Observable<String> result = metaRequest.toObservable()
            .flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>() {
                @Override
                public Observable<String> call(final RibbonResponse<Observable<ByteBuf>> response) {
                    success.set(response.getHystrixInfo().isSuccessfulExecution());
                    return response.content().map(new Func1<ByteBuf, String>() {
                        @Override
                        public String call(ByteBuf t1) {
                            return t1.toString(Charset.defaultCharset());
                        }
                    });
                }
            });
    String s = result.toBlocking().single();
    assertEquals(content, s);
    assertTrue(success.get());

    Future<RibbonResponse<ByteBuf>> future = metaRequest.queue();
    RibbonResponse<ByteBuf> response = future.get();
    assertTrue(future.isDone());
    assertEquals(content, response.content().toString(Charset.defaultCharset()));
    assertTrue(response.getHystrixInfo().isSuccessfulExecution());

    RibbonResponse<ByteBuf> result1 = metaRequest.execute();
    assertEquals(content, result1.content().toString(Charset.defaultCharset()));
    assertTrue(result1.getHystrixInfo().isSuccessfulExecution());
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testFallback() throws IOException {
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create()
            .withConfigurationBasedServerList("localhost:12345").withMaxAutoRetriesNextServer(1));
    final String fallback = "fallback";
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/")
            .withMethod("GET").withFallbackProvider(new FallbackHandler<ByteBuf>() {
                @Override/*from  w  ww  .  java 2s.c  om*/
                public Observable<ByteBuf> getFallback(HystrixExecutableInfo<?> hystrixInfo,
                        Map<String, Object> requestProperties) {
                    try {
                        return Observable.just(Unpooled.buffer().writeBytes(fallback.getBytes("UTF-8")));
                    } catch (UnsupportedEncodingException e) {
                        return Observable.error(e);
                    }
                }
            }).build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    final AtomicReference<HystrixExecutableInfo<?>> hystrixInfo = new AtomicReference<HystrixExecutableInfo<?>>();
    final AtomicBoolean failed = new AtomicBoolean(false);
    Observable<String> result = request.withMetadata().toObservable()
            .flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>() {
                @Override
                public Observable<String> call(final RibbonResponse<Observable<ByteBuf>> response) {
                    hystrixInfo.set(response.getHystrixInfo());
                    failed.set(response.getHystrixInfo().isFailedExecution());
                    return response.content().map(new Func1<ByteBuf, String>() {
                        @Override
                        public String call(ByteBuf t1) {
                            return t1.toString(Charset.defaultCharset());
                        }
                    });
                }
            });
    String s = result.toBlocking().single();
    // this returns true only after the blocking call is done
    assertTrue(hystrixInfo.get().isResponseFromFallback());
    assertTrue(failed.get());
    assertEquals(fallback, s);
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testObserve() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    server.enqueue(//w  ww .j a  va 2  s. co  m
            new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
    server.enqueue(
            new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
    server.play();
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient",
            ClientOptions.create().withMaxAutoRetriesNextServer(3).withReadTimeout(300000)
                    .withConfigurationBasedServerList(
                            "localhost:12345, localhost:10092, localhost:" + server.getPort()));
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/")
            .withMethod("GET").build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    Observable<ByteBuf> result = request.observe();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> fromCommand = new AtomicReference<String>();
    // We need to wait until the response is received and processed by event loop
    // and make sure that subscribing to it again will not cause ByteBuf ref count issue
    result.toBlocking().last();
    result.subscribe(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf t1) {
            try {
                fromCommand.set(t1.toString(Charset.defaultCharset()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    });
    latch.await();
    assertEquals(content, fromCommand.get());

    Observable<RibbonResponse<Observable<ByteBuf>>> metaResult = request.withMetadata().observe();
    String result2 = "";
    // We need to wait until the response is received and processed by event loop
    // and make sure that subscribing to it again will not cause ByteBuf ref count issue
    metaResult.toBlocking().last();
    result2 = metaResult.flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<ByteBuf>>() {
        @Override
        public Observable<ByteBuf> call(RibbonResponse<Observable<ByteBuf>> t1) {
            return t1.content();
        }
    }).map(new Func1<ByteBuf, String>() {
        @Override
        public String call(ByteBuf t1) {
            return t1.toString(Charset.defaultCharset());
        }
    }).toBlocking().single();
    assertEquals(content, result2);
}