Search in sources :

Example 6 with HttpHeader

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

the class HttpRequestMapper method applyHeaderMappings.

HttpHeaders applyHeaderMappings(Object[] swaggerMethodArgs, HttpHeaders httpHeaders) {
    for (HttpHeader header : this.headers) {
        httpHeaders.put(header.getName(), header.getValue());
    }
    if (swaggerMethodArgs != null) {
        for (MethodParameterMapping headerParameterMapping : this.headerMappings) {
            if (headerParameterMapping.argIndex < swaggerMethodArgs.length) {
                final Object methodArg = swaggerMethodArgs[headerParameterMapping.argIndex];
                if (methodArg instanceof Map) {
                    @SuppressWarnings("unchecked") final Map<String, ?> headerCollection = (Map<String, ?>) methodArg;
                    final String headerCollectionPrefix = headerParameterMapping.mapToName;
                    for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) {
                        final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey();
                        final String headerValue = this.serialize(headerCollectionEntry.getValue());
                        if (headerValue != null) {
                            httpHeaders.put(headerName, headerValue);
                        }
                    }
                } else {
                    final String headerValue = this.serialize(methodArg);
                    if (headerValue != null) {
                        httpHeaders.put(headerParameterMapping.mapToName, headerValue);
                    }
                }
            }
        }
    }
    return httpHeaders;
}
Also used : HttpHeader(com.azure.android.core.http.HttpHeader) Map(java.util.Map)

Example 7 with HttpHeader

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

the class HttpRequestMapperTests method headers.

@ParameterizedTest
@MethodSource("headersSupplier")
public void headers(Method method, HttpHeaders expectedHeaders) {
    HttpRequestMapper mapper = new HttpRequestMapper("https://raw.host.com", method, new JacksonSerder());
    HttpHeaders actual = new HttpHeaders();
    mapper.applyHeaderMappings(null, actual);
    for (HttpHeader header : actual) {
        assertEquals(expectedHeaders.getValue(header.getName()), header.getValue());
    }
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) JacksonSerder(com.azure.android.core.serde.jackson.JacksonSerder) HttpHeader(com.azure.android.core.http.HttpHeader) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 8 with HttpHeader

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

the class RecordNetworkCallPolicy method extractResponseData.

private Map<String, String> extractResponseData(final HttpResponse response) {
    final Map<String, String> responseData = new HashMap<>();
    responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));
    boolean addedRetryAfter = false;
    for (HttpHeader header : response.getHeaders()) {
        String headerValueToStore = header.getValue();
        if (header.getName().equalsIgnoreCase("retry-after")) {
            headerValueToStore = "0";
            addedRetryAfter = true;
        } else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
            // The encryption key is sensitive information so capture it with a hidden value.
            headerValueToStore = "REDACTED";
        }
        responseData.put(header.getName(), headerValueToStore);
    }
    if (!addedRetryAfter) {
        responseData.put("retry-after", "0");
    }
    String contentType = response.getHeaderValue(CONTENT_TYPE);
    if (contentType == null) {
        final byte[] bytes = response.getBodyAsByteArray();
        if (bytes != null && bytes.length != 0) {
            String content = new String(bytes, StandardCharsets.UTF_8);
            responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
            responseData.put(BODY, content);
        }
        return responseData;
    } else if (contentType.equalsIgnoreCase("application/octet-stream") || contentType.equalsIgnoreCase("avro/binary")) {
        final byte[] bytes = response.getBodyAsByteArray();
        if (bytes != null && bytes.length != 0) {
            responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
        }
        return responseData;
    } else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
        String content = response.getBodyAsString(StandardCharsets.UTF_8);
        if (content == null || content.length() == 0) {
            content = "";
        }
        responseData.put(BODY, new RecordingRedactor().redact(content));
        return responseData;
    } else {
        final byte[] bytes = response.getBodyAsByteArray();
        if (bytes == null || bytes.length == 0) {
            return responseData;
        }
        String content;
        if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
            try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
                ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
                int position = 0;
                int bytesRead = gis.read(buffer, position, buffer.length);
                while (bytesRead != -1) {
                    output.write(buffer, 0, bytesRead);
                    position += bytesRead;
                    bytesRead = gis.read(buffer, position, buffer.length);
                }
                content = output.toString("UTF-8");
            } catch (IOException e) {
                throw logger.logExceptionAsWarning(new RuntimeException(e));
            }
        } else {
            content = new String(bytes, StandardCharsets.UTF_8);
        }
        responseData.remove(CONTENT_ENCODING);
        responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
        responseData.put(BODY, content);
        return responseData;
    }
}
Also used : HashMap(java.util.HashMap) RecordingRedactor(com.azure.android.core.test.models.RecordingRedactor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeader(com.azure.android.core.http.HttpHeader) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 9 with HttpHeader

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

the class HttpUrlConnectionAsyncHttpClient method sendIntern.

private void sendIntern(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
    if (cancellationToken.isCancellationRequested()) {
        httpCallback.onError(new IOException("Canceled."));
        return;
    }
    final HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) httpRequest.getUrl().openConnection();
    } catch (IOException ioe) {
        httpCallback.onError(ioe);
        return;
    }
    connection.setDoInput(true);
    Throwable error = null;
    HttpResponse httpResponse = null;
    boolean hasResponseContent = false;
    try {
        // Request: headers
        for (HttpHeader header : httpRequest.getHeaders()) {
            connection.addRequestProperty(header.getName(), header.getValue());
        }
        // Request: method and content.
        switch(httpRequest.getHttpMethod()) {
            case GET:
            case HEAD:
            case OPTIONS:
            case TRACE:
                connection.setRequestMethod(httpRequest.getHttpMethod().toString());
                break;
            case PUT:
            case POST:
            case PATCH:
            case DELETE:
                connection.setRequestMethod(httpRequest.getHttpMethod().toString());
                final byte[] requestContent = httpRequest.getBody();
                if (requestContent != null) {
                    connection.setDoOutput(true);
                    final OutputStream requestContentStream = connection.getOutputStream();
                    try {
                        requestContentStream.write(requestContent);
                    } finally {
                        requestContentStream.close();
                    }
                }
                break;
            default:
                throw logger.logExceptionAsError(new IllegalStateException("Unknown HTTP Method:" + httpRequest.getHttpMethod()));
        }
        // Response: StatusCode
        final int statusCode = connection.getResponseCode();
        if (statusCode == -1) {
            final IOException ioException = new IOException("Retrieval of HTTP response code failed. " + "HttpUrlConnection::getResponseCode() returned -1");
            throw logger.logExceptionAsError(new RuntimeException(ioException));
        }
        // Response: headers
        final Map<String, List<String>> connHeaderMap = connection.getHeaderFields();
        final HttpHeaders headers = new HttpHeaders();
        for (Map.Entry<String, List<String>> entry : connHeaderMap.entrySet()) {
            if (entry.getKey() == null) {
                continue;
            }
            final String headerName = entry.getKey();
            final String headerValue;
            Iterator<String> hdrValueItr = entry.getValue().iterator();
            if (hdrValueItr.hasNext()) {
                headerValue = hdrValueItr.next();
            } else {
                headerValue = null;
            }
            headers.put(headerName, headerValue);
        }
        // Response: Content
        hasResponseContent = statusCode != HttpURLConnection.HTTP_NO_CONTENT && statusCode != HttpURLConnection.HTTP_NOT_MODIFIED && statusCode >= HttpURLConnection.HTTP_OK && httpRequest.getHttpMethod() != HttpMethod.HEAD;
        final InputStream responseContentStream = hasResponseContent ? new ResponseContentStream(connection) : new ByteArrayInputStream(new byte[0]);
        httpResponse = new UrlConnectionResponse(logger, httpRequest, statusCode, headers, responseContentStream);
    } catch (Throwable e) {
        error = e;
    } finally {
        if (error != null || !hasResponseContent) {
            connection.disconnect();
        }
    }
    if (error != null) {
        httpCallback.onError(error);
        return;
    } else {
        httpCallback.onSuccess(httpResponse);
    }
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) HttpResponse(com.azure.android.core.http.HttpResponse) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) HttpHeader(com.azure.android.core.http.HttpHeader) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Map(java.util.Map)

Aggregations

HttpHeader (com.azure.android.core.http.HttpHeader)9 HttpHeaders (com.azure.android.core.http.HttpHeaders)4 IOException (java.io.IOException)4 HttpRequest (com.azure.android.core.http.HttpRequest)3 HttpResponse (com.azure.android.core.http.HttpResponse)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 List (java.util.List)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 MethodSource (org.junit.jupiter.params.provider.MethodSource)2 NextPolicyCallback (com.azure.android.core.http.NextPolicyCallback)1 PolicyCompleter (com.azure.android.core.http.PolicyCompleter)1 RecordingRedactor (com.azure.android.core.test.models.RecordingRedactor)1 FilterInputStream (java.io.FilterInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1