diff --git a/pom.xml b/pom.xml index 818d131359..9bfadc01a5 100644 --- a/pom.xml +++ b/pom.xml @@ -208,6 +208,7 @@ spring-zuul spring-reactor spring-vertx + spring-rest-logging testing testng diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..3c9eebf34e --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.rest.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java index 61d279a0c5..ed3cdda7ad 100644 --- a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java +++ b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java @@ -15,14 +15,14 @@ public class TestTaxiFareController { private static final String URL = "http://localhost:" + 9090 + "/rest-log/taxifare/"; @Test - public void given_taxi_fare_get() { + public void givenRequest_thenfetchTaxiFareRateCard() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test - public void given_taxi_ride_get_fare() { + public void givenTaxiRide_thenGetCalculatedFare() { TestRestTemplate testRestTemplate = new TestRestTemplate(); TaxiRide taxiRide = new TaxiRide(true,10l); String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class);