From 390e0476092c59676406512f8ce8cdda5dfdd328 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Tue, 10 Sep 2019 18:14:41 +0000 Subject: updating logging filters maximize re-use in logging filter classes Issue-ID: LOG-1125 Signed-off-by: Smokowski, Kevin (ks6305) Change-Id: I063d57635fe56a60d97945873d0c7b64852182a5 --- .../filter/base/AbstractAuditLogFilter.java | 33 ++- .../onap/logging/filter/base/AbstractFilter.java | 222 +++++++++++++++ .../filter/base/AbstractMetricLogFilter.java | 128 +++++++++ .../filter/base/AuditLogContainerFilter.java | 6 +- .../logging/filter/base/AuditLogServletFilter.java | 13 +- .../org/onap/logging/filter/base/MDCSetup.java | 212 -------------- .../logging/filter/base/MetricLogClientFilter.java | 104 ++----- .../filter/base/PayloadLoggingClientFilter.java | 17 +- .../filter/base/PayloadLoggingServletFilter.java | 49 ++-- .../org/onap/logging/filter/base/PropertyUtil.java | 43 --- .../logging/filter/base/AbstractFilterTest.java | 301 ++++++++++++++++++++ .../filter/base/AuditLogContainerFilterTest.java | 20 +- .../filter/base/AuditLogServletFilterTest.java | 14 +- .../filter/base/LoggingContainerFilterTest.java | 2 - .../org/onap/logging/filter/base/MDCSetupTest.java | 306 --------------------- .../filter/base/MetricLogClientFilterTest.java | 25 +- .../base/PayloadLoggingClientFilterTest.java | 2 - .../onap/logging/filter/base/PropertyUtilTest.java | 50 ---- .../filter/base/SimpleJaxrsHeadersMapTest.java | 2 - .../filter/base/SimpleServletHeadersMapTest.java | 1 - .../logging/filter/spring/LoggingInterceptor.java | 62 ++--- .../logging/filter/spring/SpringClientFilter.java | 117 +++----- .../filter/spring/SpringClientPayloadFilter.java | 69 +++++ .../filter/spring/StatusLoggingInterceptor.java | 74 +++++ .../filter/spring/LoggingInterceptorTest.java | 11 +- .../filter/spring/SpringClientFilterTest.java | 43 ++- 26 files changed, 977 insertions(+), 949 deletions(-) create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java delete mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java delete mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java create mode 100644 reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java delete mode 100644 reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java delete mode 100644 reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java create mode 100644 reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java create mode 100644 reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java index 71d4e31..fd4e95a 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java @@ -26,39 +26,38 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -public abstract class AbstractAuditLogFilter { +public abstract class AbstractAuditLogFilter extends AbstractFilter { protected static final Logger logger = LoggerFactory.getLogger(AbstractAuditLogFilter.class); - protected void pre(MDCSetup mdcSetup, SimpleMap headers, GenericRequest request, - HttpServletRequest httpServletRequest) { + protected void pre(SimpleMap headers, GenericRequest request, HttpServletRequest httpServletRequest) { try { - String requestId = mdcSetup.getRequestId(headers); + String requestId = getRequestId(headers); MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - mdcSetup.setInvocationId(headers); + setInvocationId(headers); setServiceName(request); - mdcSetup.setMDCPartnerName(headers); - mdcSetup.setServerFQDN(); - mdcSetup.setClientIPAddress(httpServletRequest); - mdcSetup.setInstanceID(); - mdcSetup.setEntryTimeStamp(); + setMDCPartnerName(headers); + setServerFQDN(); + setClientIPAddress(httpServletRequest); + setInstanceID(); + setEntryTimeStamp(); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); additionalPreHandling(request); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); + setLogTimestamp(); + setElapsedTime(); logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); } catch (Exception e) { logger.warn("Error in AbstractInboundFilter pre", e); } } - protected void post(MDCSetup mdcSetup, GenericResponse response) { + protected void post(GenericResponse response) { try { int responseCode = getResponseCode(response); - mdcSetup.setResponseStatusCode(responseCode); + setResponseStatusCode(responseCode); MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseCode)); - mdcSetup.setResponseDescription(responseCode); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); + setResponseDescription(responseCode); + setLogTimestamp(); + setElapsedTime(); logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); additionalPostHandling(response); } catch (Exception e) { diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java new file mode 100644 index 0000000..13c88b0 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractFilter.java @@ -0,0 +1,222 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +public abstract class AbstractFilter { + + protected static Logger logger = LoggerFactory.getLogger(AbstractFilter.class); + + private static final String INSTANCE_UUID = UUID.randomUUID().toString(); + + protected void setInstanceID() { + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID); + } + + protected void setServerFQDN() { + String serverFQDN = ""; + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.getCanonicalHostName(); + MDC.put(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS, addr.getHostAddress()); + } catch (UnknownHostException e) { + logger.warn("Cannot Resolve Host Name"); + serverFQDN = ""; + } + MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN); + } + + protected void setClientIPAddress(HttpServletRequest httpServletRequest) { + String clientIpAddress = ""; + if (httpServletRequest != null) { + // This logic is to avoid setting the client ip address to that of the load + // balancer in front of the application + String getForwadedFor = httpServletRequest.getHeader("X-Forwarded-For"); + if (getForwadedFor != null) { + clientIpAddress = getForwadedFor; + } else { + clientIpAddress = httpServletRequest.getRemoteAddr(); + } + } + MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, clientIpAddress); + } + + protected void setEntryTimeStamp() { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + } + + protected String getRequestId(SimpleMap headers) { + logger.trace("Checking X-ONAP-RequestID header for requestId."); + String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID); + if (requestId != null && !requestId.isEmpty()) { + return requestId; + } + + logger.trace("No valid X-ONAP-RequestID header value. Checking X-RequestID header for requestId."); + requestId = headers.get(Constants.HttpHeaders.HEADER_REQUEST_ID); + if (requestId != null && !requestId.isEmpty()) { + return requestId; + } + + logger.trace("No valid X-RequestID header value. Checking X-TransactionID header for requestId."); + requestId = headers.get(Constants.HttpHeaders.TRANSACTION_ID); + if (requestId != null && !requestId.isEmpty()) { + return requestId; + } + + logger.trace("No valid X-TransactionID header value. Checking X-ECOMP-RequestID header for requestId."); + requestId = headers.get(Constants.HttpHeaders.ECOMP_REQUEST_ID); + if (requestId != null && !requestId.isEmpty()) { + return requestId; + } + + logger.trace("No valid requestId headers. Generating requestId: {}", requestId); + return UUID.randomUUID().toString(); + } + + protected void setInvocationId(SimpleMap headers) { + String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID); + if (invocationId == null || invocationId.isEmpty()) + invocationId = UUID.randomUUID().toString(); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + } + + protected void setInvocationIdFromMDC() { + String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID); + if (invocationId == null || invocationId.isEmpty()) + invocationId = UUID.randomUUID().toString(); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + } + + protected void setMDCPartnerName(SimpleMap headers) { + logger.trace("Checking X-ONAP-PartnerName header for partnerName."); + String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME); + if (partnerName == null || partnerName.isEmpty()) { + logger.trace("No valid X-ONAP-PartnerName header value. Checking User-Agent header for partnerName."); + partnerName = headers.get(HttpHeaders.USER_AGENT); + if (partnerName == null || partnerName.isEmpty()) { + logger.trace("No valid User-Agent header value. Checking X-ClientID header for partnerName."); + partnerName = headers.get(Constants.HttpHeaders.CLIENT_ID); + if (partnerName == null || partnerName.isEmpty()) { + logger.trace("No valid partnerName headers. Defaulting partnerName to UNKNOWN."); + partnerName = Constants.DefaultValues.UNKNOWN; + } + } + } + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); + } + + protected void setLogTimestamp() { + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + } + + protected void setElapsedTime() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + ZonedDateTime entryTimestamp = + ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter); + ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter); + + MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, + Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp))); + } + + protected void setElapsedTimeInvokeTimestamp() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + ZonedDateTime entryTimestamp = + ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter); + ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter); + + MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, + Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp))); + } + + protected void setResponseStatusCode(int code) { + String statusCode; + if (Response.Status.Family.familyOf(code).equals(Response.Status.Family.SUCCESSFUL)) { + statusCode = ONAPLogConstants.ResponseStatus.COMPLETE.toString(); + } else { + statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString(); + setErrorCode(code); + setErrorDesc(code); + } + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode); + } + + protected void setTargetEntity(ONAPComponents targetEntity) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString()); + } + + protected void clearClientMDCs() { + MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID); + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION); + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE); + MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); + MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); + MDC.remove(ONAPLogConstants.MDCs.ERROR_CODE); + MDC.remove(ONAPLogConstants.MDCs.ERROR_DESC); + } + + protected void setResponseDescription(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString()); + } + + protected void setErrorCode(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode)); + } + + protected void setErrorDesc(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString()); + } + + protected String getProperty(String property) { + logger.info("Checking for system property [{}]", property); + String propertyValue = System.getProperty(property); + if (propertyValue == null || propertyValue.isEmpty()) { + logger.info("System property was null or empty. Checking environment variable for: {}", property); + propertyValue = System.getenv(property); + if (propertyValue == null || propertyValue.isEmpty()) { + logger.info("Environment variable: {} was null or empty. Returning value: {}", property, + Constants.DefaultValues.UNKNOWN); + propertyValue = Constants.DefaultValues.UNKNOWN; + } + } + return propertyValue; + } +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java new file mode 100644 index 0000000..7857af9 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractMetricLogFilter.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.UUID; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +public abstract class AbstractMetricLogFilter extends AbstractFilter { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); + private final String partnerName; + private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); + + public AbstractMetricLogFilter() { + partnerName = getPartnerName(); + } + + protected abstract void addHeader(RequestHeaders requestHeaders, String headerName, String headerValue); + + protected abstract String getTargetServiceName(Request request); + + protected abstract String getServiceName(Request request); + + protected abstract int getHttpStatusCode(Response response); + + protected abstract String getResponseCode(Response response); + + protected abstract String getTargetEntity(Request request); + + protected void pre(Request request, RequestHeaders requestHeaders) { + try { + setupMDC(request); + setupHeaders(request, requestHeaders); + logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); + } catch (Exception e) { + logger.warn("Error in AbstractMetricLogFilter pre", e); + } + } + + protected void setupHeaders(Request clientRequest, RequestHeaders requestHeaders) { + String requestId = extractRequestID(); + addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.TRANSACTION_ID, requestId); + addHeader(requestHeaders, Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); + addHeader(requestHeaders, ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + addHeader(requestHeaders, ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + } + + protected void setupMDC(Request request) { + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(request)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + setInvocationIdFromMDC(); + + if (MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY) == null) { + String targetEntity = getTargetEntity(request); + if (targetEntity != null) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity); + } else { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY); + } + } + + if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(request)); + } + setServerFQDN(); + } + + protected String extractRequestID() { + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + if (requestId == null || requestId.isEmpty()) { + requestId = UUID.randomUUID().toString(); + setLogTimestamp(); + setElapsedTimeInvokeTimestamp(); + logger.warn("No value found in MDC when checking key {} value will be set to {}", + ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + } + return requestId; + } + + protected void post(Request request, Response response) { + try { + setLogTimestamp(); + setElapsedTimeInvokeTimestamp(); + setResponseStatusCode(getHttpStatusCode(response)); + setResponseDescription(getHttpStatusCode(response)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, getResponseCode(response)); + logger.info(INVOKE_RETURN, "InvokeReturn"); + clearClientMDCs(); + } catch (Exception e) { + logger.warn("Error in AbstractMetricLogFilter post", e); + } + } + + protected String getPartnerName() { + return getProperty(Constants.Property.PARTNER_NAME); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java index 3d04b62..4783e7b 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java @@ -48,18 +48,16 @@ public class AuditLogContainerFilter extends AbstractAuditLogFilter> + implements ClientRequestFilter, ClientResponseFilter { @Context private Providers providers; - private MDCSetup mdcSetup = new MDCSetup(); - private static final String TRACE = "trace-#"; - private static Logger logger = LoggerFactory.getLogger(MetricLogClientFilter.class); - private final String partnerName; - private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); - public MetricLogClientFilter() { - partnerName = getPartnerName(); + @Override + public void filter(ClientRequestContext clientRequest) { + pre(clientRequest, clientRequest.getHeaders()); } @Override - public void filter(ClientRequestContext clientRequest) { - try { - setupMDC(clientRequest); - setupHeaders(clientRequest); - logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); - } catch (Exception e) { - logger.warn("Error in JAX-RS client request filter", e); - } + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + post(requestContext, responseContext); } - protected void setupHeaders(ClientRequestContext clientRequest) { - MultivaluedMap headers = clientRequest.getHeaders(); - String requestId = extractRequestID(clientRequest); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.TRANSACTION_ID, requestId); - headers.add(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + @Override + protected void addHeader(MultivaluedMap requestHeaders, String headerName, String headerValue) { + requestHeaders.add(headerName, headerValue); } - protected void setupMDC(ClientRequestContext clientRequest) { - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getUri().toString()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - mdcSetup.setInvocationIdFromMDC(); - String targetEntity = MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY); - if (targetEntity != null) { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity); - } else { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY); - } - if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, clientRequest.getUri().getPath()); - } - mdcSetup.setServerFQDN(); + @Override + protected String getTargetServiceName(ClientRequestContext request) { + return request.getUri().toString(); } - protected String extractRequestID(ClientRequestContext clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getUri().getPath()); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - } - return requestId; + @Override + protected String getServiceName(ClientRequestContext request) { + return request.getUri().getPath(); } @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { - try { - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - mdcSetup.setResponseStatusCode(responseContext.getStatus()); - mdcSetup.setResponseDescription(responseContext.getStatus()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus())); - logger.info(INVOKE_RETURN, "InvokeReturn"); - mdcSetup.clearClientMDCs(); - } catch (Exception e) { - logger.warn("Error in JAX-RS request,response client filter", e); - } + protected int getHttpStatusCode(ClientResponseContext response) { + return response.getStatus(); + } + + @Override + protected String getResponseCode(ClientResponseContext response) { + return String.valueOf(response.getStatus()); } - protected String getPartnerName() { - PropertyUtil p = new PropertyUtil(); - return p.getProperty(Constants.Property.PARTNER_NAME); + @Override + protected String getTargetEntity(ClientRequestContext request) { + return Constants.DefaultValues.UNKNOWN_TARGET_ENTITY; } + } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java index 045a729..3777719 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java @@ -56,10 +56,6 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024); } - private void log(StringBuilder sb) { - logger.debug(sb.toString()); - } - protected InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) throws IOException { if (!stream.markSupported()) { @@ -87,9 +83,8 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); } String method = formatMethod(requestContext); - log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: " - + getHeaders(requestContext.getHeaders()))); - + logger.debug("Sending HTTP {} to:{} with request headers:{}", method, requestContext.getUri(), + getHeaders(requestContext.getHeaders())); } protected String getHeaders(MultivaluedMap headers) { @@ -107,10 +102,10 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe final StringBuilder sb = new StringBuilder(); if (responseContext.hasEntity()) { responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET)); - String method = formatMethod(requestContext); - log(sb.insert(0, "Response from " + method + ": " + requestContext.getUri() + "\nResponse Headers: " - + responseContext.getHeaders().toString())); } + String method = formatMethod(requestContext); + logger.debug("Response from method:{} performed on uri:{} has http status code:{} and response headers:{}", + method, requestContext.getUri(), responseContext.getStatus(), responseContext.getHeaders().toString()); } @Override @@ -118,7 +113,7 @@ public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientRe final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); context.proceed(); if (stream != null) { - log(stream.getStringBuilder(DEFAULT_CHARSET)); + logger.debug(stream.getStringBuilder(DEFAULT_CHARSET).toString()); } } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java index 3e85b9d..4b9cd1f 100644 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java @@ -205,18 +205,7 @@ public class PayloadLoggingServletFilter implements Filter { requestHeaders.append(":"); requestHeaders.append(httpRequest.getRequestURL().toString()); requestHeaders.append("|"); - String header; - for (Enumeration e = httpRequest.getHeaderNames(); e.hasMoreElements();) { - header = e.nextElement(); - requestHeaders.append(header); - requestHeaders.append(":"); - if (header.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { - requestHeaders.append(REDACTED); - } else { - requestHeaders.append(httpRequest.getHeader(header)); - } - requestHeaders.append(";"); - } + requestHeaders.append(getSecureRequestHeaders(httpRequest)); log.info(requestHeaders.toString()); log.info("REQUEST BODY|" + new String(bufferedRequest.getBuffer())); @@ -259,13 +248,7 @@ public class PayloadLoggingServletFilter implements Filter { try { byte[] bytes = baos.toByteArray(); StringBuilder responseHeaders = new StringBuilder("RESPONSE HEADERS|"); - - for (String headerName : response.getHeaderNames()) { - responseHeaders.append(headerName); - responseHeaders.append(":"); - responseHeaders.append(response.getHeader(headerName)); - responseHeaders.append(";"); - } + responseHeaders.append(formatResponseHeaders(response)); responseHeaders.append("Status:"); responseHeaders.append(response.getStatus()); responseHeaders.append(";IsCommited:" + wrappedResp.isCommitted()); @@ -346,4 +329,32 @@ public class PayloadLoggingServletFilter implements Filter { } return str.toString(); } + + protected String getSecureRequestHeaders(HttpServletRequest httpRequest) { + StringBuilder sb = new StringBuilder(); + String header; + for (Enumeration e = httpRequest.getHeaderNames(); e.hasMoreElements();) { + header = e.nextElement(); + sb.append(header); + sb.append(":"); + if (header.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { + sb.append(REDACTED); + } else { + sb.append(httpRequest.getHeader(header)); + } + sb.append(";"); + } + return sb.toString(); + } + + protected String formatResponseHeaders(HttpServletResponse response) { + StringBuilder sb = new StringBuilder(); + for (String headerName : response.getHeaderNames()) { + sb.append(headerName); + sb.append(":"); + sb.append(response.getHeader(headerName)); + sb.append(";"); + } + return sb.toString(); + } } diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java deleted file mode 100644 index 5a094eb..0000000 --- a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - Logging - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.logging.filter.base; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PropertyUtil { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public String getProperty(String property) { - logger.info("Checking for system property [{}]", property); - String propertyValue = System.getProperty(property); - if (propertyValue == null || propertyValue.isEmpty()) { - logger.info("System property was null or empty. Checking environment variable for: {}", property); - propertyValue = System.getenv(property); - if (propertyValue == null || propertyValue.isEmpty()) { - logger.info("Environment variable: {} was null or empty. Returning value: {}", property, - Constants.DefaultValues.UNKNOWN); - propertyValue = Constants.DefaultValues.UNKNOWN; - } - } - return propertyValue; - } -} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java new file mode 100644 index 0000000..cfa74ad --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AbstractFilterTest.java @@ -0,0 +1,301 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class AbstractFilterTest extends AbstractFilter { + + @Mock + private HttpServletRequest httpServletRequest; + + private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a"; + + @After + public void tearDown() { + MDC.clear(); + System.clearProperty("partnerName"); + } + + @Test + public void setElapsedTimeTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTime(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setElapsedTimeInvokeTimestampTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTimeInvokeTimestamp(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setRequestIdTest() { + HashMap headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdRequestIdHeaderTest() { + HashMap headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdTransactionIdHeaderTest() { + HashMap headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.TRANSACTION_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdEcompRequestIdHeaderTest() { + HashMap headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdNoHeaderTest() { + HashMap headers = new HashMap<>(); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertNotNull(fetchedRequestId); + } + + @Test + public void setInvocationIdTest() { + HashMap headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + setInvocationId(new SimpleHashMap(headers)); + assertEquals(invocationId, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setInvocationIdNoHeaderTest() { + HashMap headers = new HashMap<>(); + setInvocationId(new SimpleHashMap(headers)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setInvovationIdFromMDCTest() { + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "7b77143c-9b50-410c-ac2f-05758a68e3e8"); + setInvocationIdFromMDC(); + assertEquals("7b77143c-9b50-410c-ac2f-05758a68e3e8", MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setInvocationIdFromMDCNoInvocationIdTest() { + setInvocationIdFromMDC(); + // InvocationId is set to a random UUID + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setResponseStatusCodeTest() { + setResponseStatusCode(200); + assertEquals("COMPLETE", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void setResponseStatusCodeErrorTest() { + setResponseStatusCode(400); + assertEquals("ERROR", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertEquals("400", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertEquals("Bad Request", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + } + + @Test + public void clearClientMDCsTest() { + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "7b77143c-9b50-410c-ac2f-05758a68e3e9"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, "SDNC"); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + + clearClientMDCs(); + assertNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Test + public void setTargetEntityTest() { + setTargetEntity(ONAPComponents.SO); + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + } + + @Test + public void setResponseDescriptionTest() { + setResponseDescription(502); + assertEquals("Bad Gateway", MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + } + + @Test + public void setMDCPartnerNameTest() { + MultivaluedMap headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.PARTNER_NAME, "SO"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameUserAgentHeaderTest() { + MultivaluedMap headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(HttpHeaders.USER_AGENT, "Apache-HttpClient/4.5.8 (Java/1.8.0_191)"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("Apache-HttpClient/4.5.8 (Java/1.8.0_191)", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameClientIdHeaderTest() { + MultivaluedMap headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(Constants.HttpHeaders.CLIENT_ID, "SO"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameNoHeaderTest() { + MultivaluedMap headerMap = new MultivaluedHashMap<>(); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("UNKNOWN", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setServerFQDNTest() { + setServerFQDN(); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + } + + @Test + public void setClientIPAddressTest() { + when(httpServletRequest.getHeader("X-Forwarded-For")).thenReturn("127.0.0.2"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.2", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNoHeaderTest() { + when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.1", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNullTest() { + setClientIPAddress(null); + + assertEquals("", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setEntryTimeStampTest() { + setEntryTimeStamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + } + + @Test + public void setLogTimestampTest() { + setLogTimestamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); + } + + @Test + public void setInstanceIDTest() { + setInstanceID(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); + } + + @Test + public void getPropertyTest() { + System.setProperty("partnerName", "partnerName"); + + String partnerName = getProperty("partnerName"); + assertEquals("partnerName", partnerName); + } + + @Test + public void getPropertyNullTest() { + String partnerName = getProperty("partner"); + assertEquals("UNKNOWN", partnerName); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java index af80b19..119bdf1 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java @@ -21,11 +21,11 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.junit.After; import org.junit.Test; @@ -34,14 +34,14 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.AuditLogContainerFilter; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.slf4j.MDC; @RunWith(MockitoJUnitRunner.class) public class AuditLogContainerFilterTest { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); @Mock private ContainerRequestContext containerRequest; @@ -49,9 +49,6 @@ public class AuditLogContainerFilterTest { @Mock private ContainerResponseContext containerResponse; - @Mock - private MDCSetup mdcSetup; - @Mock private UriInfo uriInfo; @@ -64,11 +61,14 @@ public class AuditLogContainerFilterTest { MDC.clear(); } + @Test public void filterTest() { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + MultivaluedMap headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.REQUEST_ID, "e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + when(containerRequest.getHeaders()).thenReturn(headerMap); when(uriInfo.getPath()).thenReturn("onap/so/serviceInstances"); - doReturn(uriInfo).when(containerRequest).getUriInfo(); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); auditLogContainerFilter.filter(containerRequest); assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java index 1a0d0ef..f2a8218 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java @@ -21,7 +21,7 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; @@ -34,9 +34,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.AuditLogServletFilter; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @@ -49,9 +46,6 @@ public class AuditLogServletFilterTest { @Mock private ServletResponse response; - @Mock - private MDCSetup mdcSetup; - @Mock private HttpServletRequest servletRequest; @@ -69,11 +63,10 @@ public class AuditLogServletFilterTest { @Test public void preTest() { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); when(servletRequest.getRequestURI()).thenReturn("onap/so/serviceInstances"); - auditLogServletFilter.pre(servletRequest, mdcSetup); + auditLogServletFilter.pre(servletRequest); - assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); } @@ -85,4 +78,5 @@ public class AuditLogServletFilterTest { assertEquals(200, responseCode); } + } diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java index 4f8d16d..4d1f102 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java @@ -24,8 +24,6 @@ import static org.junit.Assert.assertEquals; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import org.junit.Test; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; public class LoggingContainerFilterTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java deleted file mode 100644 index 1687c19..0000000 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - Logging - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.logging.filter.base; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.when; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.ONAPComponents; -import org.onap.logging.filter.base.SimpleHashMap; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.slf4j.MDC; - -@RunWith(MockitoJUnitRunner.class) -public class MDCSetupTest { - - @Mock - private HttpServletRequest httpServletRequest; - - @Spy - @InjectMocks - private MDCSetup mdcSetup = new MDCSetup(); - - private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; - private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a"; - - @After - public void tearDown() { - MDC.clear(); - } - - @Test - public void setElapsedTimeTest() { - String expected = "318"; - MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); - - mdcSetup.setElapsedTime(); - assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); - } - - @Test - public void setElapsedTimeInvokeTimestampTest() { - String expected = "318"; - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); - - mdcSetup.setElapsedTimeInvokeTimestamp(); - assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); - } - - @Test - public void setRequestIdTest() { - HashMap headers = new HashMap<>(); - headers.put(ONAPLogConstants.Headers.REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); - assertEquals(requestId, fetchedRequestId); - } - - @Test - public void setRequestIdRequestIdHeaderTest() { - HashMap headers = new HashMap<>(); - headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); - assertEquals(requestId, fetchedRequestId); - } - - @Test - public void setRequestIdTransactionIdHeaderTest() { - HashMap headers = new HashMap<>(); - headers.put(Constants.HttpHeaders.TRANSACTION_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); - assertEquals(requestId, fetchedRequestId); - } - - @Test - public void setRequestIdEcompRequestIdHeaderTest() { - HashMap headers = new HashMap<>(); - headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); - assertEquals(requestId, fetchedRequestId); - } - - @Test - public void setRequestIdNoHeaderTest() { - HashMap headers = new HashMap<>(); - String fetchedRequestId = mdcSetup.getRequestId(new SimpleHashMap(headers)); - assertNotNull(fetchedRequestId); - } - - @Test - public void setInvocationIdTest() { - HashMap headers = new HashMap<>(); - headers.put(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); - mdcSetup.setInvocationId(new SimpleHashMap(headers)); - assertEquals(invocationId, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - } - - @Test - public void setInvocationIdNoHeaderTest() { - HashMap headers = new HashMap<>(); - mdcSetup.setInvocationId(new SimpleHashMap(headers)); - assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - } - - @Test - public void setInvovationIdFromMDCTest() { - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "7b77143c-9b50-410c-ac2f-05758a68e3e8"); - mdcSetup.setInvocationIdFromMDC(); - assertEquals("7b77143c-9b50-410c-ac2f-05758a68e3e8", MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - } - - @Test - public void setInvocationIdFromMDCNoInvocationIdTest() { - mdcSetup.setInvocationIdFromMDC(); - // InvocationId is set to a random UUID - assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - } - - @Test - public void setResponseStatusCodeTest() { - mdcSetup.setResponseStatusCode(200); - assertEquals("COMPLETE", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } - - @Test - public void setResponseStatusCodeErrorTest() { - mdcSetup.setResponseStatusCode(400); - assertEquals("ERROR", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertEquals("400", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); - assertEquals("Bad Request", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); - } - - @Test - public void clearClientMDCsTest() { - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "7b77143c-9b50-410c-ac2f-05758a68e3e9"); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "Bad Gateway"); - MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, "Bad Gateway"); - MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, "502"); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "502"); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, "502"); - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, "SDNC"); - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - - mdcSetup.clearClientMDCs(); - assertNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); - assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); - assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); - assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); - assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); - assertNull(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); - } - - @Test - public void setTargetEntityTest() { - mdcSetup.setTargetEntity(ONAPComponents.SO); - assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); - } - - @Test - public void setResponseDescriptionTest() { - mdcSetup.setResponseDescription(502); - assertEquals("Bad Gateway", MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); - } - - @Test - public void setMDCPartnerNameTest() { - MultivaluedMap headerMap = new MultivaluedHashMap<>(); - headerMap.putSingle(ONAPLogConstants.Headers.PARTNER_NAME, "SO"); - SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - - mdcSetup.setMDCPartnerName(headers); - - assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - - @Test - public void setMDCPartnerNameUserAgentHeaderTest() { - MultivaluedMap headerMap = new MultivaluedHashMap<>(); - headerMap.putSingle(HttpHeaders.USER_AGENT, "Apache-HttpClient/4.5.8 (Java/1.8.0_191)"); - SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - - mdcSetup.setMDCPartnerName(headers); - - assertEquals("Apache-HttpClient/4.5.8 (Java/1.8.0_191)", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - - @Test - public void setMDCPartnerNameClientIdHeaderTest() { - MultivaluedMap headerMap = new MultivaluedHashMap<>(); - headerMap.putSingle(Constants.HttpHeaders.CLIENT_ID, "SO"); - SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - - mdcSetup.setMDCPartnerName(headers); - - assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - - @Test - public void setMDCPartnerNameNoHeaderTest() { - MultivaluedMap headerMap = new MultivaluedHashMap<>(); - SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); - - mdcSetup.setMDCPartnerName(headers); - - assertEquals("UNKNOWN", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - - @Test - public void setServerFQDNTest() { - mdcSetup.setServerFQDN(); - assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS)); - assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); - } - - @Test - public void setClientIPAddressTest() { - when(httpServletRequest.getHeader("X-Forwarded-For")).thenReturn("127.0.0.2"); - mdcSetup.setClientIPAddress(httpServletRequest); - - assertEquals("127.0.0.2", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); - } - - @Test - public void setClientIPAddressNoHeaderTest() { - when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1"); - mdcSetup.setClientIPAddress(httpServletRequest); - - assertEquals("127.0.0.1", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); - } - - @Test - public void setClientIPAddressNullTest() { - mdcSetup.setClientIPAddress(null); - - assertEquals("", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); - } - - @Test - public void setEntryTimeStampTest() { - mdcSetup.setEntryTimeStamp(); - - assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - } - - @Test - public void setLogTimestampTest() { - mdcSetup.setLogTimestamp(); - - assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); - } - - @Test - public void setInstanceIDTest() { - mdcSetup.setInstanceID(); - - assertNotNull(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - } - - @Test - public void setServiceNameTest() { - String requestUri = "onap/so/serviceInstances"; - when(httpServletRequest.getRequestURI()).thenReturn(requestUri); - mdcSetup.setServiceName(httpServletRequest); - - assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - } -} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java index 9a9f883..ed217aa 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java @@ -23,9 +23,11 @@ package org.onap.logging.filter.base; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; import java.net.URI; import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; @@ -36,18 +38,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.MetricLogClientFilter; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @RunWith(MockitoJUnitRunner.class) public class MetricLogClientFilterTest { - - @Mock - private MDCSetup mdcSetup; - @Mock private ClientRequestContext clientRequest; @@ -64,10 +59,9 @@ public class MetricLogClientFilterTest { public void setupHeadersTest() { MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "8819bfb4-69d2-43fc-b0d6-81d2690533ea"); MultivaluedMap headers = new MultivaluedHashMap<>(); - when(clientRequest.getHeaders()).thenReturn(headers); - doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(clientRequest); + doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(); - metricLogClientFilter.setupHeaders(clientRequest); + metricLogClientFilter.setupHeaders(clientRequest, headers); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); @@ -80,6 +74,7 @@ public class MetricLogClientFilterTest { @Test public void setupMDCTest() throws URISyntaxException { + // TODO ingest change from upstream MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); URI uri = new URI("onap/so/serviceInstances"); doReturn(uri).when(clientRequest).getUri(); @@ -110,15 +105,15 @@ public class MetricLogClientFilterTest { @Test public void extractRequestIDTest() { MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - String requestId = metricLogClientFilter.extractRequestID(clientRequest); + String requestId = metricLogClientFilter.extractRequestID(); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); } @Test public void extractRequestIDNullTest() throws URISyntaxException { - URI uri = new URI("onap/so/serviceInstances"); - doReturn(uri).when(clientRequest).getUri(); - String requestId = metricLogClientFilter.extractRequestID(clientRequest); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = metricLogClientFilter.extractRequestID(); assertNotNull(requestId); assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java index 5156516..0290784 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java @@ -33,8 +33,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.PayloadLoggingClientFilter; @RunWith(MockitoJUnitRunner.class) public class PayloadLoggingClientFilterTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java deleted file mode 100644 index 4ec14bc..0000000 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/PropertyUtilTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - Logging - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.logging.filter.base; - -import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Test; -import org.onap.logging.filter.base.PropertyUtil; - -public class PropertyUtilTest { - - private PropertyUtil propertyUtil = new PropertyUtil(); - - @After - public void tearDown() { - System.clearProperty("partnerName"); - } - - @Test - public void getPropertyTest() { - System.setProperty("partnerName", "partnerName"); - - String partnerName = propertyUtil.getProperty("partnerName"); - assertEquals("partnerName", partnerName); - } - - @Test - public void getPropertyNullTest() { - String partnerName = propertyUtil.getProperty("partner"); - assertEquals("UNKNOWN", partnerName); - } -} diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java index a1c5f9b..e2c5da9 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java @@ -24,8 +24,6 @@ import static org.junit.Assert.assertEquals; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import org.junit.Test; -import org.onap.logging.filter.base.SimpleJaxrsHeadersMap; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; public class SimpleJaxrsHeadersMapTest { diff --git a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java index f1e6af8..fff6776 100644 --- a/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java +++ b/reference/logging-filter/logging-filter-base/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java @@ -29,7 +29,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.SimpleServletHeadersMap; @RunWith(MockitoJUnitRunner.class) public class SimpleServletHeadersMapTest { diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java index d8d6bf4..dc1918b 100644 --- a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/LoggingInterceptor.java @@ -18,32 +18,25 @@ * ============LICENSE_END========================================================= */ + package org.onap.logging.filter.spring; -import java.util.Collections; -import java.util.Map; -import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Providers; -import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.base.AbstractAuditLogFilter; import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.filter.base.SimpleServletHeadersMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @Component -public class LoggingInterceptor extends HandlerInterceptorAdapter { - - private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class); - - private MDCSetup mdcSetup = new MDCSetup(); +public class LoggingInterceptor extends AbstractAuditLogFilter + implements HandlerInterceptor { @Context private Providers providers; @@ -52,45 +45,24 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SimpleMap headers = new SimpleServletHeadersMap(request); - String requestId = mdcSetup.getRequestId(headers); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - mdcSetup.setInvocationId(headers); - mdcSetup.setServiceName(request); - mdcSetup.setMDCPartnerName(headers); - mdcSetup.setClientIPAddress(request); - mdcSetup.setEntryTimeStamp(); - mdcSetup.setInstanceID(); - mdcSetup.setServerFQDN(); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - if (logger.isDebugEnabled()) - logRequestInformation(request); + pre(headers, request, request); return true; } - protected void logRequestInformation(HttpServletRequest request) { - Map headers = Collections.list((request).getHeaderNames()).stream() - .collect(Collectors.toMap(h -> h, request::getHeader)); - - logger.debug("===========================request begin================================================"); - logger.debug("URI : {}", request.getRequestURI()); - logger.debug("Method : {}", request.getMethod()); - logger.debug("Headers : {}", headers); - logger.debug("==========================request end================================================"); + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + post(response); + } + @Override + protected int getResponseCode(HttpServletResponse response) { + return response.getStatus(); } @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - mdcSetup.setResponseStatusCode(response.getStatus()); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTime(); - mdcSetup.setResponseDescription(response.getStatus()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getStatus())); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); - MDC.clear(); + protected void setServiceName(HttpServletRequest request) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); } + } diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java index 6eeee1a..1437435 100644 --- a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientFilter.java @@ -21,99 +21,69 @@ package org.onap.logging.filter.spring; import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.util.List; -import java.util.UUID; +import org.onap.logging.filter.base.AbstractMetricLogFilter; import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.PropertyUtil; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.slf4j.MDC; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; import org.springframework.http.HttpHeaders; 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; -public class SpringClientFilter implements ClientHttpRequestInterceptor { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final String TRACE = "trace-#"; - private MDCSetup mdcSetup = new MDCSetup(); - private final String partnerName; - private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN"); +public class SpringClientFilter extends AbstractMetricLogFilter + implements ClientHttpRequestInterceptor { public SpringClientFilter() { - this.partnerName = getPartnerName(); + } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - processRequest(request, body); + pre(request, request.getHeaders()); ClientHttpResponse response = execution.execute(request, body); - processResponse(response); + post(request, response); return response; } - protected void processRequest(HttpRequest request, byte[] body) throws IOException { - mdcSetup.setInvocationIdFromMDC(); - setupMDC(request); - setupHeaders(request); - if (logger.isDebugEnabled()) { - logger.debug("===========================request begin================================================"); - logger.debug("URI : {}", request.getURI()); - logger.debug("Method : {}", request.getMethod()); - logger.debug("Headers : {}", request.getHeaders()); - logger.debug("Request body: {}", new String(body, StandardCharsets.UTF_8)); - logger.debug("==========================request end================================================"); - } + @Override + protected void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { + requestHeaders.add(headerName, headerValue); } - protected void setupHeaders(HttpRequest clientRequest) { - HttpHeaders headers = clientRequest.getHeaders(); - String requestId = extractRequestID(clientRequest); - headers.add(ONAPLogConstants.Headers.REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); - headers.add(Constants.HttpHeaders.TRANSACTION_ID, requestId); - headers.add(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); - headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - headers.add(ONAPLogConstants.Headers.PARTNER_NAME, partnerName); + @Override + protected String getTargetServiceName(HttpRequest request) { + return request.getURI().toString(); + } + + @Override + protected String getServiceName(HttpRequest request) { + return request.getURI().getPath(); } - protected String extractRequestID(HttpRequest clientRequest) { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); - if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) { - requestId = UUID.randomUUID().toString(); - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getURI()); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + @Override + protected int getHttpStatusCode(ClientHttpResponse response) { + try { + return response.getStatusCode().value(); + } catch (IOException e) { + // TODO figure out the right thing to do here + return 500; } - return requestId; } - protected void setupMDC(HttpRequest clientRequest) { - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getURI().toString()); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, extractTargetEntity(clientRequest)); - if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, clientRequest.getURI().getPath()); + @Override + protected String getResponseCode(ClientHttpResponse response) { + try { + return response.getStatusCode().toString(); + } catch (IOException e) { + return "500"; } - mdcSetup.setServerFQDN(); } - protected String extractTargetEntity(HttpRequest clientRequest) { + @Override + protected String getTargetEntity(HttpRequest clientRequest) { HttpHeaders headers = clientRequest.getHeaders(); String headerTargetEntity = null; List headerTargetEntityList = headers.get(Constants.HttpHeaders.TARGET_ENTITY_HEADER); @@ -131,27 +101,4 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { return targetEntity; } - protected void processResponse(ClientHttpResponse response) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("============================response begin=========================================="); - logger.debug("Status code : {}", response.getStatusCode()); - logger.debug("Status text : {}", response.getStatusText()); - logger.debug("Headers : {}", response.getHeaders()); - logger.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); - logger.debug("=======================response end================================================="); - } - mdcSetup.setLogTimestamp(); - mdcSetup.setElapsedTimeInvokeTimestamp(); - mdcSetup.setResponseStatusCode(response.getRawStatusCode()); - int statusCode = response.getRawStatusCode(); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(statusCode)); - mdcSetup.setResponseDescription(statusCode); - logger.info(INVOKE_RETURN, "InvokeReturn"); - mdcSetup.clearClientMDCs(); - } - - protected String getPartnerName() { - PropertyUtil p = new PropertyUtil(); - return p.getProperty(Constants.Property.PARTNER_NAME); - } } diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java new file mode 100644 index 0000000..47ea031 --- /dev/null +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/SpringClientPayloadFilter.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.logging.filter.spring; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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; + +public class SpringClientPayloadFilter implements ClientHttpRequestInterceptor { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + protected void logRequest(HttpRequest request, byte[] body) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("===========================request begin================================================"); + logger.debug("URI : {}", request.getURI()); + logger.debug("Method : {}", request.getMethod()); + logger.debug("Headers : {}", request.getHeaders()); + logger.debug("Request body: {}", new String(body, StandardCharsets.UTF_8)); + logger.debug("==========================request end================================================"); + } + } + + protected void logResponse(ClientHttpResponse response) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("============================response begin=========================================="); + logger.debug("Status code : {}", response.getStatusCode()); + logger.debug("Status text : {}", response.getStatusText()); + logger.debug("Headers : {}", response.getHeaders()); + logger.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); + logger.debug("=======================response end================================================="); + } + } + +} diff --git a/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java new file mode 100644 index 0000000..887e621 --- /dev/null +++ b/reference/logging-filter/logging-filter-spring/src/main/java/org/onap/logging/filter/spring/StatusLoggingInterceptor.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.logging.filter.spring; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Providers; +import org.onap.logging.filter.base.PayloadLoggingServletFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +// TODO do we want this class to log message payloads? In the previous implementation it did not +@Component +public class StatusLoggingInterceptor extends PayloadLoggingServletFilter implements HandlerInterceptor { + + private static final Logger logger = LoggerFactory.getLogger(StatusLoggingInterceptor.class); + + @Context + private Providers providers; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (logger.isDebugEnabled()) { + logRequestInformation(request); + } + return true; + } + + protected void logRequestInformation(HttpServletRequest request) { + logger.debug("===========================request begin================================================"); + logger.debug("URI : {}", request.getRequestURI()); + logger.debug("Method : {}", request.getMethod()); + logger.debug("Headers : {}", getSecureRequestHeaders(request)); + logger.debug("==========================request end================================================"); + } + + // TODO previously no response information was being logged, I followed the format in SpringClientPayloadFilter + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + if (logger.isDebugEnabled()) { + logger.debug("============================response begin=========================================="); + logger.debug("Status code : {}", response.getStatus()); + logger.debug("Status text : {}", Response.Status.fromStatusCode(response.getStatus())); + logger.debug("Headers : {}", formatResponseHeaders(response)); + logger.debug("=======================response end================================================="); + } + } +} diff --git a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java index 1a6d701..1d373dc 100644 --- a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java +++ b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/LoggingInterceptorTest.java @@ -21,8 +21,7 @@ package org.onap.logging.filter.spring; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.junit.Assert.assertNotNull; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; @@ -31,8 +30,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; @@ -48,18 +45,14 @@ public class LoggingInterceptorTest { @Mock private Object handler; - @Mock - private MDCSetup mdcSetup; - @Spy @InjectMocks private LoggingInterceptor loggingInterceptor; @Test public void preHandleTest() throws Exception { - when(mdcSetup.getRequestId(any(SimpleMap.class))).thenReturn("428443e6-eeb2-4e4a-9a8c-2ca9e2bc8067"); loggingInterceptor.preHandle(request, response, handler); assertEquals(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), "INPROGRESS"); - assertEquals("428443e6-eeb2-4e4a-9a8c-2ca9e2bc8067", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); } } diff --git a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java index 9de5d68..3836ab7 100644 --- a/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java +++ b/reference/logging-filter/logging-filter-spring/src/test/java/org/onap/logging/filter/spring/SpringClientFilterTest.java @@ -22,12 +22,14 @@ package org.onap.logging.filter.spring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,8 +37,8 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.AbstractFilter; import org.onap.logging.filter.base.Constants; -import org.onap.logging.filter.base.MDCSetup; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; import org.springframework.http.HttpHeaders; @@ -45,10 +47,10 @@ import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; @RunWith(MockitoJUnitRunner.class) -public class SpringClientFilterTest { +public class SpringClientFilterTest extends SpringClientFilter { @Mock - private MDCSetup mdcSetup; + private AbstractFilter mdcSetup; @Mock private ClientHttpResponse response; @@ -70,8 +72,7 @@ public class SpringClientFilterTest { @Test public void processResponseTest() throws IOException { - String partnerName = springClientFilter.getPartnerName(); - + String partnerName = getPartnerName(); assertEquals("UNKNOWN", partnerName); } @@ -81,7 +82,7 @@ public class SpringClientFilterTest { headers.add(Constants.HttpHeaders.TARGET_ENTITY_HEADER, "SO"); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("SO", targetEntity); } @@ -91,7 +92,7 @@ public class SpringClientFilterTest { HttpHeaders headers = new HttpHeaders(); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("SO", targetEntity); } @@ -100,20 +101,17 @@ public class SpringClientFilterTest { HttpHeaders headers = new HttpHeaders(); when(clientRequest.getHeaders()).thenReturn(headers); - String targetEntity = springClientFilter.extractTargetEntity(clientRequest); + String targetEntity = springClientFilter.getTargetEntity(clientRequest); assertEquals("Unknown-Target-Entity", targetEntity); } @Test public void setupMDCTest() throws URISyntaxException { - doReturn("SO").when(springClientFilter).extractTargetEntity(clientRequest); URI uri = new URI("onap/so/serviceInstances"); when(clientRequest.getURI()).thenReturn(uri); - - springClientFilter.setupMDC(clientRequest); - + when(clientRequest.getHeaders()).thenReturn(new HttpHeaders()); + setupMDC(clientRequest); assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); - assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); assertNotNull(ONAPLogConstants.MDCs.SERVICE_NAME); @@ -123,11 +121,10 @@ public class SpringClientFilterTest { @Test public void setupHeadersTest() { MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "8819bfb4-69d2-43fc-b0d6-81d2690533ea"); - HttpHeaders headers = new HttpHeaders(); - when(clientRequest.getHeaders()).thenReturn(headers); - doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(springClientFilter).extractRequestID(clientRequest); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - springClientFilter.setupHeaders(clientRequest); + HttpHeaders headers = new HttpHeaders(); + setupHeaders(clientRequest, headers); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); @@ -141,13 +138,16 @@ public class SpringClientFilterTest { @Test public void extractRequestIDTest() { MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); - String requestId = springClientFilter.extractRequestID(clientRequest); + String requestId = extractRequestID(); assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); } @Test public void extractRequestIDNullTest() { - String requestId = springClientFilter.extractRequestID(clientRequest); + // NPE exception will occur when extractRequestID is called if INVOKE_TIMESTAMP is null + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = extractRequestID(); assertNotNull(requestId); assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); @@ -156,10 +156,7 @@ public class SpringClientFilterTest { @Test public void interceptTest() throws IOException { byte[] body = new byte[3]; - doNothing().when(springClientFilter).processRequest(clientRequest, body); doReturn(response).when(execution).execute(clientRequest, body); - doNothing().when(springClientFilter).processResponse(response); - ClientHttpResponse httpResponse = springClientFilter.intercept(clientRequest, body, execution); assertEquals(response, httpResponse); } -- cgit 1.2.3-korg