use of com.azure.android.core.http.HttpResponse 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);
}
});
}
use of com.azure.android.core.http.HttpResponse 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;
}
});
}
});
}
use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.
the class CookiePolicy method process.
@Override
public void process(HttpPipelinePolicyChain chain) {
HttpRequest httpRequest = chain.getRequest();
final URI uri;
try {
uri = httpRequest.getUrl().toURI();
} catch (URISyntaxException error) {
chain.completedError(error);
return;
}
Map<String, List<String>> cookieHeaders = new HashMap<>();
for (HttpHeader header : httpRequest.getHeaders()) {
cookieHeaders.put(header.getName(), Arrays.asList(chain.getRequest().getHeaders().getValues(header.getName())));
}
final Map<String, List<String>> requestCookies;
try {
requestCookies = cookies.get(uri, cookieHeaders);
} catch (IOException error) {
chain.completedError(error);
return;
}
for (Map.Entry<String, List<String>> entry : requestCookies.entrySet()) {
httpRequest.getHeaders().put(entry.getKey(), TextUtils.join(",", entry.getValue()));
}
chain.processNextPolicy(httpRequest, new NextPolicyCallback() {
@Override
public PolicyCompleter.CompletionState onSuccess(HttpResponse response, PolicyCompleter completer) {
Map<String, List<String>> responseHeaders = new HashMap<>();
for (HttpHeader header : response.getHeaders()) {
responseHeaders.put(header.getName(), Collections.singletonList(header.getValue()));
}
try {
cookies.put(uri, responseHeaders);
} catch (IOException error) {
return completer.completedError(error);
}
return completer.completed(response);
}
@Override
public PolicyCompleter.CompletionState onError(Throwable error, PolicyCompleter completer) {
return completer.completedError(error);
}
});
}
use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.
the class ProtocolPolicyTests method withOverwrite.
@Test
public void withOverwrite() {
final HttpPipeline pipeline = createPipeline("ftp", "ftp://www.bing.com");
CountDownLatch latch = new CountDownLatch(1);
pipeline.send(createHttpRequest("http://www.bing.com"), 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, "withOverwrite");
}
use of com.azure.android.core.http.HttpResponse in project azure-sdk-for-android by Azure.
the class RequestIdPolicyTests method sameRequestIdForRetry.
@Test
public void sameRequestIdForRetry() {
final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() {
String firstRequestId = null;
@Override
public void send(HttpRequest request, CancellationToken cancellationToken, HttpCallback httpCallback) {
if (firstRequestId != null) {
String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER);
Assertions.assertNotNull(newRequestId, "newRequestId should not be null");
Assertions.assertEquals(newRequestId, firstRequestId);
}
firstRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER);
if (firstRequestId == null) {
Assertions.fail("The firstRequestId should not be null.");
}
httpCallback.onSuccess(mockResponse);
// TODO: anuchan add a test with misbehaving httpclient that signal twice and assert we throw meaningful error
// TODO: anuchan add a test that watch running calls when we schedule (i.e. ensure not holding the thread)
//
// if (firstRequestId != null) {
// String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER);
// Assertions.assertNotNull(newRequestId);
// Assertions.assertEquals(newRequestId, firstRequestId);
// }
// firstRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER);
// if (firstRequestId == null) {
// Assertions.fail();
// }
// httpCallback.onSuccess(mockResponse);
}
}).policies(new RequestIdPolicy(), new RetryPolicy(new FixedDelay(1, Duration.of(5, ChronoUnit.SECONDS)))).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, "sameRequestIdForRetry");
}
Aggregations