fbe28a79eb1aa1227b549122e257513571dbda6b
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.logging.servlet.jaxrs;
18
19 import static org.openecomp.sdc.logging.api.StatusCode.COMPLETE;
20 import static org.openecomp.sdc.logging.api.StatusCode.ERROR;
21
22 import javax.servlet.http.HttpServletRequest;
23 import javax.ws.rs.container.ContainerRequestContext;
24 import javax.ws.rs.container.ContainerResponseContext;
25 import javax.ws.rs.container.ContainerResponseFilter;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.Response;
28 import javax.ws.rs.ext.Provider;
29 import org.openecomp.sdc.logging.api.AuditData;
30 import org.openecomp.sdc.logging.api.Logger;
31 import org.openecomp.sdc.logging.api.LoggerFactory;
32 import org.openecomp.sdc.logging.api.LoggingContext;
33 import org.openecomp.sdc.logging.api.StatusCode;
34
35 /**
36  * <p>Takes care of logging when an HTTP request leaves the application. This includes writing to audit and clearing
37  * logging context. This filter <b>only works properly in tandem</b> with {@link LoggingRequestFilter} or a similar
38  * implementation.</p>
39  * <p>Sample configuration for a Spring environment:</p>
40  * <pre>
41  *     &lt;jaxrs:providers&gt;
42  *         &lt;bean class="org.openecomp.sdc.logging.ws.rs.LoggingResponseFilter"/&gt;
43  *     &lt;/jaxrs:providers&gt;
44  * </pre>
45  * <p><i>It is highly recommended to configure a custom JAX-RS exception mapper so that this filter will not be bypassed
46  * due to unhandled application or container exceptions.</i></p>
47  *
48  * @author evitaliy
49  * @since 29 Oct 17
50  *
51  * @see ContainerResponseFilter
52  */
53 @Provider
54 public class LoggingResponseFilter implements ContainerResponseFilter {
55
56     private final Logger logger = LoggerFactory.getLogger(this.getClass());
57
58     /**
59      * Tracks reporting configuration problems to the log. We want to report them only once, and not to write to log
60      * upon every request, as the configuration will not change in runtime.
61      */
62     private boolean reportBadConfiguration = true;
63
64     private HttpServletRequest httpRequest;
65
66     /**
67      * Injection of HTTP request object from JAX-RS context.
68      *
69      * @param httpRequest automatically injected by JAX-RS container
70      */
71     @Context
72     public void setHttpRequest(HttpServletRequest httpRequest) {
73         this.httpRequest = httpRequest;
74     }
75
76     @Override
77     public void filter(ContainerRequestContext containerRequestContext,
78             ContainerResponseContext containerResponseContext) {
79
80         try {
81             writeAudit(containerRequestContext, containerResponseContext);
82         } finally {
83             LoggingContext.clear();
84         }
85     }
86
87     private void writeAudit(ContainerRequestContext containerRequestContext,
88             ContainerResponseContext containerResponseContext) {
89
90         if (!logger.isAuditEnabled()) {
91             return;
92         }
93
94         long start = readStartTime(containerRequestContext);
95         long end = System.currentTimeMillis();
96
97         Response.StatusType statusInfo = containerResponseContext.getStatusInfo();
98         int responseCode = statusInfo.getStatusCode();
99         StatusCode statusCode = isSuccess(responseCode) ? COMPLETE : ERROR;
100
101         AuditData auditData = AuditData.builder().startTime(start).endTime(end).statusCode(statusCode)
102                                        .responseCode(Integer.toString(responseCode))
103                                        .responseDescription(statusInfo.getReasonPhrase())
104                                        .clientIpAddress(httpRequest.getRemoteAddr()).build();
105         logger.audit(auditData);
106     }
107
108     private boolean isSuccess(int responseCode) {
109         return responseCode > 199 && responseCode < 400;
110     }
111
112     private long readStartTime(ContainerRequestContext containerRequestContext) {
113
114         Object startTime = containerRequestContext.getProperty(LoggingRequestFilter.START_TIME_KEY);
115         if (startTime == null) {
116             return handleMissingStartTime();
117         }
118
119         return parseStartTime(startTime);
120     }
121
122     private long handleMissingStartTime() {
123         reportConfigProblem("{} key was not found in JAX-RS request context. "
124                 + "Make sure you configured a request filter", LoggingRequestFilter.START_TIME_KEY);
125         return 0;
126     }
127
128     private long parseStartTime(Object startTime) {
129
130         try {
131             return Long.class.cast(startTime);
132         } catch (ClassCastException e) {
133             reportConfigProblem("{} key in JAX-RS request context contains an object of type '{}', but 'java.lang.Long'"
134                     + " is expected", LoggingRequestFilter.START_TIME_KEY, startTime.getClass().getName());
135             return 0;
136         }
137     }
138
139     private void reportConfigProblem(String message, Object... arguments) {
140
141         if (reportBadConfiguration) {
142             reportBadConfiguration = false;
143             logger.error(message, arguments);
144         }
145     }
146 }
147