From 5104a66d12a2ada0819d1cbcaf935785748f2b87 Mon Sep 17 00:00:00 2001 From: "Brittany Plummer (bp896r)" Date: Tue, 27 Aug 2019 15:36:44 -0400 Subject: Add JAX-RS and Spring filters for setting up MDC Issue-ID: LOG-1113 Change-Id: I7167943384e3983c7eced1c969ed51fcd8130c88 Signed-off-by: Brittany Plummer (bp896r) --- .../filter/base/AbstractAuditLogFilter.java | 83 +++++ .../filter/base/AuditLogContainerFilter.java | 75 +++++ .../logging/filter/base/AuditLogServletFilter.java | 86 +++++ .../org/onap/logging/filter/base/Constants.java | 45 +++ .../org/onap/logging/filter/base/MDCSetup.java | 212 +++++++++++++ .../logging/filter/base/MetricLogClientFilter.java | 128 ++++++++ .../onap/logging/filter/base/ONAPComponents.java | 80 +++++ .../logging/filter/base/ONAPComponentsList.java | 25 ++ .../filter/base/PayloadLoggingClientFilter.java | 164 ++++++++++ .../filter/base/PayloadLoggingServletFilter.java | 349 +++++++++++++++++++++ .../org/onap/logging/filter/base/PropertyUtil.java | 43 +++ .../onap/logging/filter/base/SimpleHashMap.java | 37 +++ .../logging/filter/base/SimpleJaxrsHeadersMap.java | 37 +++ .../org/onap/logging/filter/base/SimpleMap.java | 25 ++ .../filter/base/SimpleServletHeadersMap.java | 37 +++ 15 files changed, 1426 insertions(+) create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/Constants.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponents.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponentsList.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java create 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/main/java/org/onap/logging/filter/base/SimpleHashMap.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMap.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleMap.java create mode 100644 reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleServletHeadersMap.java (limited to 'reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter') 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 new file mode 100644 index 0000000..71d4e31 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AbstractAuditLogFilter.java @@ -0,0 +1,83 @@ +/*- + * ============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 javax.servlet.http.HttpServletRequest; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +public abstract class AbstractAuditLogFilter { + protected static final Logger logger = LoggerFactory.getLogger(AbstractAuditLogFilter.class); + + protected void pre(MDCSetup mdcSetup, SimpleMap headers, GenericRequest request, + HttpServletRequest httpServletRequest) { + try { + String requestId = mdcSetup.getRequestId(headers); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + mdcSetup.setInvocationId(headers); + setServiceName(request); + mdcSetup.setMDCPartnerName(headers); + mdcSetup.setServerFQDN(); + mdcSetup.setClientIPAddress(httpServletRequest); + mdcSetup.setInstanceID(); + mdcSetup.setEntryTimeStamp(); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + additionalPreHandling(request); + mdcSetup.setLogTimestamp(); + mdcSetup.setElapsedTime(); + logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); + } catch (Exception e) { + logger.warn("Error in AbstractInboundFilter pre", e); + } + } + + protected void post(MDCSetup mdcSetup, GenericResponse response) { + try { + int responseCode = getResponseCode(response); + mdcSetup.setResponseStatusCode(responseCode); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseCode)); + mdcSetup.setResponseDescription(responseCode); + mdcSetup.setLogTimestamp(); + mdcSetup.setElapsedTime(); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting."); + additionalPostHandling(response); + } catch (Exception e) { + logger.warn("Error in AbstractInboundFilter post", e); + } finally { + MDC.clear(); + } + } + + protected abstract int getResponseCode(GenericResponse response); + + protected abstract void setServiceName(GenericRequest request); + + protected void additionalPreHandling(GenericRequest request) { + // override to add additional pre handling + } + + protected void additionalPostHandling(GenericResponse response) { + // override to add additional post handling + } + +} 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 new file mode 100644 index 0000000..3d04b62 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogContainerFilter.java @@ -0,0 +1,75 @@ +/*- + * ============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.io.IOException; +import javax.annotation.Priority; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.ext.Provider; +import javax.ws.rs.ext.Providers; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +@Priority(1) +@Provider +public class AuditLogContainerFilter extends AbstractAuditLogFilter + implements ContainerRequestFilter, ContainerResponseFilter { + + protected static Logger logger = LoggerFactory.getLogger(AuditLogContainerFilter.class); + + @Context + private HttpServletRequest httpServletRequest; + + @Context + private Providers providers; + + private MDCSetup mdcSetup = new MDCSetup(); + + @Override + public void filter(ContainerRequestContext containerRequest) { + SimpleMap headers = new SimpleJaxrsHeadersMap(containerRequest.getHeaders()); + pre(mdcSetup, headers, containerRequest, httpServletRequest); + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + post(mdcSetup, responseContext); + } + + @Override + protected void setServiceName(ContainerRequestContext containerRequest) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, containerRequest.getUriInfo().getPath()); + } + + @Override + protected int getResponseCode(ContainerResponseContext response) { + return response.getStatus(); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java new file mode 100644 index 0000000..ac7529f --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/AuditLogServletFilter.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * 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.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +public class AuditLogServletFilter extends AbstractAuditLogFilter + implements Filter { + + @Override + public void destroy() { + // this method does nothing + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) + throws IOException, ServletException { + MDCSetup mdcSetup = new MDCSetup(); + try { + if (request != null && request instanceof HttpServletRequest) { + pre((HttpServletRequest) request, mdcSetup); + } + filterChain.doFilter(request, response); + } finally { + if (request != null && request instanceof HttpServletRequest) { + post((HttpServletRequest) request, (HttpServletResponse) response, mdcSetup); + } + MDC.clear(); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // this method does nothing + } + + protected void pre(HttpServletRequest request, MDCSetup mdcSetup) { + SimpleMap headers = new SimpleServletHeadersMap(request); + pre(mdcSetup, headers, request, request); + } + + @Override + protected void setServiceName(HttpServletRequest request) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); + } + + private void post(HttpServletRequest request, HttpServletResponse response, MDCSetup mdcSetup) { + post(mdcSetup, response); + } + + @Override + protected int getResponseCode(HttpServletResponse response) { + return response.getStatus(); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/Constants.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/Constants.java new file mode 100644 index 0000000..1549be1 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/Constants.java @@ -0,0 +1,45 @@ +/*- + * ============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; + +public class Constants { + + public static final class DefaultValues { + public static final String UNKNOWN = "UNKNOWN"; + public static final String UNKNOWN_TARGET_ENTITY = "Unknown-Target-Entity"; + } + + public static final class HttpHeaders { + public static final String HEADER_FROM_APP_ID = "X-FromAppId"; + public static final String ONAP_PARTNER_NAME = "X-ONAP-PartnerName"; + public static final String HEADER_REQUEST_ID = "X-RequestID"; + public static final String TRANSACTION_ID = "X-TransactionID"; + public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; + public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; + public static final String CLIENT_ID = "X-ClientID"; + public static final String INVOCATION_ID_HEADER = "X-InvocationID"; + public static final String TARGET_ENTITY_HEADER = "X-Target-Entity"; + } + + public static final class Property { + public static final String PARTNER_NAME = "partnerName"; + } +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java new file mode 100644 index 0000000..16fa210 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MDCSetup.java @@ -0,0 +1,212 @@ +/*- + * ============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 class MDCSetup { + + protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class); + + private static final String INSTANCE_UUID = UUID.randomUUID().toString(); + + public void setInstanceID() { + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID); + } + + public 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); + } + + public 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); + } + + public void setEntryTimeStamp() { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + } + + public void setServiceName(HttpServletRequest request) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); + } + + public 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(); + } + + public 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); + } + + public 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); + } + + public 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); + } + + public void setLogTimestamp() { + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + } + + public 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))); + } + + public 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))); + } + + public 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); + } + + public void setTargetEntity(ONAPComponentsList targetEntity) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString()); + } + + public 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); + } + + public void setResponseDescription(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString()); + } + + public void setErrorCode(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode)); + } + + public void setErrorDesc(int statusCode) { + MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString()); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.java new file mode 100644 index 0000000..8533456 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/MetricLogClientFilter.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 javax.annotation.Priority; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.Providers; +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; + +@Priority(0) +public class MetricLogClientFilter 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) { + try { + setupMDC(clientRequest); + setupHeaders(clientRequest); + logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke"); + } catch (Exception e) { + logger.warn("Error in JAX-RS client request filter", e); + } + } + + 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); + } + + 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(); + } + + 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 + 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 String getPartnerName() { + PropertyUtil p = new PropertyUtil(); + return p.getProperty(Constants.Property.PARTNER_NAME); + } +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponents.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponents.java new file mode 100644 index 0000000..1b9c1cd --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponents.java @@ -0,0 +1,80 @@ +/*- + * ============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.util.EnumSet; +import java.util.Set; + +public enum ONAPComponents implements ONAPComponentsList { + OPENSTACK_ADAPTER, + BPMN, + GRM, + AAI, + DMAAP, + POLICY, + CATALOG_DB, + REQUEST_DB, + SNIRO, + SDC, + EXTERNAL, + VNF_ADAPTER, + SDNC_ADAPTER, + MULTICLOUD, + CLAMP, + PORTAL, + VID, + APPC, + DCAE, + HOLMES, + SDNC, + SO, + VFC, + ESR, + DBC, + DR, + MR, + OPTF; + + + public static Set getSOInternalComponents() { + return EnumSet.of(OPENSTACK_ADAPTER, BPMN, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER); + } + + public static Set getDMAAPInternalComponents() { + return EnumSet.of(DBC, DR, MR); + } + + public static Set getAAIInternalComponents() { + return EnumSet.of(ESR); + } + + @Override + public String toString() { + if (getSOInternalComponents().contains(this)) + return SO + "." + this.name(); + else if (getDMAAPInternalComponents().contains(this)) + return DMAAP + "." + this.name(); + else if (getAAIInternalComponents().contains(this)) + return AAI + "." + this.name(); + else + return this.name(); + } +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponentsList.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponentsList.java new file mode 100644 index 0000000..f117ab7 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/ONAPComponentsList.java @@ -0,0 +1,25 @@ +/*- + * ============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; + +public interface ONAPComponentsList { + +} 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 new file mode 100644 index 0000000..045a729 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingClientFilter.java @@ -0,0 +1,164 @@ +/*- + * ============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.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PayloadLoggingClientFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { + + private static final Logger logger = LoggerFactory.getLogger(PayloadLoggingClientFilter.class); + private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream"; + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + private final int maxEntitySize; + + public PayloadLoggingClientFilter() { + maxEntitySize = 1024 * 1024; + } + + public PayloadLoggingClientFilter(int maxPayloadSize) { + 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()) { + stream = new BufferedInputStream(stream); + } + stream.mark(maxEntitySize + 1); + final byte[] entity = new byte[maxEntitySize + 1]; + final int entitySize = stream.read(entity); + if (entitySize != -1) { + b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); + } + if (entitySize > maxEntitySize) { + b.append("...more..."); + } + b.append('\n'); + stream.reset(); + return stream; + } + + @Override + public void filter(ClientRequestContext requestContext) throws IOException { + if (requestContext.hasEntity()) { + final OutputStream stream = new LoggingStream(requestContext.getEntityStream()); + requestContext.setEntityStream(stream); + requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); + } + String method = formatMethod(requestContext); + log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: " + + getHeaders(requestContext.getHeaders()))); + + } + + protected String getHeaders(MultivaluedMap headers) { + MultivaluedMap printHeaders = new MultivaluedHashMap<>(); + for (String header : headers.keySet()) { + if (!header.equals(HttpHeaders.AUTHORIZATION)) { + printHeaders.add(header, headers.getFirst(header)); + } + } + return printHeaders.toString(); + } + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + 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())); + } + } + + @Override + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); + context.proceed(); + if (stream != null) { + log(stream.getStringBuilder(DEFAULT_CHARSET)); + } + } + + private class LoggingStream extends FilterOutputStream { + + private final StringBuilder sb = new StringBuilder(); + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + LoggingStream(OutputStream out) { + super(out); + } + + StringBuilder getStringBuilder(Charset charset) { + // write entity to the builder + final byte[] entity = baos.toByteArray(); + + sb.append(new String(entity, 0, entity.length, charset)); + if (entity.length > maxEntitySize) { + sb.append("...more..."); + } + sb.append('\n'); + + return sb; + } + + @Override + public void write(final int i) throws IOException { + if (baos.size() <= maxEntitySize) { + baos.write(i); + } + out.write(i); + } + } + + protected String formatMethod(ClientRequestContext requestContext) { + String httpMethodOverride = requestContext.getHeaderString("X-HTTP-Method-Override"); + if (httpMethodOverride == null) { + return requestContext.getMethod(); + } else { + return requestContext.getMethod() + " (overridden to " + httpMethodOverride + ")"; + } + } +} 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 new file mode 100644 index 0000000..3e85b9d --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PayloadLoggingServletFilter.java @@ -0,0 +1,349 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * 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.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.zip.GZIPInputStream; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ReadListener; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; +import javax.ws.rs.core.HttpHeaders; + +public class PayloadLoggingServletFilter implements Filter { + + private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(PayloadLoggingServletFilter.class); + private static final String REDACTED = "***REDACTED***"; + + private static class ByteArrayServletStream extends ServletOutputStream { + ByteArrayOutputStream baos; + + ByteArrayServletStream(ByteArrayOutputStream baos) { + this.baos = baos; + } + + @Override + public void write(int param) throws IOException { + baos.write(param); + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setWriteListener(WriteListener arg0) { + // this method does nothing + } + } + + private static class ByteArrayPrintWriter extends PrintWriter { + private ByteArrayOutputStream baos; + private int errorCode = -1; + private String errorMsg = ""; + private boolean errored = false; + + public ByteArrayPrintWriter(ByteArrayOutputStream out) { + super(out); + this.baos = out; + } + + public ServletOutputStream getStream() { + return new ByteArrayServletStream(baos); + } + + public Boolean hasErrored() { + return errored; + } + + public int getErrorCode() { + return errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setError(int code) { + errorCode = code; + errored = true; + } + + public void setError(int code, String msg) { + errorMsg = msg; + errorCode = code; + errored = true; + } + + } + + private class BufferedServletInputStream extends ServletInputStream { + ByteArrayInputStream bais; + + public BufferedServletInputStream(ByteArrayInputStream bais) { + this.bais = bais; + } + + @Override + public int available() { + return bais.available(); + } + + @Override + public int read() { + return bais.read(); + } + + @Override + public int read(byte[] buf, int off, int len) { + return bais.read(buf, off, len); + } + + @Override + public boolean isFinished() { + return available() < 1; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener arg0) { + // this method does nothing + } + + } + + private class BufferedRequestWrapper extends HttpServletRequestWrapper { + ByteArrayInputStream bais; + ByteArrayOutputStream baos; + BufferedServletInputStream bsis; + byte[] buffer; + + public BufferedRequestWrapper(HttpServletRequest req) throws IOException { + super(req); + + InputStream is = req.getInputStream(); + baos = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int letti; + while ((letti = is.read(buf)) > 0) { + baos.write(buf, 0, letti); + } + buffer = baos.toByteArray(); + } + + @Override + public ServletInputStream getInputStream() { + try { + bais = new ByteArrayInputStream(buffer); + bsis = new BufferedServletInputStream(bais); + } catch (Exception ex) { + log.error("Exception in getInputStream", ex); + } + return bsis; + } + + public byte[] getBuffer() { + return buffer; + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // this method does nothing + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); + + StringBuilder requestHeaders = new StringBuilder("REQUEST|"); + requestHeaders.append(httpRequest.getMethod()); + 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(";"); + } + log.info(requestHeaders.toString()); + + log.info("REQUEST BODY|" + new String(bufferedRequest.getBuffer())); + + final HttpServletResponse response = (HttpServletResponse) servletResponse; + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(baos); + + HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) { + @Override + public PrintWriter getWriter() { + return pw; + } + + @Override + public ServletOutputStream getOutputStream() { + return pw.getStream(); + } + + @Override + public void sendError(int sc) throws IOException { + super.sendError(sc); + pw.setError(sc); + + } + + @Override + public void sendError(int sc, String msg) throws IOException { + super.sendError(sc, msg); + pw.setError(sc, msg); + } + }; + + try { + filterChain.doFilter(bufferedRequest, wrappedResp); + } catch (Exception e) { + log.error("Chain Exception", e); + throw e; + } finally { + 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("Status:"); + responseHeaders.append(response.getStatus()); + responseHeaders.append(";IsCommited:" + wrappedResp.isCommitted()); + + log.info(responseHeaders.toString()); + + if ("gzip".equals(response.getHeader("Content-Encoding"))) { + log.info("UNGZIPED RESPONSE BODY|" + decompressGZIPByteArray(bytes)); + } else { + log.info("RESPONSE BODY|" + new String(bytes)); + } + + if (pw.hasErrored()) { + log.info("ERROR RESPONSE|" + pw.getErrorCode() + ":" + pw.getErrorMsg()); + } else { + if (!wrappedResp.isCommitted()) { + response.getOutputStream().write(bytes); + response.getOutputStream().flush(); + } + } + } catch (Exception e) { + log.error("Exception in response filter", e); + } + } + } + + @Override + public void destroy() { + // this method does nothing + } + + private String decompressGZIPByteArray(byte[] bytes) { + BufferedReader in = null; + InputStreamReader inR = null; + ByteArrayInputStream byteS = null; + GZIPInputStream gzS = null; + StringBuilder str = new StringBuilder(); + try { + byteS = new ByteArrayInputStream(bytes); + gzS = new GZIPInputStream(byteS); + inR = new InputStreamReader(gzS); + in = new BufferedReader(inR); + + if (in != null) { + String content; + while ((content = in.readLine()) != null) { + str.append(content); + } + } + + } catch (Exception e) { + log.error("Failed get read GZIPInputStream", e); + } finally { + if (byteS != null) + try { + byteS.close(); + } catch (IOException e1) { + log.error("Failed to close ByteStream", e1); + } + if (gzS != null) + try { + gzS.close(); + } catch (IOException e2) { + log.error("Failed to close GZStream", e2); + } + if (inR != null) + try { + inR.close(); + } catch (IOException e3) { + log.error("Failed to close InputReader", e3); + } + if (in != null) + try { + in.close(); + } catch (IOException e) { + log.error("Failed to close BufferedReader", e); + } + } + return str.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 new file mode 100644 index 0000000..5a094eb --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/PropertyUtil.java @@ -0,0 +1,43 @@ +/*- + * ============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/main/java/org/onap/logging/filter/base/SimpleHashMap.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleHashMap.java new file mode 100644 index 0000000..1e9cedb --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleHashMap.java @@ -0,0 +1,37 @@ +/*- + * ============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.util.HashMap; + +public class SimpleHashMap implements SimpleMap { + private HashMap map; + + public SimpleHashMap(HashMap map) { + this.map = map; + } + + @Override + public String get(String key) { + return map.get(key); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMap.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMap.java new file mode 100644 index 0000000..5007478 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMap.java @@ -0,0 +1,37 @@ +/*- + * ============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 javax.ws.rs.core.MultivaluedMap; + +public class SimpleJaxrsHeadersMap implements SimpleMap { + MultivaluedMap map; + + public SimpleJaxrsHeadersMap(MultivaluedMap map) { + this.map = map; + } + + @Override + public String get(String key) { + return map.getFirst(key); + } + +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleMap.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleMap.java new file mode 100644 index 0000000..9543721 --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleMap.java @@ -0,0 +1,25 @@ +/*- + * ============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; + +public interface SimpleMap { + String get(String key); +} diff --git a/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleServletHeadersMap.java b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleServletHeadersMap.java new file mode 100644 index 0000000..e6a91fb --- /dev/null +++ b/reference/logging-filter/logging-filter-base/src/main/java/org/onap/logging/filter/base/SimpleServletHeadersMap.java @@ -0,0 +1,37 @@ +/*- + * ============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 javax.servlet.http.HttpServletRequest; + +public class SimpleServletHeadersMap implements SimpleMap { + private HttpServletRequest request; + + public SimpleServletHeadersMap(HttpServletRequest request) { + this.request = request; + } + + @Override + public String get(String key) { + return request.getHeader(key); + } + +} -- cgit 1.2.3-korg