Search in sources :

Example 36 with Response

use of com.ning.http.client.Response in project riposte by Nike-Inc.

the class AsyncHttpClientHelperTest method getCircuitBreaker_returns_CircuitBreakerDelegate_wrapping_default_CircuitBreakerForHttpStatusCode_using_host_as_the_key.

@DataProvider(value = { "true", "false" }, splitBy = "\\|")
@Test
public void getCircuitBreaker_returns_CircuitBreakerDelegate_wrapping_default_CircuitBreakerForHttpStatusCode_using_host_as_the_key(boolean useNettyEventLoop) {
    // given
    String host = UUID.randomUUID().toString();
    String url = "http://" + host + "/some/path";
    String method = "GET";
    AsyncHttpClient.BoundRequestBuilder reqMock = mock(AsyncHttpClient.BoundRequestBuilder.class);
    Optional<CircuitBreaker<Response>> customCb = Optional.empty();
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(url, method, reqMock, customCb, false);
    if (useNettyEventLoop)
        rbw.setCtx(ctxMock);
    // when
    Optional<CircuitBreaker<Response>> result = helperSpy.getCircuitBreaker(rbw);
    // then
    assertThat(result).isPresent();
    assertThat(result.get()).isInstanceOf(CircuitBreakerDelegate.class);
    CircuitBreakerDelegate<Response, Integer> wrapper = (CircuitBreakerDelegate) result.get();
    CircuitBreaker<Integer> delegate = (CircuitBreaker<Integer>) Whitebox.getInternalState(wrapper, "delegate");
    Function<Response, Integer> eventConverter = (Function<Response, Integer>) Whitebox.getInternalState(wrapper, "eventConverter");
    assertThat(delegate).isSameAs(CircuitBreakerForHttpStatusCode.getDefaultHttpStatusCodeCircuitBreakerForKey(host));
    Response responseMock = mock(Response.class);
    doReturn(42).when(responseMock).getStatusCode();
    assertThat(eventConverter.apply(responseMock)).isEqualTo(42);
    assertThat(eventConverter.apply(null)).isNull();
    if (useNettyEventLoop) {
        assertThat(Whitebox.getInternalState(delegate, "scheduler")).isEqualTo(eventLoopMock);
        assertThat(Whitebox.getInternalState(delegate, "stateChangeNotificationExecutor")).isEqualTo(eventLoopMock);
    } else {
        assertThat(Whitebox.getInternalState(delegate, "scheduler")).isNotEqualTo(eventLoopMock);
        assertThat(Whitebox.getInternalState(delegate, "stateChangeNotificationExecutor")).isNotEqualTo(eventLoopMock);
    }
}
Also used : CircuitBreaker(com.nike.fastbreak.CircuitBreaker) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Response(com.ning.http.client.Response) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Function(java.util.function.Function) CircuitBreakerDelegate(com.nike.fastbreak.CircuitBreakerDelegate) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Example 37 with Response

use of com.ning.http.client.Response in project riposte by Nike-Inc.

the class AsyncHttpClientHelperTest method executeAsyncHttpRequest_sets_up_and_executes_call_as_expected.

@DataProvider(value = { "true   |   true", "true   |   false", "false  |   true", "false  |   false" }, splitBy = "\\|")
@Test
public void executeAsyncHttpRequest_sets_up_and_executes_call_as_expected(boolean performSubspan, boolean currentTracingInfoNull) {
    // given
    Whitebox.setInternalState(helperSpy, "performSubSpanAroundDownstreamCalls", performSubspan);
    CircuitBreaker<Response> circuitBreakerMock = mock(CircuitBreaker.class);
    doReturn(Optional.of(circuitBreakerMock)).when(helperSpy).getCircuitBreaker(any(RequestBuilderWrapper.class));
    ManualModeTask<Response> cbManualTaskMock = mock(ManualModeTask.class);
    doReturn(cbManualTaskMock).when(circuitBreakerMock).newManualModeTask();
    String url = "http://localhost/some/path";
    String method = "GET";
    AsyncHttpClient.BoundRequestBuilder reqMock = mock(AsyncHttpClient.BoundRequestBuilder.class);
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(url, method, reqMock, Optional.empty(), false);
    AsyncResponseHandler responseHandlerMock = mock(AsyncResponseHandler.class);
    Span initialSpan = (currentTracingInfoNull) ? null : Tracer.getInstance().startRequestWithRootSpan("foo");
    Deque<Span> initialSpanStack = (currentTracingInfoNull) ? null : Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> initialMdc = (currentTracingInfoNull) ? null : MDC.getCopyOfContextMap();
    resetTracingAndMdc();
    // when
    CompletableFuture resultFuture = helperSpy.executeAsyncHttpRequest(rbw, responseHandlerMock, initialSpanStack, initialMdc);
    // then
    // Verify that the circuit breaker came from the getCircuitBreaker helper method and that its
    // throwExceptionIfCircuitBreakerIsOpen() method was called.
    verify(helperSpy).getCircuitBreaker(rbw);
    verify(cbManualTaskMock).throwExceptionIfCircuitBreakerIsOpen();
    // Verify that the inner request's execute method was called with a
    // AsyncCompletionHandlerWithTracingAndMdcSupport for the handler.
    ArgumentCaptor<AsyncHandler> executedHandlerCaptor = ArgumentCaptor.forClass(AsyncHandler.class);
    verify(reqMock).execute(executedHandlerCaptor.capture());
    AsyncHandler executedHandler = executedHandlerCaptor.getValue();
    assertThat(executedHandler).isInstanceOf(AsyncCompletionHandlerWithTracingAndMdcSupport.class);
    // Verify that the AsyncCompletionHandlerWithTracingAndMdcSupport was created with the expected args
    AsyncCompletionHandlerWithTracingAndMdcSupport achwtams = (AsyncCompletionHandlerWithTracingAndMdcSupport) executedHandler;
    assertThat(achwtams.completableFutureResponse).isSameAs(resultFuture);
    assertThat(achwtams.responseHandlerFunction).isSameAs(responseHandlerMock);
    assertThat(achwtams.performSubSpanAroundDownstreamCalls).isEqualTo(performSubspan);
    assertThat(achwtams.circuitBreakerManualTask).isEqualTo(Optional.of(cbManualTaskMock));
    if (performSubspan) {
        int initialSpanStackSize = (initialSpanStack == null) ? 0 : initialSpanStack.size();
        assertThat(achwtams.distributedTraceStackToUse).hasSize(initialSpanStackSize + 1);
        Span subspan = (Span) achwtams.distributedTraceStackToUse.peek();
        assertThat(subspan.getSpanName()).isEqualTo(initialSpanNameFromStrategy.get());
        if (initialSpan != null) {
            assertThat(subspan.getTraceId()).isEqualTo(initialSpan.getTraceId());
            assertThat(subspan.getParentSpanId()).isEqualTo(initialSpan.getSpanId());
        }
        assertThat(achwtams.mdcContextToUse.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId());
    } else {
        assertThat(achwtams.distributedTraceStackToUse).isSameAs(initialSpanStack);
        assertThat(achwtams.mdcContextToUse).isSameAs(initialMdc);
    }
    // Verify that the trace headers were added (or not depending on state).
    Span spanForDownstreamCall = achwtams.getSpanForCall();
    if (initialSpan == null && !performSubspan) {
        assertThat(spanForDownstreamCall).isNull();
        verifyNoMoreInteractions(reqMock);
    } else {
        assertThat(spanForDownstreamCall).isNotNull();
        verify(reqMock).setHeader(TraceHeaders.TRACE_SAMPLED, convertSampleableBooleanToExpectedB3Value(spanForDownstreamCall.isSampleable()));
        verify(reqMock).setHeader(TraceHeaders.TRACE_ID, spanForDownstreamCall.getTraceId());
        verify(reqMock).setHeader(TraceHeaders.SPAN_ID, spanForDownstreamCall.getSpanId());
        if (spanForDownstreamCall.getParentSpanId() == null) {
            verify(reqMock, never()).setHeader(eq(TraceHeaders.PARENT_SPAN_ID), anyString());
        } else {
            verify(reqMock).setHeader(TraceHeaders.PARENT_SPAN_ID, spanForDownstreamCall.getParentSpanId());
        }
        verify(reqMock, never()).setHeader(eq(TraceHeaders.SPAN_NAME), anyString());
    }
    // Verify that any subspan had request tagging performed.
    if (performSubspan) {
        strategyRequestTaggingArgs.get().verifyArgs(spanForDownstreamCall, rbw, wingtipsTagAndNamingAdapterMock);
    }
}
Also used : AsyncHandler(com.ning.http.client.AsyncHandler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Span(com.nike.wingtips.Span) Response(com.ning.http.client.Response) CompletableFuture(java.util.concurrent.CompletableFuture) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Example 38 with Response

use of com.ning.http.client.Response in project riposte by Nike-Inc.

the class AwsUtil method getAwsRegion.

/**
 * @param asyncHttpClientHelper The async HTTP client you want this method to use to make the AWS metadata call.
 *
 * @return A {@link CompletableFuture} that will contain the AWS region this app is running in (assuming it
 * completes successfully). If an error occurs retrieving the region from AWS then the error will be logged and
 * {@link AppInfo#UNKNOWN_VALUE} returned as the value.
 */
@NotNull
public static CompletableFuture<@NotNull String> getAwsRegion(@NotNull AsyncHttpClientHelper asyncHttpClientHelper) {
    return asyncHttpClientHelper.executeAsyncHttpRequest(asyncHttpClientHelper.getRequestBuilder(AMAZON_METADATA_DOCUMENT_URL, HttpMethod.GET), response -> {
        String region = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> resultMap = objectMapper.readValue(response.getResponseBody(), new TypeReference<Map<String, String>>() {
            });
            region = resultMap.get("region");
        } catch (Throwable t) {
            logger.error("Error retrieving region from AWS", t);
        }
        if (region == null) {
            logger.error("AWS metadata service returned null for region. Using 'unknown' as fallback.");
            region = AppInfo.UNKNOWN_VALUE;
        }
        return region;
    }).handle((region, error) -> {
        if (error != null) {
            logger.error("Unable to get region info from AWS metadata service.", error);
            return AppInfo.UNKNOWN_VALUE;
        }
        if (region == null) {
            logger.error("AWS metadata service returned null for region. Using 'unknown' as fallback.");
            region = AppInfo.UNKNOWN_VALUE;
        }
        return region;
    });
}
Also used : AppInfoImpl(com.nike.riposte.server.config.impl.AppInfoImpl) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) HttpMethod(io.netty.handler.codec.http.HttpMethod) CompletableFuture(java.util.concurrent.CompletableFuture) UnknownHostException(java.net.UnknownHostException) InetAddress(java.net.InetAddress) Map(java.util.Map) AppInfo(com.nike.riposte.server.config.AppInfo) TypeReference(com.fasterxml.jackson.core.type.TypeReference) NotNull(org.jetbrains.annotations.NotNull) AsyncHttpClientHelper(com.nike.riposte.client.asynchttp.ning.AsyncHttpClientHelper) Response(com.ning.http.client.Response) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NotNull(org.jetbrains.annotations.NotNull)

Example 39 with Response

use of com.ning.http.client.Response in project pinpoint by naver.

the class NingAsyncHttpClientIT method test.

@Test
public void test() throws Exception {
    AsyncHttpClient client = new AsyncHttpClient();
    try {
        Future<Response> f = client.preparePost(webServer.getCallHttpUrl()).addParameter("param1", "value1").execute();
        Response response = f.get();
    } finally {
        client.close();
    }
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    String destinationId = webServer.getHostAndPort();
    String httpUrl = webServer.getCallHttpUrl();
    verifier.verifyTrace(event("ASYNC_HTTP_CLIENT", AsyncHttpClient.class.getMethod("executeRequest", Request.class, AsyncHandler.class), null, null, destinationId, annotation("http.url", httpUrl)));
    verifier.verifyTraceCount(0);
}
Also used : Response(com.ning.http.client.Response) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) Test(org.junit.Test)

Example 40 with Response

use of com.ning.http.client.Response in project Singularity by HubSpot.

the class RawUserResponseParser method parse.

SingularityUserPermissionsResponse parse(Response response) throws IOException {
    if (response.getStatusCode() > 299) {
        throw WebExceptions.unauthorized(String.format("Got status code %d when verifying jwt", response.getStatusCode()));
    } else {
        String responseBody = response.getResponseBody();
        WebhookAuthUser user = objectMapper.readValue(responseBody, WebhookAuthUser.class);
        return new SingularityUserPermissionsResponse(Optional.of(new SingularityUser(user.getUid(), Optional.of(user.getUid()), authConfiguration.getDefaultEmailDomain().map(d -> String.format("%s@%s", user.getUid(), d)), user.getGroups(), user.getScopes(), true)), Optional.empty());
    }
}
Also used : WebhookAuthUser(com.hubspot.singularity.WebhookAuthUser) WebExceptions(com.hubspot.singularity.WebExceptions) SingularityUser(com.hubspot.singularity.SingularityUser) Inject(com.google.inject.Inject) AuthConfiguration(com.hubspot.singularity.config.AuthConfiguration) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Singularity(com.hubspot.singularity.Singularity) Optional(java.util.Optional) IOException(java.io.IOException) WebhookAuthUser(com.hubspot.singularity.WebhookAuthUser) Singleton(com.google.inject.Singleton) Response(com.ning.http.client.Response) SingularityUser(com.hubspot.singularity.SingularityUser)

Aggregations

Response (com.ning.http.client.Response)42 IOException (java.io.IOException)14 Test (org.junit.Test)11 AsyncHttpClient (com.ning.http.client.AsyncHttpClient)9 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 BoundRequestBuilder (com.ning.http.client.AsyncHttpClient.BoundRequestBuilder)6 Map (java.util.Map)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 Request (com.ning.http.client.Request)5 ExecutionException (java.util.concurrent.ExecutionException)5 AsyncHttpClientConfig (com.ning.http.client.AsyncHttpClientConfig)4 RequestBuilder (com.ning.http.client.RequestBuilder)4 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)4 HttpMethod (io.netty.handler.codec.http.HttpMethod)4 TimeoutException (java.util.concurrent.TimeoutException)4 NodesInfoResponse (org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse)4 Span (com.nike.wingtips.Span)3 AsyncCompletionHandler (com.ning.http.client.AsyncCompletionHandler)3 NettyAsyncHttpProvider (com.ning.http.client.providers.netty.NettyAsyncHttpProvider)3