package com.mridul.software.automation.rest.interceptors;
import com.aventstack.extentreports.ExtentTest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;
@Slf4j
public class ExtentLoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static final ThreadLocal<ExtentTest> TEST_THREAD_LOCAL = new ThreadLocal<>();
public void setExtentTest(ExtentTest test) {
TEST_THREAD_LOCAL.set(test);
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
logRequestDetails(request);
ClientHttpResponse response = execution.execute(request, body);
logResponseDetails(response);
return response;
}
private void logAndTest(String header, Object value) {
ExtentTest test = TEST_THREAD_LOCAL.get();
log.debug("{}: {}", header, value.toString());
test.info(header + " : <pre>" + value.toString() + "</pre>");
}
private void logRequestDetails(HttpRequest request) {
logAndTest("Headers", request.getHeaders());
logAndTest("Request Method",
(Objects.isNull(request.getMethod())) ? "No Request Method" : request.getMethod());
logAndTest("Request URI", request.getURI());
}
private void logResponseDetails(ClientHttpResponse response) {
try {
String responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
String formattedResponseBody = toPrettyFormat(responseBody);
logAndTest("Status Code", response.getStatusCode());
logAndTest("Status Text", response.getStatusText());
logAndTest("Response Body", formattedResponseBody);
} catch (final Exception e) {
log.debug("Exception in Response : {}", e);
}
}
private String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
log.debug("String formatted to Json String : {}{}", System.lineSeparator(), prettyJson);
return prettyJson;
}
}
Comments
Post a Comment