io.reactivex.netty.protocol.http.client.HttpClientResponse Java Examples

The following examples show how to use io.reactivex.netty.protocol.http.client.HttpClientResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubmitToAbsoluteURI() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person");
    LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient();
    // final List<Person> result = Lists.newArrayList();
    Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request);
    Person person = getPersonObservable(response).toBlocking().single();
    assertEquals(EmbeddedResources.defaultPerson, person);
    // need to sleep to wait until connection is released
    final HttpClientListener listener = observableClient.getListener();
    assertEquals(1, listener.getConnectionCount());
    assertEquals(1, listener.getPoolAcquires());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {
        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 1;
        }
    });
}
 
Example #2
Source File: NewsServiceApp.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@Bean
HttpNewsService externalNews() {
    return () -> HttpClient.newClient(new InetSocketAddress(NEWS_SERVER_PORT))
                           .createGet("")
                           .flatMap(HttpClientResponse::getContent)
                           .flatMapIterable(bb -> {
                               try {
                                   return new ObjectMapper().readValue(
                                           bb.toString(Charset.defaultCharset()),
                                           new TypeReference<ArrayList<News>>() {}
                                   );
                               }
                               catch (IOException e) {
                                   throw new RuntimeException(e);
                               }
                           });
}
 
Example #3
Source File: HttpUtilsTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = { "unit" })
public void verifyConversionOfHttpResponseHeadersToMap() throws UnsupportedEncodingException {
    HttpHeaders headersMap = new DefaultHttpHeaders();
    headersMap.add(HttpConstants.HttpHeaders.OWNER_FULL_NAME, OWNER_FULL_NAME_VALUE);

    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0,
            HttpResponseStatus.ACCEPTED,
            headersMap);
    HttpResponseHeaders httpResponseHeaders = new HttpClientResponse(httpResponse, null).getHeaders();
    Set<Entry<String, String>> resultHeadersSet = HttpUtils.asMap(httpResponseHeaders).entrySet();
    
    assertThat(resultHeadersSet.size()).isEqualTo(1);
    Entry<String, String> entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
    
    List<Entry<String, String>> resultHeadersList = HttpUtils.unescape(httpResponseHeaders.entries());
    assertThat(resultHeadersList.size()).isEqualTo(1);
    entry = resultHeadersSet.iterator().next();
    assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME);
    assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE));
}
 
Example #4
Source File: RxMovieTransportExample.java    From ribbon with Apache License 2.0 6 votes vote down vote up
private Observable<Void> updateRecommendation(String user, Movie movie) {
    HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.createPost(format("/users/%s/recommendations", user))
            .withHeader("X-Platform-Version", "xyz")
            .withHeader("X-Auth-Token", "abc")
            .withRawContentSource(Observable.just(movie.getId()), new StringTransformer());

    return client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() {
        @Override
        public Observable<Void> call(HttpClientResponse<ByteBuf> httpClientResponse) {
            if (httpClientResponse.getStatus().code() / 100 != 2) {
                return Observable.error(new RuntimeException(
                        format("HTTP request failed (status code=%s)", httpClientResponse.getStatus())));
            }
            return Observable.empty();
        }
    });
}
 
Example #5
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostWithByteBuf() throws Exception {
    Person myPerson = new Person("netty", 5);
    ObjectMapper mapper = new ObjectMapper();
    byte[] raw = mapper.writeValueAsBytes(myPerson);
    ByteBuf buffer = Unpooled.copiedBuffer(raw);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(SERVICE_URI + "testAsync/person")
            .withHeader("Content-type", "application/json")
            .withHeader("Content-length", String.valueOf(raw.length))
            .withContent(buffer);
    LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(
            DefaultClientConfigImpl.getClientConfigWithDefaultValues().set(CommonClientConfigKey.ReadTimeout, 10000));
    Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request);
    Person person = getPersonObservable(response).toBlocking().single();
    assertEquals(myPerson, person);
}
 
Example #6
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testPoolReuse() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person");
    LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(
            IClientConfig.Builder.newBuilder().withDefaultValues()
            .withMaxAutoRetries(1)
            .withMaxAutoRetriesNextServer(1).build());
    Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request);
    Person person = getPersonObservable(response).toBlocking().single();
    assertEquals(EmbeddedResources.defaultPerson, person);
    response = observableClient.submit(request);
    person = getPersonObservable(response).toBlocking().single();
    assertEquals(EmbeddedResources.defaultPerson, person);
    final HttpClientListener listener = observableClient.getListener();
    assertEquals(2, listener.getPoolAcquires());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {
        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 2;
        }
    });
    assertEquals(1, listener.getConnectionCount());
    assertEquals(1, listener.getPoolReuse());
}
 
Example #7
Source File: HttpClientMockWrapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public HttpClientResponse<ByteBuf> asHttpClientResponse() {
    if (this.networkFailure != null) {
        return null;
    }

    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(status)).when(resp).getStatus();
    Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content))).when(resp).getContent();

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class.getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }

    return resp;
}
 
Example #8
Source File: HttpClientMockWrapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
private HttpClientMockWrapper(long responseAfterMillis, final HttpClientResponse<ByteBuf> httpClientResponse, final Exception e) {
    httpClient = Mockito.mock(CompositeHttpClient.class);
    assert httpClientResponse == null || e == null;

    Mockito.doAnswer(new Answer() {
        @Override
        public Observable<HttpClientResponse<ByteBuf>> answer(InvocationOnMock invocationOnMock) throws Throwable {
            RxClient.ServerInfo serverInfo = invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class);
            HttpClientRequest<ByteBuf> req = invocationOnMock.getArgumentAt(1, HttpClientRequest.class);

            requests.add(new ImmutablePair<>(req, serverInfo));

            if (responseAfterMillis <= 0) {
                return httpClientResponseOrException(httpClientResponse, e);
            } else {
                return Observable.timer(responseAfterMillis, TimeUnit.MILLISECONDS).flatMap(t -> httpClientResponseOrException(httpClientResponse, e));
            }
        }
    }).when(httpClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class));
}
 
Example #9
Source File: ResponseUtils.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to read the content of an error response as {@code text/plain;charset=utf-8}, otherwise the content
 * will be ignored and a string detailing the Content-Type that was not processed.
 * <p>
 * <b>NOTE:</b>
 * <i>
 *     This method MUST be called from the netty-io thread otherwise the content of the response will not be
 *     available because if will be released automatically as soon as the netty-io thread is left.
 * </i>
 * @param resp  The response to attempt to read from
 * @return An {@link Observable} representing the {@code text/plain;charset=utf-8} response content if it existed
 *         or an error message indicating the content-type that was not attempted to read.
 */
@NotNull
static Observable<String> attemptToReadErrorResponse(@NotNull final HttpClientResponse<ByteBuf> resp) {
    final HttpResponseHeaders headers = resp.getHeaders();
    final String contentType = resp.getHeaders().get(HttpHeaderNames.CONTENT_TYPE);
    if (headers.isContentLengthSet() && headers.getContentLength() > 0 ) {
        if (contentType != null && contentType.startsWith("text/plain")) {
            return resp.getContent()
                .map(r -> r.toString(StandardCharsets.UTF_8));
        } else {
            resp.ignoreContent();
            final String errMsg = getErrMsg(contentType);
            return Observable.just(errMsg);
        }
    } else {
        return Observable.just("");
    }
}
 
Example #10
Source File: ResponseUtilsTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void attemptToReadErrorResponse_responseContentIgnoredByDefaultWhenNotString() throws Exception {
    final String errMsg = "lies";
    final byte[] bytes = errMsg.getBytes(StandardCharsets.UTF_8);
    final HttpClientResponse<ByteBuf> resp = response(Unpooled.copiedBuffer(bytes), (headers) -> {
        headers.add("Content-Type", "application/json;charset=utf-8");
        headers.add("Content-Length", bytes.length);
    });

    final String err = ResponseUtils.attemptToReadErrorResponse(resp).toBlocking().first();
    assertThat(err).isNotEqualTo("lies");

    try {
        resp.getContent().toBlocking().first();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage()).isEqualTo("Content stream is already disposed.");
    }
}
 
Example #11
Source File: RxMovieTransportExample.java    From ribbon with Apache License 2.0 6 votes vote down vote up
private Observable<Void> registerMovie(Movie movie) {
    HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.createPost("/movies")
            .withHeader("X-Platform-Version", "xyz")
            .withHeader("X-Auth-Token", "abc")
            .withRawContentSource(Observable.just(movie), new RxMovieTransformer());

    return client.submit(httpRequest).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() {
        @Override
        public Observable<Void> call(HttpClientResponse<ByteBuf> httpClientResponse) {
            if (httpClientResponse.getStatus().code() / 100 != 2) {
                return Observable.error(new RuntimeException(
                        format("HTTP request failed (status code=%s)", httpClientResponse.getStatus())));
            }
            return Observable.empty();
        }
    });
}
 
Example #12
Source File: SecuredTransportFactory.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public HttpClient<ByteBuf, ByteBuf> newHttpClient(final IClientConfig config) {
    final List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = new ArrayList<>();
    listeners.add(createBearerHeaderAdder());
    final PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineConfigurator = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, 
            HttpClientRequest<ByteBuf>>(new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(),
            new HttpObjectAggregationConfigurator(maxChunkSize));
    final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
            .withClientConfig(config)
            .withExecutorListeners(listeners)
            .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
            .withPipelineConfigurator(pipelineConfigurator)
            .withPoolCleanerScheduler(RibbonTransport.poolCleanerScheduler)
            .build();

    return client;
}
 
Example #13
Source File: SimpleGet.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings
public static void main(String[] args) throws Exception {
    LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient();
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://www.google.com/");
    final CountDownLatch latch = new CountDownLatch(1);
    client.submit(request)
        .toBlocking()
        .forEach(new Action1<HttpClientResponse<ByteBuf>>() {
            @Override
            public void call(HttpClientResponse<ByteBuf> t1) {
                System.out.println("Status code: " + t1.getStatus());
                t1.getContent().subscribe(new Action1<ByteBuf>() {

                    @Override
                    public void call(ByteBuf content) {
                        System.out.println("Response content: " + content.toString(Charset.defaultCharset()));
                        latch.countDown();
                    }
                    
                });
            }
        });
    latch.await(2, TimeUnit.SECONDS);
}
 
Example #14
Source File: TestUtils.java    From Prana with Apache License 2.0 6 votes vote down vote up
public static String getResponse(HttpClientRequest<ByteBuf> request, HttpClient<ByteBuf, ByteBuf> client) {
    return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {
        @Override
        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();
}
 
Example #15
Source File: HttpResourceObservableCommand.java    From ribbon with Apache License 2.0 6 votes vote down vote up
public HttpResourceObservableCommand(HttpClient<ByteBuf, ByteBuf> httpClient,
                                     HttpClientRequest<ByteBuf> httpRequest, String hystrixCacheKey,
                                     Map<String, Object> requestProperties,
                                     FallbackHandler<T> fallbackHandler,
                                     ResponseValidator<HttpClientResponse<ByteBuf>> validator,
                                     Class<? extends T> classType,
                                     HystrixObservableCommand.Setter setter) {
    super(setter);
    this.httpClient = httpClient;
    this.fallbackHandler = fallbackHandler;
    this.validator = validator;
    this.httpRequest = httpRequest;
    this.hystrixCacheKey = hystrixCacheKey;
    this.classType = classType;
    this.requestProperties = requestProperties;
}
 
Example #16
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testObservable() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person");
    LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient();
    Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request);
    Person person = getPersonObservable(response).toBlocking().single();
    assertEquals(EmbeddedResources.defaultPerson, person);
    final HttpClientListener listener = observableClient.getListener();
    assertEquals(1, listener.getPoolAcquires());
    assertEquals(1, listener.getConnectionCount());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {
        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 1;
        }
    });
}
 
Example #17
Source File: LoadBalancingHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
/**
 * Subject an operation to run in the load balancer
 * 
 * @param request
 * @param errorHandler
 * @param requestConfig
 * @param rxClientConfig
 * @return
 */
private Observable<HttpClientResponse<O>> submit(final Server server, final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig, final ClientConfig rxClientConfig) {
    RetryHandler retryHandler = errorHandler;
    if (retryHandler == null) {
        retryHandler = getRequestRetryHandler(request, requestConfig);
    }
    
    final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl.getEmptyConfig() : requestConfig;
    final ExecutionContext<HttpClientRequest<I>> context = new ExecutionContext<HttpClientRequest<I>>(request, config, this.getClientConfig(), retryHandler);
    
    Observable<HttpClientResponse<O>> result = submitToServerInURI(request, config, rxClientConfig, retryHandler, context);
    if (result == null) {
        LoadBalancerCommand<HttpClientResponse<O>> command;
        if (retryHandler != defaultRetryHandler) {
            // need to create new builder instead of the default one
            command = LoadBalancerCommand.<HttpClientResponse<O>>builder()
                    .withExecutionContext(context)
                    .withLoadBalancerContext(lbContext)
                    .withListeners(listeners)
                    .withClientConfig(this.getClientConfig())
                    .withRetryHandler(retryHandler)
                    .withServer(server)
                    .build();
        }
        else {
            command = defaultCommandBuilder;
        }
        
        result = command.submit(requestToOperation(request, getRxClientConfig(config, rxClientConfig)));
    }
    return result;
}
 
Example #18
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator,
        ILoadBalancer loadBalancer, IClientConfig config) {
    return LoadBalancingHttpClient.<I, O>builder()
            .withLoadBalancer(loadBalancer)
            .withClientConfig(config)
            .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
            .withPipelineConfigurator(pipelineConfigurator)
            .withPoolCleanerScheduler(poolCleanerScheduler)
            .build();
}
 
Example #19
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static <I> LoadBalancingHttpClient<I, ServerSentEvent> newSSEClient(PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<I>> pipelineConfigurator,
        ILoadBalancer loadBalancer, IClientConfig config) {
    return SSEClient.<I>sseClientBuilder()
            .withLoadBalancer(loadBalancer)
            .withClientConfig(config)
            .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
            .withPipelineConfigurator(pipelineConfigurator)
            .build();
}
 
Example #20
Source File: TestRouteWithSimpleFaultTolerance.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
private static Observable<BackendResponse> getDataFromBackend(String url) {
    return RxNetty.createHttpClient("localhost", 9999)
            .submit(HttpClientRequest.createGet(url))
            .timeout(50, TimeUnit.MILLISECONDS) // change the timeout value to see how response differs
            .flatMap((HttpClientResponse<ByteBuf> r) -> {
                Observable<BackendResponse> bytesToJson = r.getContent().map(b -> {
                    return BackendResponse.fromJson(new ByteBufInputStream(b));
                });
                return bytesToJson;
            }).onErrorResumeNext(t -> {
                BackendResponse fallback = new BackendResponse(0, -1, -1, -1, new String[] {});
                return Observable.just(fallback);
            });
}
 
Example #21
Source File: KaryonHttpModuleTest.java    From karyon with Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus sendRequest(String path, RxServer server) throws Exception {
    return (HttpResponseStatus) RxNetty.createHttpGet("http://localhost:" + server.getServerPort() + path)
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<?>>() {
                @Override
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS);
}
 
Example #22
Source File: GatewayServiceConfigurationReaderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Test(groups = "simple")
public void mockInitializeReaderAsyncWithResourceToken() throws Exception {
    mockGatewayServiceConfigurationReader = new GatewayServiceConfigurationReader(new URI(TestConfigurations.HOST),
            true, "SampleResourceToken", connectionPolicy, baseAuthorizationTokenProvider, mockHttpClient);

    HttpClientResponse<ByteBuf> mockedResponse = getMockResponse(databaseAccountJson);

    Mockito.when(mockHttpClient.submit(Matchers.any(RxClient.ServerInfo.class), Matchers.any()))
            .thenReturn(Observable.just(mockedResponse));

    Single<DatabaseAccount> databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync();
    validateSuccess(databaseAccount, expectedDatabaseAccount);
}
 
Example #23
Source File: BearerHeaderAdder.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public void onExecutionSuccess(ExecutionContext<HttpClientRequest<ByteBuf>> context, HttpClientResponse<ByteBuf> response, ExecutionInfo info) {
    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) context.get(KeycloakSecurityContextAssociation.class.getName());
    if (securityContext != null) {
        KeycloakSecurityContextAssociation.associate(securityContext);
    } else {
        KeycloakSecurityContextAssociation.disassociate();
    }
}
 
Example #24
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUriFromRedirectResponse_200() throws Exception {
    final URI mesosUri = URI.create("http://127.1.0.1:5050/api/v1/scheduler");
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );
    final URI uri = MesosClient.getUriFromRedirectResponse(mesosUri, response);
    assertThat(uri).isEqualTo(URI.create("http://127.1.0.1:5050/api/v1/scheduler"));
}
 
Example #25
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUriFromRedirectResponse() throws Exception {
    final URI mesosUri = URI.create("http://127.1.0.1:5050/api/v1/scheduler");
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
    nettyResponse.headers().add("Location", "//127.1.0.2:5050");
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );
    final URI uri = MesosClient.getUriFromRedirectResponse(mesosUri, response);
    assertThat(uri).isEqualTo(URI.create("http://127.1.0.2:5050/api/v1/scheduler"));
}
 
Example #26
Source File: GatewayServiceConfigurationReaderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
private HttpClientResponse<ByteBuf> getMockResponse(String databaseAccountJson) {
    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(200)).when(resp).getStatus();
    ByteBuf byteBuffer = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, databaseAccountJson);

    Mockito.doReturn(Observable.just(byteBuffer))
            .when(resp).getContent();

    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders = httpHeaders.add(HttpConstants.HttpHeaders.CONTENT_LENGTH, byteBuffer.writerIndex());

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(200), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class
                .getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }
    return resp;
}
 
Example #27
Source File: RxMovieServerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testMovieRegistration() {
    String movieFormatted = ORANGE_IS_THE_NEW_BLACK.toString();

    HttpResponseStatus statusCode = RxNetty.createHttpPost(baseURL + "/movies", Observable.just(movieFormatted), new StringTransformer())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() {
                @Override
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).toBlocking().first();

    assertEquals(HttpResponseStatus.CREATED, statusCode);
    assertEquals(ORANGE_IS_THE_NEW_BLACK, movieServer.movies.get(ORANGE_IS_THE_NEW_BLACK.getId()));
}
 
Example #28
Source File: ResponseUtilsTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
private static HttpClientResponse<ByteBuf> response(
    @NotNull final ByteBuf content,
    @NotNull final Action1<HttpHeaders> headerTransformer
) {
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    headerTransformer.call(nettyResponse.headers());
    final UnicastContentSubject<ByteBuf> subject = UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS);
    subject.onNext(content);
    return new HttpClientResponse<>(
        nettyResponse,
        subject
    );
}
 
Example #29
Source File: RxDocumentClientUnderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
RxGatewayStoreModel createRxGatewayProxy(
        ISessionContainer sessionContainer,
        ConsistencyLevel consistencyLevel,
        QueryCompatibilityMode queryCompatibilityMode,
        UserAgentContainer userAgentContainer,
        GlobalEndpointManager globalEndpointManager,
        CompositeHttpClient<ByteBuf, ByteBuf> rxOrigClient) {

    origHttpClient = rxOrigClient;
    spyHttpClient = Mockito.spy(rxOrigClient);

    doAnswer((Answer<Observable<HttpClientResponse<ByteBuf>>>) invocationOnMock -> {

        RxClient.ServerInfo serverInfo =
                invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class);

        HttpClientRequest<ByteBuf> request
                = invocationOnMock.getArgumentAt(1, HttpClientRequest.class);

        httpRequests.add(request);

        Observable<HttpClientResponse<ByteBuf>> httpRespObs =
                origHttpClient.submit(serverInfo, request);

        return httpRespObs;
    }).when(spyHttpClient).submit( anyObject(),
            (HttpClientRequest) anyObject());

    return super.createRxGatewayProxy(sessionContainer,
            consistencyLevel,
            queryCompatibilityMode,
            userAgentContainer,
            globalEndpointManager,
            spyHttpClient);
}
 
Example #30
Source File: GatewayServiceConfigurationReaderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Test(groups = "simple")
public void mockInitializeReaderAsync() throws Exception {

    HttpClientResponse<ByteBuf> mockedResponse = getMockResponse(databaseAccountJson);

    Mockito.when(mockHttpClient.submit(Matchers.any(RxClient.ServerInfo.class), Matchers.any()))
            .thenReturn(Observable.just(mockedResponse));

    Single<DatabaseAccount> databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync();
    validateSuccess(databaseAccount, expectedDatabaseAccount);
}