Search in sources :

Example 1 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class ListenerTest method testSuccessExecutionOnAbosoluteURI.

@Test
public void testSuccessExecutionOnAbosoluteURI() throws IOException {
    MockWebServer server = new MockWebServer();
    String content = "OK";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json").setBody(content));
    server.play();
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "2000").withProperty(CommonClientConfigKey.MaxAutoRetries, 1).withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://localhost:" + server.getPort() + "/testAsync/person");
    Server badServer = new Server("localhost:12345");
    Server goodServer = new Server("localhost:" + server.getPort());
    List<Server> servers = Lists.newArrayList(goodServer, badServer);
    BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder().withRule(new AvailabilityFilteringRule()).withPing(new DummyPing()).buildFixedServerListLoadBalancer(servers);
    IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500);
    TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig);
    List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener);
    LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners);
    HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last();
    assertEquals(200, response.getStatus().code());
    assertEquals(1, listener.executionStartCounter.get());
    assertEquals(1, listener.startWithServerCounter.get());
    assertEquals(0, listener.exceptionWithServerCounter.get());
    assertEquals(0, listener.executionFailedCounter.get());
    assertEquals(1, listener.executionSuccessCounter.get());
    assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue());
    assertTrue(listener.isContextChecked());
    assertTrue(listener.isCheckExecutionInfo());
    assertSame(response, listener.getResponse());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) ByteBuf(io.netty.buffer.ByteBuf) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) DummyPing(com.netflix.loadbalancer.DummyPing) MockWebServer(com.google.mockwebserver.MockWebServer) IClientConfig(com.netflix.client.config.IClientConfig) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Test(org.junit.Test)

Example 2 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class RibbonTest method testCommandWithMetaData.

@Test
@Ignore
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));
    }
    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());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) ByteBuf(io.netty.buffer.ByteBuf) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Observable(rx.Observable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockWebServer(com.google.mockwebserver.MockWebServer) Func1(rx.functions.Func1) Map(java.util.Map) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 3 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class NettyClientTest method testLoadBalancingWithTwoServers.

@Test
public void testLoadBalancingWithTwoServers() throws Exception {
    MockWebServer server = new MockWebServer();
    String content = "{\"name\": \"ribbon\", \"age\": 2}";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json").setBody(content));
    server.play();
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/person").withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null)).withHeader("Content-type", "application/json");
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    HttpClientListener externalListener = HttpClientListener.newHttpListener("external");
    lbObservables.subscribe(externalListener);
    Server server1 = new Server("localhost:" + server.getPort());
    Server server2 = new Server("localhost:" + port);
    lb.setServersList(Lists.newArrayList(server1, server2));
    RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) {

        @Override
        public boolean isRetriableException(Throwable e, boolean sameServer) {
            return true;
        }
    };
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(EmbeddedResources.defaultPerson.age, observer.obj.age);
    observer = new ObserverWithLatch<Person>();
    observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(server1);
    server.shutdown();
    // assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    stats = lbObservables.getServerStats(server2);
    // two requests to bad server because retry same server is set to 1
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
    final HttpClientListener listener = lbObservables.getListener();
    assertEquals(2, listener.getPoolAcquires());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {

        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 2;
        }
    });
    assertEquals(2, listener.getConnectionCount());
    assertEquals(0, listener.getPoolReuse());
    assertEquals(2, externalListener.getPoolAcquires());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) HttpServer(com.sun.net.httpserver.HttpServer) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) RequestSpecificRetryHandler(com.netflix.client.RequestSpecificRetryHandler) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) ByteBuf(io.netty.buffer.ByteBuf) HttpClientListener(io.reactivex.netty.servo.http.HttpClientListener) ServerStats(com.netflix.loadbalancer.ServerStats) RequestSpecificRetryHandler(com.netflix.client.RequestSpecificRetryHandler) RetryHandler(com.netflix.client.RetryHandler) DummyPing(com.netflix.loadbalancer.DummyPing) MockWebServer(com.google.mockwebserver.MockWebServer) IClientConfig(com.netflix.client.config.IClientConfig) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Person(com.netflix.ribbon.test.resources.EmbeddedResources.Person) Test(org.junit.Test)

Example 4 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class RibbonTest method testValidator.

@Test
public void testValidator() throws IOException, InterruptedException {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
    server.play();
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create().withConfigurationBasedServerList("localhost:" + server.getPort()));
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/").withMethod("GET").withResponseValidator(new ResponseValidator<HttpClientResponse<ByteBuf>>() {

        @Override
        public void validate(HttpClientResponse<ByteBuf> t1) throws UnsuccessfulResponseException {
            throw new UnsuccessfulResponseException("error", new IllegalArgumentException());
        }
    }).build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    request.toObservable().subscribe(new Action1<ByteBuf>() {

        @Override
        public void call(ByteBuf t1) {
        }
    }, new Action1<Throwable>() {

        @Override
        public void call(Throwable t1) {
            error.set(t1);
            latch.countDown();
        }
    }, new Action0() {

        @Override
        public void call() {
        }
    });
    latch.await();
    assertTrue(error.get() instanceof HystrixBadRequestException);
    assertTrue(error.get().getCause() instanceof UnsuccessfulResponseException);
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) Action0(rx.functions.Action0) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) HttpClientResponse(io.reactivex.netty.protocol.http.client.HttpClientResponse) MockWebServer(com.google.mockwebserver.MockWebServer) Test(org.junit.Test)

Example 5 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class RibbonTest method testCacheMiss.

@Test
public void testCacheMiss() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
    server.play();
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create().withConfigurationBasedServerList("localhost:" + server.getPort()).withMaxAutoRetriesNextServer(1));
    final String cacheKey = "somekey";
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test").withCacheProvider(cacheKey, new CacheProvider<ByteBuf>() {

        @Override
        public Observable<ByteBuf> get(String key, Map<String, Object> vars) {
            return Observable.error(new Exception("Cache miss again"));
        }
    }).withMethod("GET").withUriTemplate("/").build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    String result = toStringBlocking(request);
    assertEquals(content, result);
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Test(org.junit.Test)

Aggregations

MockResponse (com.google.mockwebserver.MockResponse)240 HttpURLConnection (java.net.HttpURLConnection)89 RecordedRequest (com.google.mockwebserver.RecordedRequest)80 HttpGet (org.apache.http.client.methods.HttpGet)54 HttpClient (org.apache.http.client.HttpClient)48 HttpResponse (org.apache.http.HttpResponse)42 MockWebServer (com.google.mockwebserver.MockWebServer)39 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)36 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)32 URLConnection (java.net.URLConnection)29 IOException (java.io.IOException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)25 InputStream (java.io.InputStream)23 LargeTest (android.test.suitebuilder.annotation.LargeTest)18 GZIPInputStream (java.util.zip.GZIPInputStream)18 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)18 OutputStream (java.io.OutputStream)17 GZIPOutputStream (java.util.zip.GZIPOutputStream)17 CookieManager (java.net.CookieManager)14 URL (java.net.URL)14