Search in sources :

Example 31 with HttpRequest

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

the class RequestIdPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    String requestId = httpRequest.getHeaders().getValue(requestIdHeaderName);
    if (requestId == null) {
        httpRequest.getHeaders().put(requestIdHeaderName, UUID.randomUUID().toString());
    }
    chain.processNextPolicy(httpRequest);
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest)

Example 32 with HttpRequest

use of com.azure.android.core.http.HttpRequest 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)

Example 33 with HttpRequest

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

the class UserAgentPolicy method process.

/**
 * Updates the "User-Agent" header with the value supplied at the time of creating policy.
 */
@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    final String existingUserAgent = httpRequest.getHeaders().getValue("User-Agent");
    httpRequest.getHeaders().put("User-Agent", existingUserAgent != null && existingUserAgent.length() != 0 ? existingUserAgent + " " + this.userAgent : this.userAgent);
    chain.processNextPolicy(httpRequest);
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest)

Example 34 with HttpRequest

use of com.azure.android.core.http.HttpRequest 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)

Example 35 with HttpRequest

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

the class ChatThreadClientBuilder method createInternalClient.

private AzureCommunicationChatServiceImpl createInternalClient() {
    if (endpoint == null) {
        throw logger.logExceptionAsError(new NullPointerException("'endpoint' is required."));
    }
    HttpPipeline pipeline;
    if (this.httpPipeline != null) {
        pipeline = this.httpPipeline;
    } else {
        if (this.communicationTokenCredential == null) {
            throw logger.logExceptionAsError(new NullPointerException("CommunicationTokenCredential is required."));
        }
        HttpPipelinePolicy authorizationPolicy = chain -> {
            final CompletableFuture<CommunicationAccessToken> tokenFuture = this.communicationTokenCredential.getToken();
            final CommunicationAccessToken token;
            try {
                token = tokenFuture.get();
            } catch (ExecutionException e) {
                chain.completedError(e);
                return;
            } catch (InterruptedException e) {
                chain.completedError(e);
                return;
            }
            HttpRequest httpRequest = chain.getRequest();
            httpRequest.getHeaders().put("Authorization", "Bearer " + token.getToken());
            chain.processNextPolicy(httpRequest);
        };
        pipeline = createHttpPipeline(this.httpClient, authorizationPolicy, this.customPolicies);
    }
    AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder().apiVersion((this.serviceVersion == null) ? ChatServiceVersion.getLatest().getVersion() : this.serviceVersion.getVersion()).endpoint(this.endpoint).pipeline(pipeline);
    return clientBuilder.buildClient();
}
Also used : AzureCommunicationChatServiceImplBuilder(com.azure.android.communication.chat.implementation.AzureCommunicationChatServiceImplBuilder) AzureCommunicationChatServiceImpl(com.azure.android.communication.chat.implementation.AzureCommunicationChatServiceImpl) VERSION_NAME(com.azure.android.communication.chat.BuildConfig.VERSION_NAME) RetryPolicy(com.azure.android.core.http.policy.RetryPolicy) ServiceClientBuilder(com.azure.android.core.rest.annotation.ServiceClientBuilder) UserAgentPolicy(com.azure.android.core.http.policy.UserAgentPolicy) CompletableFuture(java9.util.concurrent.CompletableFuture) ClientLogger(com.azure.android.core.logging.ClientLogger) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) LIBRARY_PACKAGE_NAME(com.azure.android.communication.chat.BuildConfig.LIBRARY_PACKAGE_NAME) HttpPipelineBuilder(com.azure.android.core.http.HttpPipelineBuilder) HttpLoggingPolicy(com.azure.android.core.http.policy.HttpLoggingPolicy) List(java.util.List) HttpLogOptions(com.azure.android.core.http.policy.HttpLogOptions) HttpPipelinePolicy(com.azure.android.core.http.HttpPipelinePolicy) HttpPipeline(com.azure.android.core.http.HttpPipeline) CookiePolicy(com.azure.android.core.http.policy.CookiePolicy) CommunicationTokenCredential(com.azure.android.communication.common.CommunicationTokenCredential) HttpClient(com.azure.android.core.http.HttpClient) HttpRequest(com.azure.android.core.http.HttpRequest) CommunicationAccessToken(com.azure.android.communication.common.CommunicationAccessToken) CommunicationAccessToken(com.azure.android.communication.common.CommunicationAccessToken) HttpRequest(com.azure.android.core.http.HttpRequest) HttpPipelinePolicy(com.azure.android.core.http.HttpPipelinePolicy) CompletableFuture(java9.util.concurrent.CompletableFuture) AzureCommunicationChatServiceImplBuilder(com.azure.android.communication.chat.implementation.AzureCommunicationChatServiceImplBuilder) HttpPipeline(com.azure.android.core.http.HttpPipeline) ExecutionException(java.util.concurrent.ExecutionException)

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