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