Merge "fixed sonar issues in NetworkAdaptorNotify_Service"
[so.git] / common / src / main / java / org / onap / so / logging / jaxrs / filter / JaxRsClientLogging.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
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.so.logging.jaxrs.filter;
22
23
24 import org.apache.commons.io.IOUtils;
25 import org.onap.so.logger.MsoLogger;
26 import org.onap.so.utils.TargetEntity;
27 import org.slf4j.MDC;
28 import org.springframework.stereotype.Component;
29
30 import javax.ws.rs.client.ClientRequestContext;
31 import javax.ws.rs.client.ClientRequestFilter;
32 import javax.ws.rs.client.ClientResponseContext;
33 import javax.ws.rs.client.ClientResponseFilter;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response;
36
37 import java.io.*;
38
39 import java.time.Instant;
40 import java.time.ZoneId;
41 import java.time.format.DateTimeFormatter;
42 import java.util.Locale;
43 import java.util.UUID;
44
45 @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
46 @Component
47 public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter {
48         
49         private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,JaxRsClientLogging.class);
50
51         private TargetEntity targetEntity;
52
53         public void setTargetService(TargetEntity targetEntity){
54             this.targetEntity = targetEntity;
55     }
56
57         @Override
58         public void filter(ClientRequestContext clientRequest) {
59         try{
60             MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
61             
62             
63             Instant instant = Instant.now();
64             DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
65                 .withLocale( Locale.US )
66                 .withZone( ZoneId.systemDefault() );
67
68             String requestId = MDC.get(MsoLogger.REQUEST_ID);
69             if(requestId == null || requestId.isEmpty()){
70                 requestId = UUID.randomUUID().toString();
71                 logger.warnSimple(clientRequest.getUri().getPath(),"Could not Find Request ID Generating New One");
72             }
73
74                         MDC.put(MsoLogger.METRIC_BEGIN_TIME, formatter.format(instant));
75                         MDC.put(MsoLogger.METRIC_START_TIME, String.valueOf(System.currentTimeMillis()));
76             MDC.put(MsoLogger.REQUEST_ID,requestId);    
77             MDC.put(MsoLogger.TARGETSERVICENAME, clientRequest.getUri().toString());
78         } catch (Exception e) {
79                         logger.warnSimple("Error in incoming JAX-RS Inteceptor", e);
80                 }
81         }       
82
83
84         @Override
85         public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
86
87         try {
88                         Instant instant = Instant.now();
89                         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
90                                 .withLocale( Locale.US )
91                                 .withZone( ZoneId.systemDefault() );
92                         String startTime= MDC.get(MsoLogger.METRIC_START_TIME);
93
94                         long elapsedTime = System.currentTimeMillis()-Long.parseLong(startTime);
95                         String statusCode;
96                         if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){             
97                             statusCode=MsoLogger.COMPLETE;
98                         }else{                                                  
99                                 statusCode=MsoLogger.StatusCode.ERROR.toString();                               
100                         }
101                         MultivaluedMap<String, String> headers = responseContext.getHeaders();
102
103                         String partnerName =  headers.getFirst(MsoLogger.HEADER_FROM_APP_ID );
104                         if(partnerName == null || partnerName.isEmpty())
105                                 partnerName="UNKNOWN";
106                         MDC.put(MsoLogger.RESPONSEDESC,getStringFromInputStream(responseContext));
107                         MDC.put(MsoLogger.STATUSCODE, statusCode);
108                         MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus()));
109                         MDC.put(MsoLogger.METRIC_TIMER, String.valueOf(elapsedTime));
110                         MDC.put(MsoLogger.METRIC_END_TIME,formatter.format(instant));
111                         MDC.put(MsoLogger.PARTNERNAME,partnerName);     
112             MDC.put(MsoLogger.TARGETENTITY, targetEntity.toString());
113                         logger.recordMetricEvent();                     
114                 } catch ( Exception e) {
115                         logger.warnSimple("Error in outgoing JAX-RS Inteceptor", e);
116                 }
117         }
118
119     private static String getStringFromInputStream(ClientResponseContext clientResponseContext) {
120
121             InputStream is = clientResponseContext.getEntityStream();
122             ByteArrayOutputStream boas = new ByteArrayOutputStream();
123
124         try {
125             IOUtils.copy(is,boas);
126             InputStream copiedStream = new ByteArrayInputStream(boas.toByteArray());
127             clientResponseContext.setEntityStream(copiedStream);
128             return boas.toString();
129
130         } catch (IOException e) {
131             logger.warnSimple("Failed to read response body", e);
132         }
133         return "Unable to read input stream";
134     }
135 }