re base code
[sdc.git] / openecomp-be / lib / openecomp-sdc-logging-lib / openecomp-sdc-logging-api / src / main / java / org / openecomp / sdc / logging / servlet / jaxrs / LoggingResponseFilter.java
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 org.openecomp.sdc.logging.api.*;
20
21 import javax.servlet.http.HttpServletRequest;
22 import javax.ws.rs.container.ContainerRequestContext;
23 import javax.ws.rs.container.ContainerResponseContext;
24 import javax.ws.rs.container.ContainerResponseFilter;
25 import javax.ws.rs.container.ResourceInfo;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.Response;
28 import javax.ws.rs.ext.Provider;
29
30 import static org.openecomp.sdc.logging.api.StatusCode.COMPLETE;
31 import static org.openecomp.sdc.logging.api.StatusCode.ERROR;
32
33 /**
34  * <p>Takes care of logging when an HTTP request leaves the application. This includes writing to audit and clearing
35  * logging context. This filter <b>only works properly in tandem</b> with {@link LoggingRequestFilter} or a similar
36  * implementation.</p>
37  * <p>Sample configuration for a Spring environment:</p>
38  * <pre>
39  *     &lt;jaxrs:providers&gt;
40  *         &lt;bean class="org.openecomp.sdc.logging.ws.rs.LoggingResponseFilter"/&gt;
41  *     &lt;/jaxrs:providers&gt;
42  * </pre>
43  * <p><i>It is highly recommended to configure a custom JAX-RS exception mapper so that this filter will not be bypassed
44  * due to unhandled application or container exceptions.</i></p>
45  *
46  * @author evitaliy
47  * @since 29 Oct 17
48  *
49  * @see ContainerResponseFilter
50  */
51 @Provider
52 public class LoggingResponseFilter implements ContainerResponseFilter {
53
54     private static final int UNKNOWN_START_TIME = 0;
55
56     private static final Logger LOGGER = LoggerFactory.getLogger(LoggingResponseFilter.class);
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     private ResourceInfo resource;
67
68     /**
69      * Injection of HTTP request object from JAX-RS context.
70      *
71      * @param httpRequest automatically injected by JAX-RS container
72      */
73     @Context
74     public void setHttpRequest(HttpServletRequest httpRequest) {
75         this.httpRequest = httpRequest;
76     }
77
78     /**
79      * Injection of a resource that matches the request from JAX-RS context.
80      *
81      * @param resource automatically injected by JAX-RS container
82      */
83     @Context
84     public void setResource(ResourceInfo resource) {
85         this.resource = resource;
86     }
87
88     @Override
89     public void filter(ContainerRequestContext containerRequestContext,
90             ContainerResponseContext containerResponseContext) {
91
92         try {
93
94             if ((resource == null) || (resource.getResourceClass() == null)) {
95                 LOGGER.debug("No matching resource, skipping audit.");
96                 return;
97             }
98
99             writeAudit(containerRequestContext, containerResponseContext);
100
101         } finally {
102             LoggingContext.clear();
103         }
104     }
105
106     private void writeAudit(ContainerRequestContext containerRequestContext,
107             ContainerResponseContext containerResponseContext) {
108
109         Logger resourceLogger = LoggerFactory.getLogger(resource.getResourceMethod().getDeclaringClass());
110         if (!resourceLogger.isAuditEnabled()) {
111             return;
112         }
113
114         long start = readStartTime(containerRequestContext);
115         long end = System.currentTimeMillis();
116
117         Response.StatusType statusInfo = containerResponseContext.getStatusInfo();
118         int responseCode = statusInfo.getStatusCode();
119         StatusCode statusCode = isSuccess(responseCode) ? COMPLETE : ERROR;
120
121         AuditData auditData = AuditData.builder().startTime(start).endTime(end).statusCode(statusCode)
122                                        .responseCode(Integer.toString(responseCode))
123                                        .responseDescription(statusInfo.getReasonPhrase())
124                                        .clientIpAddress(httpRequest.getRemoteAddr()).build();
125         resourceLogger.audit(auditData);
126     }
127
128     private boolean isSuccess(int responseCode) {
129         return responseCode > 199 && responseCode < 400;
130     }
131
132     private long readStartTime(ContainerRequestContext containerRequestContext) {
133
134         Object startTime = containerRequestContext.getProperty(LoggingRequestFilter.START_TIME_KEY);
135         if (startTime == null) {
136             return handleMissingStartTime();
137         }
138
139         return parseStartTime(startTime);
140     }
141
142     private long handleMissingStartTime() {
143         reportConfigProblem("{} key was not found in JAX-RS request context. "
144                 + "Make sure you configured a request filter", LoggingRequestFilter.START_TIME_KEY);
145         return UNKNOWN_START_TIME;
146     }
147
148     private long parseStartTime(Object startTime) {
149
150         try {
151             return Long.class.cast(startTime);
152         } catch (ClassCastException e) {
153             reportConfigProblem("{} key in JAX-RS request context contains an object of type '{}', but 'java.lang.Long'"
154                     + " is expected", LoggingRequestFilter.START_TIME_KEY, startTime.getClass().getName(), e);
155             return 0;
156         }
157     }
158
159     private void reportConfigProblem(String message, Object... arguments) {
160
161         if (reportBadConfiguration) {
162             reportBadConfiguration = false;
163             LOGGER.error(message, arguments);
164         }
165     }
166 }
167