Merge "[AAI] Fix doc config files"
[aai/aai-common.git] / aai-els-onap-logging / src / main / java / org / onap / aai / aailog / filter / RestControllerClientLoggingInterceptor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright Â© 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.aailog.filter;
22
23 import com.sun.jersey.api.client.ClientHandler;
24 import com.sun.jersey.api.client.ClientHandlerException;
25 import com.sun.jersey.api.client.ClientRequest;
26 import com.sun.jersey.api.client.ClientResponse;
27 import com.sun.jersey.api.client.filter.ClientFilter;
28
29 import java.time.ZoneOffset;
30 import java.time.ZonedDateTime;
31 import java.time.format.DateTimeFormatter;
32 import java.util.UUID;
33
34 import javax.ws.rs.core.MultivaluedMap;
35
36 import org.onap.aai.aailog.logs.ServiceName;
37 import org.onap.logging.filter.base.Constants;
38 import org.onap.logging.filter.base.MDCSetup;
39 import org.onap.logging.ref.slf4j.ONAPLogConstants;
40 import org.slf4j.*;
41
42 public class RestControllerClientLoggingInterceptor extends ClientFilter {
43     private static final Logger logger = LoggerFactory.getLogger(RestControllerClientLoggingInterceptor.class);
44     private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
45     private final MDCSetup mdcSetup;
46     private final String partnerName;
47
48     public RestControllerClientLoggingInterceptor() {
49         mdcSetup = new MDCSetup();
50         partnerName = getPartnerName();
51     }
52
53     @Override
54     public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
55         ClientResponse clientResponse = null;
56         pre(clientRequest);
57         // Call the next client handler in the filter chain
58         ClientHandler nextHandler = getNext();
59         if (nextHandler != null) {
60             clientResponse = nextHandler.handle(clientRequest);
61         }
62         if (clientResponse != null) {
63             post(clientResponse);
64         }
65         return clientResponse;
66     }
67
68     protected String getTargetServiceName(ClientRequest clientRequest) {
69         return getServiceName(clientRequest);
70     }
71
72     protected String getServiceName(ClientRequest clientRequest) {
73         String path = clientRequest.getURI().getRawPath();
74         return ServiceName.extractServiceName(path);
75     }
76
77     protected int getHttpStatusCode(ClientResponse response) {
78         return response.getStatus();
79     }
80
81     protected String getResponseCode(ClientResponse clientResponse) {
82         return String.valueOf(clientResponse.getStatus());
83     }
84
85     protected String getTargetEntity(ClientRequest ClientRequest) {
86         return Constants.DefaultValues.UNKNOWN_TARGET_ENTITY;
87     };
88
89     protected void pre(ClientRequest clientRequest) {
90         try {
91             setInvocationId(clientRequest);
92             setupMDC(clientRequest);
93             setupHeaders(clientRequest);
94             logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke");
95         } catch (Exception e) {
96             logger.warn("Error in RestControllerClientLoggingInterceptor pre", e.getMessage());
97         }
98     }
99
100     public void setInvocationId(ClientRequest clientRequest) {
101         String invocationId = null;
102         MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
103         Object id = requestHeaders.get(ONAPLogConstants.Headers.INVOCATION_ID);
104         if (id != null) {
105             invocationId = (String) id;
106         }
107         requestHeaders.remove(ONAPLogConstants.Headers.INVOCATION_ID);
108         if (invocationId == null) {
109             invocationId = UUID.randomUUID().toString();
110         }
111         MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
112     }
113
114     protected void setupHeaders(ClientRequest clientRequest) {
115         String requestId = extractRequestID(clientRequest);
116         MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
117         addHeader(requestHeaders, ONAPLogConstants.Headers.REQUEST_ID, requestId);
118         addHeader(requestHeaders, Constants.HttpHeaders.HEADER_REQUEST_ID, requestId);
119         Object requestIdObj = requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID);
120         if (requestIdObj == null) {
121             addHeader(requestHeaders, Constants.HttpHeaders.TRANSACTION_ID, requestId);
122         }
123         addHeader(requestHeaders, Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId);
124         addHeader(requestHeaders, ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
125         if (partnerName != null && (!partnerName.isEmpty())) {
126             addHeader(requestHeaders, ONAPLogConstants.Headers.PARTNER_NAME, partnerName);
127         }
128     }
129
130     protected void setupMDC(ClientRequest clientRequest) {
131         MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
132                 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
133         MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, getTargetServiceName(clientRequest));
134         MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
135         mdcSetup.setInvocationIdFromMDC();
136
137         if (MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY) == null) {
138             String targetEntity = getTargetEntity(clientRequest);
139             if (targetEntity != null) {
140                 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity);
141             } else {
142                 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, Constants.DefaultValues.UNKNOWN_TARGET_ENTITY);
143             }
144         }
145
146         if (MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME) == null) {
147             MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, getServiceName(clientRequest));
148         }
149         mdcSetup.setServerFQDN();
150     }
151
152     protected String extractRequestID(ClientRequest clientRequest) {
153         String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
154         if (requestId == null || requestId.isEmpty()) {
155             MultivaluedMap<String, Object> requestHeaders = clientRequest.getHeaders();
156             Object requestIdObj = requestHeaders.getFirst(Constants.HttpHeaders.TRANSACTION_ID);
157             if (requestIdObj != null) {
158                 requestId = (String) requestIdObj;
159             }
160             if (requestId == null || requestId.isEmpty()) {
161                 requestId = UUID.randomUUID().toString();
162             }
163             mdcSetup.setLogTimestamp();
164             mdcSetup.setElapsedTimeInvokeTimestamp();
165             logger.warn("No value found in MDC when checking key {} value will be set to {}",
166                     ONAPLogConstants.MDCs.REQUEST_ID, requestId);
167             MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
168         }
169         return requestId;
170     }
171
172     protected void post(ClientResponse clientResponse) {
173         try {
174             mdcSetup.setLogTimestamp();
175             mdcSetup.setElapsedTimeInvokeTimestamp();
176             mdcSetup.setResponseStatusCode(getHttpStatusCode(clientResponse));
177             mdcSetup.setResponseDescription(getHttpStatusCode(clientResponse));
178             MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, getResponseCode(clientResponse));
179             logger.info(INVOKE_RETURN, "InvokeReturn");
180             mdcSetup.clearClientMDCs();
181         } catch (Exception e) {
182             logger.warn("Error in RestControllerClientLoggingInterceptor post", e.getMessage());
183         }
184     }
185
186     protected String getPartnerName() {
187         return mdcSetup.getProperty(Constants.Property.PARTNER_NAME);
188     }
189
190     protected void addHeader(MultivaluedMap<String, Object> requestHeaders, String headerName, String headerValue) {
191         requestHeaders.add(headerName, headerValue);
192     }
193 }