2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.logging.jaxrs.filter.jersey;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.lang.annotation.Annotation;
27 import java.lang.reflect.Type;
28 import java.time.Instant;
29 import java.time.ZoneId;
30 import java.time.format.DateTimeFormatter;
31 import java.util.Locale;
32 import java.util.UUID;
34 import javax.annotation.Priority;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.ws.rs.container.ContainerRequestContext;
37 import javax.ws.rs.container.ContainerRequestFilter;
38 import javax.ws.rs.container.ContainerResponseContext;
39 import javax.ws.rs.container.ContainerResponseFilter;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.MultivaluedMap;
43 import javax.ws.rs.core.Response;
44 import javax.ws.rs.ext.MessageBodyWriter;
45 import javax.ws.rs.ext.Provider;
46 import javax.ws.rs.ext.Providers;
47 import org.onap.so.logger.MsoLogger;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.stereotype.Component;
53 import com.fasterxml.jackson.databind.ObjectMapper;
58 public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter {
60 protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class);
63 private HttpServletRequest httpServletRequest;
66 private Providers providers;
69 ObjectMapper objectMapper;
72 public void filter(ContainerRequestContext containerRequest) {
75 String clientID = null;
76 //check headers for request id
77 MultivaluedMap<String, String> headers = containerRequest.getHeaders();
78 String requestId = findRequestId(headers);
79 containerRequest.setProperty("requestId", requestId);
80 if(headers.containsKey(MsoLogger.CLIENT_ID)){
81 clientID = headers.getFirst(MsoLogger.CLIENT_ID);
84 headers.add(MsoLogger.CLIENT_ID, clientID);
87 String remoteIpAddress = "";
88 if (httpServletRequest != null) {
89 remoteIpAddress = httpServletRequest.getRemoteAddr();
91 Instant instant = Instant.now();
92 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
93 .withLocale( Locale.US )
94 .withZone( ZoneId.systemDefault() );
96 String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID );
97 if(partnerName == null || partnerName.isEmpty())
98 partnerName="UNKNOWN";
100 MDC.put(MsoLogger.REQUEST_ID,requestId);
101 MDC.put(MsoLogger.INVOCATION_ID,requestId);
102 MDC.put(MsoLogger.FROM_APP_ID,partnerName);
103 MDC.put(MsoLogger.SERVICE_NAME, containerRequest.getUriInfo().getPath());
104 MDC.put(MsoLogger.INVOCATION_ID, findInvocationId(headers));
105 MDC.put(MsoLogger.STATUSCODE, MsoLogger.INPROGRESS);
106 MDC.put(MsoLogger.BEGINTIME, formatter.format(instant));
107 MDC.put(MsoLogger.PARTNERNAME,partnerName);
108 MDC.put(MsoLogger.REMOTE_HOST, String.valueOf(remoteIpAddress));
109 MDC.put(MsoLogger.STARTTIME, String.valueOf(System.currentTimeMillis()));
110 logger.debug(MsoLogger.ENTRY, "Entering.");
111 } catch (Exception e) {
112 logger.warn("Error in incoming JAX-RS Inteceptor", e);
117 private String findRequestId(MultivaluedMap<String, String> headers) {
118 String requestId = (String) headers.getFirst(MsoLogger.HEADER_REQUEST_ID );
119 if(requestId == null || requestId.isEmpty()){
120 if(headers.containsKey(MsoLogger.ONAP_REQUEST_ID)){
121 requestId = headers.getFirst(MsoLogger.ONAP_REQUEST_ID);
122 }else if(headers.containsKey(MsoLogger.ECOMP_REQUEST_ID)){
123 requestId = headers.getFirst(MsoLogger.ECOMP_REQUEST_ID);
125 requestId = UUID.randomUUID().toString();
131 private String findInvocationId(MultivaluedMap<String, String> headers) {
132 String invocationId = (String) headers.getFirst(MsoLogger.INVOCATION_ID_HEADER );
133 if(invocationId == null || invocationId.isEmpty())
134 invocationId =UUID.randomUUID().toString();
139 public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
142 Instant instant = Instant.now();
143 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
144 .withLocale( Locale.US )
145 .withZone( ZoneId.systemDefault() );
146 String startTime= MDC.get(MsoLogger.STARTTIME);
149 elapsedTime = System.currentTimeMillis() - Long.parseLong(startTime);
150 }catch(NumberFormatException e){
154 if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
155 statusCode=MsoLogger.COMPLETE;
157 statusCode= MsoLogger.StatusCode.ERROR.toString();
160 MDC.put(MsoLogger.RESPONSEDESC,payloadMessage(responseContext));
161 MDC.put(MsoLogger.STATUSCODE, statusCode);
162 MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus()));
163 MDC.put(MsoLogger.TIMER, String.valueOf(elapsedTime));
164 MDC.put(MsoLogger.ENDTIME,formatter.format(instant));
165 logger.debug(MsoLogger.EXIT, "Exiting.");
166 } catch ( Exception e) {
167 logger.warn("Error in outgoing JAX-RS Inteceptor", e);
171 private String payloadMessage(ContainerResponseContext responseContext) throws IOException {
172 String message = new String();
173 if (responseContext.hasEntity()) {
174 ByteArrayOutputStream baos = new ByteArrayOutputStream();
175 Class<?> entityClass = responseContext.getEntityClass();
176 Type entityType = responseContext.getEntityType();
177 Annotation[] entityAnnotations = responseContext.getEntityAnnotations();
178 MediaType mediaType = responseContext.getMediaType();
179 @SuppressWarnings("unchecked")
180 MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(entityClass,
184 bodyWriter.writeTo(responseContext.getEntity(),
189 responseContext.getHeaders(),
191 message = message.concat(new String(baos.toByteArray()));