Search in sources :

Example 21 with HttpHeaders

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

the class AddHeadersPolicyTest method clientProvidedMultipleHeader.

@Test
public void clientProvidedMultipleHeader() throws Exception {
    String customRequestId = "request-id-value";
    final HttpHeaders headers = new HttpHeaders();
    headers.put("x-ms-client-request-id", customRequestId);
    headers.put("my-header1", "my-header1-value");
    headers.put("my-header2", "my-header2-value");
    final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() {

        @Override
        public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
            Assertions.assertEquals(httpRequest.getHeaders().getValue("x-ms-client-request-id"), customRequestId);
            Assertions.assertEquals(httpRequest.getHeaders().getValue("my-header1"), "my-header1-value");
            Assertions.assertEquals(httpRequest.getHeaders().getValue("my-header2"), "my-header2-value");
            httpCallback.onSuccess(mockResponse);
        }
    }).policies(new AddHeadersPolicy(headers)).policies(new RequestIdPolicy()).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) {
            try {
                throw new RuntimeException(error);
            } finally {
                latch.countDown();
            }
        }
    });
    awaitOnLatch(latch, "clientProvidedMultipleHeader");
}
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) CountDownLatch(java.util.concurrent.CountDownLatch) HttpPipeline(com.azure.android.core.http.HttpPipeline) Test(org.junit.jupiter.api.Test)

Example 22 with HttpHeaders

use of com.azure.android.core.http.HttpHeaders 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 23 with HttpHeaders

use of com.azure.android.core.http.HttpHeaders 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 24 with HttpHeaders

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

the class OkHttpAsyncHttpClient method send.

@Override
public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
    okhttp3.Request.Builder okhttpRequestBuilder = new okhttp3.Request.Builder();
    okhttpRequestBuilder.url(httpRequest.getUrl());
    if (httpRequest.getHeaders() != null) {
        Map<String, String> headers = new HashMap<>();
        for (HttpHeader hdr : httpRequest.getHeaders()) {
            if (hdr.getValue() != null) {
                headers.put(hdr.getName(), hdr.getValue());
            }
        }
        okhttpRequestBuilder.headers(okhttp3.Headers.of(headers));
    } else {
        okhttpRequestBuilder.headers(okhttp3.Headers.of(new HashMap<>()));
    }
    if (httpRequest.getHttpMethod() == HttpMethod.GET) {
        okhttpRequestBuilder.get();
    } else if (httpRequest.getHttpMethod() == HttpMethod.HEAD) {
        okhttpRequestBuilder.head();
    } else {
        byte[] content = httpRequest.getBody();
        content = content == null ? new byte[0] : content;
        final String contentType = httpRequest.getHeaders().getValue("Content-Type");
        if (contentType == null) {
            okhttpRequestBuilder.method(httpRequest.getHttpMethod().toString(), RequestBody.create(null, content));
        } else {
            okhttpRequestBuilder.method(httpRequest.getHttpMethod().toString(), RequestBody.create(MediaType.parse(contentType), content));
        }
    }
    final okhttp3.Request okHttpRequest = okhttpRequestBuilder.build();
    final okhttp3.Call call = httpClient.newCall(okHttpRequest);
    final String onCancelId = (cancellationToken == CancellationToken.NONE) ? null : UUID.randomUUID().toString();
    if (onCancelId != null) {
        // Register an identifiable Runnable to run on cancellationToken.cancel().
        // 
        // This Runnable unregistered once the 'call' completes.
        // 
        // We don't want a cancel on cancellationToken to call call.cancel()
        // after the call completion (though call.cancel() after it's completion is nop).
        // 
        cancellationToken.registerOnCancel(onCancelId, () -> call.cancel());
    }
    call.enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(okhttp3.Call call, IOException error) {
            if (onCancelId != null) {
                cancellationToken.unregisterOnCancel(onCancelId);
            }
            httpCallback.onError(error);
        }

        @Override
        public void onResponse(okhttp3.Call call, Response response) {
            if (onCancelId != null) {
                cancellationToken.unregisterOnCancel(onCancelId);
            }
            httpCallback.onSuccess(new HttpResponse(httpRequest) {

                private final HttpHeaders headers = fromOkHttpHeaders(response.headers());

                private final ResponseBody responseBody = response.body();

                @Override
                public int getStatusCode() {
                    return response.code();
                }

                @Override
                public String getHeaderValue(String name) {
                    return this.headers.getValue(name);
                }

                @Override
                public HttpHeaders getHeaders() {
                    return this.headers;
                }

                @Override
                public InputStream getBody() {
                    if (this.responseBody == null) {
                        return new ByteArrayInputStream(new byte[0]);
                    } else {
                        return this.responseBody.byteStream();
                    }
                }

                @Override
                public byte[] getBodyAsByteArray() {
                    if (this.responseBody == null) {
                        return new byte[0];
                    } else {
                        try {
                            return this.responseBody.bytes();
                        } catch (IOException e) {
                            throw logger.logExceptionAsError(new RuntimeException(e));
                        }
                    }
                }

                @Override
                public String getBodyAsString() {
                    return bomAwareToString(this.getBodyAsByteArray(), headers.getValue("Content-Type"));
                }

                @Override
                public void close() {
                    if (this.responseBody != null) {
                        this.responseBody.close();
                    }
                }

                @Override
                public String getBodyAsString(Charset charset) {
                    return new String(this.getBodyAsByteArray(), charset);
                }

                private HttpHeaders fromOkHttpHeaders(Headers headers) {
                    HttpHeaders httpHeaders = new HttpHeaders();
                    for (String headerName : headers.names()) {
                        httpHeaders.put(headerName, headers.get(headerName));
                    }
                    return httpHeaders;
                }
            });
        }
    });
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) HashMap(java.util.HashMap) HttpHeaders(com.azure.android.core.http.HttpHeaders) Headers(okhttp3.Headers) HttpRequest(com.azure.android.core.http.HttpRequest) HttpResponse(com.azure.android.core.http.HttpResponse) Charset(java.nio.charset.Charset) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) HttpResponse(com.azure.android.core.http.HttpResponse) Response(okhttp3.Response) HttpHeader(com.azure.android.core.http.HttpHeader) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 25 with HttpHeaders

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

the class HttpRequestMapper method map.

HttpRequest map(Object[] swaggerMethodArgs) throws IOException {
    final String path = this.applyPathMappings(swaggerMethodArgs);
    UrlBuilder urlBuilder = UrlBuilder.parse(path);
    // (a simple scheme presence check to determine full URL) and ignore the Host annotation.
    if (urlBuilder.getScheme() == null) {
        urlBuilder = this.applySchemeAndHostMapping(swaggerMethodArgs, new UrlBuilder());
        // Set the path after host, concatenating the path segment in the host.
        if (path != null && !path.isEmpty() && !"/".equals(path)) {
            String hostPath = urlBuilder.getPath();
            if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains("://")) {
                urlBuilder.setPath(path);
            } else {
                urlBuilder.setPath(hostPath + "/" + path);
            }
        }
    }
    this.applyQueryMappings(swaggerMethodArgs, urlBuilder);
    final HttpRequest request = new HttpRequest(this.httpMethod, urlBuilder.toString());
    if (!this.formDataEntriesMapping.isEmpty()) {
        final String formData = this.applyFormDataMapping(swaggerMethodArgs);
        if (formData == null) {
            request.getHeaders().put("Content-Length", "0");
        } else {
            request.getHeaders().put("Content-Type", "application/x-www-form-urlencoded");
            request.setBody(formData);
        }
    } else {
        final Object content = this.retrieveContentArg(swaggerMethodArgs);
        if (content == null) {
            request.getHeaders().put("Content-Length", "0");
        } else {
            String contentType = this.contentType;
            if (contentType == null || contentType.isEmpty()) {
                if (content instanceof byte[] || content instanceof String) {
                    contentType = "application/octet-stream";
                } else {
                    contentType = "application/json";
                }
            }
            request.getHeaders().put("Content-Type", contentType);
            boolean isJson = false;
            final String[] contentTypeParts = contentType.split(";");
            for (final String contentTypePart : contentTypeParts) {
                if (contentTypePart.trim().equalsIgnoreCase("application/json")) {
                    isJson = true;
                    break;
                }
            }
            if (isJson) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                this.jacksonSerder.serialize(content, SerdeEncoding.JSON, stream);
                request.setHeader("Content-Length", String.valueOf(stream.size()));
                request.setBody(stream.toByteArray());
            } else if (content instanceof byte[]) {
                request.setBody((byte[]) content);
            } else if (content instanceof String) {
                final String contentString = (String) content;
                request.setBody(contentString);
            } else {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                this.jacksonSerder.serialize(content, SerdeEncoding.fromHeaders(request.getHeaders().toMap()), stream);
                request.setHeader("Content-Length", String.valueOf(stream.size()));
                request.setBody(stream.toByteArray());
            }
        }
    }
    // Headers from Swagger method arguments always take precedence over inferred headers from body types.
    HttpHeaders httpHeaders = request.getHeaders();
    this.applyHeaderMappings(swaggerMethodArgs, httpHeaders);
    return request;
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HttpHeaders(com.azure.android.core.http.HttpHeaders) UrlBuilder(com.azure.android.core.http.util.UrlBuilder) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

HttpHeaders (com.azure.android.core.http.HttpHeaders)37 Test (org.junit.jupiter.api.Test)23 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)23 HttpResponse (com.azure.android.core.http.HttpResponse)20 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)17 HttpMethod (com.azure.android.core.http.HttpMethod)16 Method (java.lang.reflect.Method)16 PagedResponse (com.azure.android.core.rest.util.paging.PagedResponse)13 CountDownLatch (java.util.concurrent.CountDownLatch)9 HashMap (java.util.HashMap)7 HttpRequest (com.azure.android.core.http.HttpRequest)6 HttpBinJSON (com.azure.android.core.test.implementation.entities.HttpBinJSON)6 Map (java.util.Map)6 OffsetDateTime (org.threeten.bp.OffsetDateTime)6 Response (com.azure.android.core.rest.Response)5 StreamResponse (com.azure.android.core.rest.StreamResponse)5 List (java.util.List)5 HttpCallback (com.azure.android.core.http.HttpCallback)4 HttpHeader (com.azure.android.core.http.HttpHeader)4 HttpPipeline (com.azure.android.core.http.HttpPipeline)4