Search in sources :

Example 26 with HttpResponse

use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.

the class RetryPolicyTests method fixedDelayRetry.

@Test
public void fixedDelayRetry() {
    final int maxRetries = 5;
    final long delayMillis = 500;
    final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() {

        int count = -1;

        long previousAttemptMadeAt = -1;

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            if (count > 0) {
                Assertions.assertTrue(System.currentTimeMillis() >= previousAttemptMadeAt + delayMillis);
            }
            Assertions.assertTrue(count++ < maxRetries);
            previousAttemptMadeAt = System.currentTimeMillis();
            httpCallback.onSuccess(new MockHttpResponse(httpRequest, 500));
        }
    }).policies(new RetryPolicy(new FixedDelay(maxRetries, Duration.ofMillis(delayMillis)))).build();
    CountDownLatch latch = new CountDownLatch(1);
    pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"), RequestContext.NONE, CancellationToken.NONE, new HttpCallback() {

        @Override
        public void onSuccess(HttpResponse response) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable error) {
            latch.countDown();
        }
    });
    awaitOnLatch(latch, "fixedDelayRetry");
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) CancellationToken(com.azure.android.core.util.CancellationToken) HttpPipelineBuilder(com.azure.android.core.http.HttpPipelineBuilder) HttpCallback(com.azure.android.core.http.HttpCallback) HttpResponse(com.azure.android.core.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) Test(org.junit.jupiter.api.Test)

Example 27 with HttpResponse

use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.

the class RetryPolicyTests method exponentialDelayRetry.

@Test
public void exponentialDelayRetry() {
    final int maxRetries = 5;
    final long baseDelayMillis = 100;
    final long maxDelayMillis = 1000;
    ExponentialBackoff exponentialBackoff = new ExponentialBackoff(maxRetries, Duration.ofMillis(baseDelayMillis), Duration.ofMillis(maxDelayMillis));
    final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() {

        int count = -1;

        long previousAttemptMadeAt = -1;

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            if (count > 0) {
                long requestMadeAt = System.currentTimeMillis();
                long expectedToBeMadeAt = previousAttemptMadeAt + ((1 << (count - 1)) * (long) (baseDelayMillis * 0.95));
                Assertions.assertTrue(requestMadeAt >= expectedToBeMadeAt);
            }
            Assertions.assertTrue(count++ < maxRetries);
            previousAttemptMadeAt = System.currentTimeMillis();
            httpCallback.onSuccess(new MockHttpResponse(httpRequest, 503));
        }
    }).policies(new RetryPolicy(exponentialBackoff)).build();
    CountDownLatch latch = new CountDownLatch(1);
    pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"), RequestContext.NONE, CancellationToken.NONE, new HttpCallback() {

        @Override
        public void onSuccess(HttpResponse response) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable error) {
            latch.countDown();
        }
    });
    awaitOnLatch(latch, "exponentialDelayRetry");
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) CancellationToken(com.azure.android.core.util.CancellationToken) HttpPipelineBuilder(com.azure.android.core.http.HttpPipelineBuilder) HttpCallback(com.azure.android.core.http.HttpCallback) HttpResponse(com.azure.android.core.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) Test(org.junit.jupiter.api.Test)

Example 28 with HttpResponse

use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.

the class RetryPolicyTests method retryEndOn501.

@Test
public void retryEndOn501() {
    final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() {

        // Send 408, 500, 502, all retried, with a 501 ending
        private final int[] codes = new int[] { 408, 500, 502, 501 };

        private int count = 0;

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            httpCallback.onSuccess(new MockHttpResponse(httpRequest, codes[count++]));
        }
    }).policies(new RetryPolicy(new FixedDelay(3, Duration.of(0, ChronoUnit.MILLIS)))).build();
    final HttpResponse[] httpResponse = new HttpResponse[1];
    CountDownLatch latch = new CountDownLatch(1);
    pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"), RequestContext.NONE, CancellationToken.NONE, new HttpCallback() {

        @Override
        public void onSuccess(HttpResponse response) {
            httpResponse[0] = response;
            latch.countDown();
        }

        @Override
        public void onError(Throwable error) {
            try {
                throw new RuntimeException(error);
            } finally {
                latch.countDown();
            }
        }
    });
    awaitOnLatch(latch, "retryEndOn501");
    assertNotNull(httpResponse[0]);
    assertEquals(501, httpResponse[0].getStatusCode());
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) CancellationToken(com.azure.android.core.util.CancellationToken) HttpPipelineBuilder(com.azure.android.core.http.HttpPipelineBuilder) HttpCallback(com.azure.android.core.http.HttpCallback) HttpResponse(com.azure.android.core.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) Test(org.junit.jupiter.api.Test)

Example 29 with HttpResponse

use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.

the class RetryPolicy method retryIfRequired.

private PolicyCompleter.CompletionState retryIfRequired(HttpPipelinePolicyChain chain, HttpResponse response, Throwable error, PolicyCompleter completer, final int retryAttempts) {
    if (chain.getCancellationToken().isCancellationRequested()) {
        if (response != null) {
            response.close();
        }
        return completer.completedError(new IOException("Canceled."));
    }
    if (!shouldRetry(response, error, retryAttempts)) {
        if (response != null) {
            return completer.completed(response);
        } else {
            if (retryAttempts >= this.retryStrategy.getMaxRetries()) {
                final RuntimeException maxRetriedError = new RuntimeException(String.format("The max retries (%d times) for the service call is exceeded.", this.retryStrategy.getMaxRetries()));
                if (error != null) {
                    maxRetriedError.addSuppressed(error);
                }
                return completer.completedError(maxRetriedError);
            } else {
                return completer.completedError(error);
            }
        }
    } else {
        Duration delay = null;
        Throwable userError = null;
        try {
            delay = calculateRetryDelay(response, null, retryAttempts);
        } catch (Throwable e) {
            userError = e;
        } finally {
            if (response != null) {
                response.close();
            }
        }
        if (userError != null) {
            return completer.completedError(userError);
        } else {
            chain.processNextPolicy(chain.getRequest(), new NextPolicyCallback() {

                @Override
                public PolicyCompleter.CompletionState onSuccess(HttpResponse response, PolicyCompleter completer) {
                    return retryIfRequired(chain, response, null, completer, retryAttempts + 1);
                }

                @Override
                public PolicyCompleter.CompletionState onError(Throwable error, PolicyCompleter completer) {
                    return retryIfRequired(chain, null, error, completer, retryAttempts + 1);
                }
            }, delay.toMillis(), TimeUnit.MILLISECONDS);
            return completer.defer();
        }
    }
}
Also used : HttpResponse(com.azure.android.core.http.HttpResponse) Duration(org.threeten.bp.Duration) IOException(java.io.IOException) NextPolicyCallback(com.azure.android.core.http.NextPolicyCallback) PolicyCompleter(com.azure.android.core.http.PolicyCompleter)

Example 30 with HttpResponse

use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.

the class HttpLoggingPolicyTests method redactQueryParameters.

/**
 * Tests that a query string will be properly redacted before it is logged.
 */
@ParameterizedTest
@MethodSource("redactQueryParametersSupplier")
@ResourceLock("SYSTEM_OUT")
public void redactQueryParameters(String requestUrl, String expectedQueryString, Set<String> allowedQueryParameters) {
    HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC).setAllowedQueryParamNames(allowedQueryParameters))).httpClient(new NoOpHttpClient()).build();
    CountDownLatch latch = new CountDownLatch(1);
    // pipeline.send(new HttpRequest(HttpMethod.POST, requestUrl), CONTEXT, new HttpCallback() {..})
    pipeline.send(new HttpRequest(HttpMethod.POST, requestUrl), RequestContext.NONE, CancellationToken.NONE, new HttpCallback() {

        @Override
        public void onSuccess(HttpResponse response) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable error) {
            try {
                assertTrue(false, "unexpected call to pipeline::send onError" + error.getMessage());
            } finally {
                latch.countDown();
            }
        }
    });
    awaitOnLatch(latch, "redactQueryParameters");
    assertTrue(convertOutputStreamToString(logCaptureStream).contains(expectedQueryString));
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HttpPipeline(com.azure.android.core.http.HttpPipeline) HttpPipelineBuilder(com.azure.android.core.http.HttpPipelineBuilder) HttpCallback(com.azure.android.core.http.HttpCallback) HttpResponse(com.azure.android.core.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) ResourceLock(org.junit.jupiter.api.parallel.ResourceLock) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

HttpResponse (com.azure.android.core.http.HttpResponse)32 HttpCallback (com.azure.android.core.http.HttpCallback)21 CountDownLatch (java.util.concurrent.CountDownLatch)21 HttpRequest (com.azure.android.core.http.HttpRequest)20 HttpPipeline (com.azure.android.core.http.HttpPipeline)18 Test (org.junit.jupiter.api.Test)18 HttpPipelineBuilder (com.azure.android.core.http.HttpPipelineBuilder)14 CancellationToken (com.azure.android.core.util.CancellationToken)13 HttpHeaders (com.azure.android.core.http.HttpHeaders)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 IOException (java.io.IOException)5 NextPolicyCallback (com.azure.android.core.http.NextPolicyCallback)4 PolicyCompleter (com.azure.android.core.http.PolicyCompleter)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 HttpHeader (com.azure.android.core.http.HttpHeader)3 HttpMethod (com.azure.android.core.http.HttpMethod)3 PagedResponse (com.azure.android.core.rest.util.paging.PagedResponse)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3