Search in sources :

Example 16 with HttpRequest

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

the class HttpLoggingPolicyTests method validateLoggingDoesNotChangeResponse.

/**
 * Tests that logging the response body doesn't consume the stream before it is returned from the service call.
 */
@ParameterizedTest(name = "[{index}] {displayName}")
@MethodSource("validateLoggingDoesNotConsumeSupplier")
@ResourceLock("SYSTEM_OUT")
public void validateLoggingDoesNotChangeResponse(byte[] content, byte[] data, int contentLength) {
    HttpRequest request = new HttpRequest(HttpMethod.GET, "https://test.com");
    HttpHeaders responseHeaders = new HttpHeaders().put("Content-Type", "application/json").put("Content-Length", Integer.toString(contentLength));
    HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))).httpClient(new HttpClient() {

        @Override
        public HttpCallDispatcher getHttpCallDispatcher() {
            return new HttpCallDispatcher();
        }

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            httpCallback.onSuccess(new MockHttpResponse(httpRequest, 200, responseHeaders, content));
        }
    }).build();
    CountDownLatch latch = new CountDownLatch(1);
    // pipeline.send(request, CONTEXT)
    pipeline.send(request, RequestContext.NONE, CancellationToken.NONE, new HttpCallback() {

        @Override
        public void onSuccess(HttpResponse response) {
            try {
                assertArrayEquals(data, response.getBodyAsByteArray());
            } finally {
                latch.countDown();
            }
        }

        @Override
        public void onError(Throwable error) {
            try {
                assertTrue(false, "unexpected call to pipeline::send onError" + error.getMessage());
            } finally {
                latch.countDown();
            }
        }
    });
    awaitOnLatch(latch, "validateLoggingDoesNotChangeResponse");
    String logString = convertOutputStreamToString(logCaptureStream);
    assertTrue(logString.contains(new String(data, StandardCharsets.UTF_8)));
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HttpHeaders(com.azure.android.core.http.HttpHeaders) 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) HttpCallDispatcher(com.azure.android.core.http.HttpCallDispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) HttpClient(com.azure.android.core.http.HttpClient) ResourceLock(org.junit.jupiter.api.parallel.ResourceLock) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 17 with HttpRequest

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

the class HttpLoggingPolicyTests method validateLoggingDoesNotChangeRequest.

/**
 * Tests that logging the request body doesn't consume the stream before it is sent over the network.
 */
@ParameterizedTest(name = "[{index}] {displayName}")
@MethodSource("validateLoggingDoesNotConsumeSupplier")
@ResourceLock("SYSTEM_OUT")
public void validateLoggingDoesNotChangeRequest(byte[] content, byte[] data, int contentLength) {
    final String requestUrl = "https://test.com";
    HttpHeaders requestHeaders = new HttpHeaders().put("Content-Type", "application/json").put("Content-Length", Integer.toString(contentLength));
    HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY))).httpClient(new HttpClient() {

        @Override
        public HttpCallDispatcher getHttpCallDispatcher() {
            return new HttpCallDispatcher();
        }

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            assertArrayEquals(data, httpRequest.getBody());
            httpCallback.onSuccess(new MockHttpResponse(httpRequest, 200));
        }
    }).build();
    CountDownLatch latch = new CountDownLatch(1);
    // pipeline.send(new HttpRequest(HttpMethod.POST, requestUrl, requestHeaders, content), CONTEXT)
    pipeline.send(new HttpRequest(HttpMethod.POST, requestUrl, requestHeaders, content), 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, "validateLoggingDoesNotChangeRequest");
    String logString = convertOutputStreamToString(logCaptureStream);
    assertTrue(logString.contains(new String(data, StandardCharsets.UTF_8)));
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HttpHeaders(com.azure.android.core.http.HttpHeaders) 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) HttpCallDispatcher(com.azure.android.core.http.HttpCallDispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) HttpClient(com.azure.android.core.http.HttpClient) ResourceLock(org.junit.jupiter.api.parallel.ResourceLock) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 18 with HttpRequest

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

the class HostPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    final UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl());
    try {
        httpRequest.setUrl(urlBuilder.setHost(host).toString());
    } catch (IllegalArgumentException error) {
        chain.completedError(error);
        return;
    }
    chain.processNextPolicy(httpRequest);
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) UrlBuilder(com.azure.android.core.http.util.UrlBuilder)

Example 19 with HttpRequest

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

the class HttpLoggingPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    // No logging will be performed, trigger a no-op.
    if (httpLogDetailLevel == HttpLogDetailLevel.NONE) {
        chain.processNextPolicy(chain.getRequest());
        return;
    }
    // final ClientLogger logger = new ClientLogger((String) context.getData("caller-method").orElse(""));
    // TODO: bring context ^
    final ClientLogger logger = new ClientLogger((String) "caller-method");
    if (!logger.canLogAtLevel(LogLevel.INFORMATIONAL)) {
        chain.processNextPolicy(chain.getRequest());
        return;
    }
    final long startNs = System.nanoTime();
    final HttpRequest httpRequest = chain.getRequest();
    // final Integer retryCount = context.getData(RETRY_COUNT_CONTEXT);
    // final Integer retryCount = null; // TODO: bring context ^
    StringBuilder requestLogMessage = new StringBuilder();
    if (httpLogDetailLevel.shouldLogUrl()) {
        requestLogMessage.append("--> ").append(httpRequest.getHttpMethod()).append(" ").append(this.getRedactedUrl(httpRequest.getUrl())).append(LINE_SEPARATOR);
    // if (retryCount != null) {
    // requestLogMessage.append(retryCount).append(LINE_SEPARATOR);
    // }
    }
    this.appendHeaders(logger, httpRequest.getHeaders(), requestLogMessage);
    if (httpLogDetailLevel.shouldLogBody()) {
        if (httpRequest.getBody() == null) {
            requestLogMessage.append("(empty body)").append(LINE_SEPARATOR).append("--> END ").append(httpRequest.getHttpMethod()).append(LINE_SEPARATOR);
        } else {
            final String requestContentType = httpRequest.getHeaders().getValue("Content-Type");
            final long requestContentLength = this.getContentLength(logger, httpRequest.getHeaders());
            if (this.isContentLoggable(requestContentType, requestContentLength)) {
                final String content = this.convertBytesToString(httpRequest.getBody(), logger);
                requestLogMessage.append(requestContentLength).append("-byte body:").append(LINE_SEPARATOR).append(content).append(LINE_SEPARATOR).append("--> END ").append(httpRequest.getHttpMethod()).append(LINE_SEPARATOR);
            } else {
                requestLogMessage.append(requestContentLength).append("-byte body: (content not logged)").append(LINE_SEPARATOR).append("--> END ").append(httpRequest.getHttpMethod()).append(LINE_SEPARATOR);
            }
        }
    }
    logger.info(requestLogMessage.toString());
    chain.processNextPolicy(httpRequest, new NextPolicyCallback() {

        @Override
        public PolicyCompleter.CompletionState onSuccess(HttpResponse response, PolicyCompleter completer) {
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            final String contentLengthHeaderValue = response.getHeaderValue("Content-Length");
            final String contentLengthMessage = (contentLengthHeaderValue == null || contentLengthHeaderValue.length() == 0) ? "unknown-length body" : contentLengthHeaderValue + "-byte body";
            StringBuilder responseLogMessage = new StringBuilder();
            if (httpLogDetailLevel.shouldLogUrl()) {
                responseLogMessage.append("<-- ").append(response.getStatusCode()).append(" ").append(getRedactedUrl(response.getRequest().getUrl())).append(" (").append(tookMs).append(" ms, ").append(contentLengthMessage).append(")").append(LINE_SEPARATOR);
            }
            appendHeaders(logger, response.getHeaders(), responseLogMessage);
            HttpResponse httpResponse = response;
            if (httpLogDetailLevel.shouldLogBody()) {
                final String responseContentType = response.getHeaderValue("Content-Type");
                final long responseContentLength = getContentLength(logger, response.getHeaders());
                if (isContentLoggable(responseContentType, responseContentLength)) {
                    httpResponse = response.buffer();
                    final String content = convertBytesToString(httpResponse.getBodyAsByteArray(), logger);
                    responseLogMessage.append("Response body:").append(LINE_SEPARATOR).append(content).append(LINE_SEPARATOR).append("<-- END HTTP");
                } else {
                    responseLogMessage.append("(body content not logged)").append(LINE_SEPARATOR).append("<-- END HTTP");
                }
            } else {
                responseLogMessage.append("<-- END HTTP");
            }
            logger.info(responseLogMessage.toString());
            return completer.completed(httpResponse);
        }

        @Override
        public PolicyCompleter.CompletionState onError(Throwable error, PolicyCompleter completer) {
            logger.warning("<-- HTTP FAILED: ", error);
            return completer.completedError(error);
        }
    });
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) ClientLogger(com.azure.android.core.logging.ClientLogger) HttpResponse(com.azure.android.core.http.HttpResponse) NextPolicyCallback(com.azure.android.core.http.NextPolicyCallback) PolicyCompleter(com.azure.android.core.http.PolicyCompleter)

Example 20 with HttpRequest

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

the class PortPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    final UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl());
    if (overwrite || urlBuilder.getPort() == null) {
        logger.info("Changing port to {}", port);
        try {
            httpRequest.setUrl(urlBuilder.setPort(port).toUrl().toString());
        } catch (MalformedURLException error) {
            chain.completedError(error);
            return;
        }
        chain.processNextPolicy(httpRequest);
    }
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) MalformedURLException(java.net.MalformedURLException) UrlBuilder(com.azure.android.core.http.util.UrlBuilder)

Aggregations

HttpRequest (com.azure.android.core.http.HttpRequest)37 HttpResponse (com.azure.android.core.http.HttpResponse)22 HttpCallback (com.azure.android.core.http.HttpCallback)18 CountDownLatch (java.util.concurrent.CountDownLatch)18 HttpPipeline (com.azure.android.core.http.HttpPipeline)17 HttpPipelineBuilder (com.azure.android.core.http.HttpPipelineBuilder)17 CancellationToken (com.azure.android.core.util.CancellationToken)15 Test (org.junit.jupiter.api.Test)13 HttpHeaders (com.azure.android.core.http.HttpHeaders)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 HttpClient (com.azure.android.core.http.HttpClient)4 UrlBuilder (com.azure.android.core.http.util.UrlBuilder)4 IOException (java.io.IOException)4 HttpHeader (com.azure.android.core.http.HttpHeader)3 ClientLogger (com.azure.android.core.logging.ClientLogger)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)3 List (java.util.List)3 ResourceLock (org.junit.jupiter.api.parallel.ResourceLock)3 MethodSource (org.junit.jupiter.params.provider.MethodSource)3 LIBRARY_PACKAGE_NAME (com.azure.android.communication.chat.BuildConfig.LIBRARY_PACKAGE_NAME)2