aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java
blob: fbe28a79eb1aa1227b549122e257513571dbda6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
 * Copyright © 2016-2018 European Support Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openecomp.sdc.logging.servlet.jaxrs;

import static org.openecomp.sdc.logging.api.StatusCode.COMPLETE;
import static org.openecomp.sdc.logging.api.StatusCode.ERROR;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.openecomp.sdc.logging.api.AuditData;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.logging.api.LoggingContext;
import org.openecomp.sdc.logging.api.StatusCode;

/**
 * <p>Takes care of logging when an HTTP request leaves the application. This includes writing to audit and clearing
 * logging context. This filter <b>only works properly in tandem</b> with {@link LoggingRequestFilter} or a similar
 * implementation.</p>
 * <p>Sample configuration for a Spring environment:</p>
 * <pre>
 *     &lt;jaxrs:providers&gt;
 *         &lt;bean class="org.openecomp.sdc.logging.ws.rs.LoggingResponseFilter"/&gt;
 *     &lt;/jaxrs:providers&gt;
 * </pre>
 * <p><i>It is highly recommended to configure a custom JAX-RS exception mapper so that this filter will not be bypassed
 * due to unhandled application or container exceptions.</i></p>
 *
 * @author evitaliy
 * @since 29 Oct 17
 *
 * @see ContainerResponseFilter
 */
@Provider
public class LoggingResponseFilter implements ContainerResponseFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Tracks reporting configuration problems to the log. We want to report them only once, and not to write to log
     * upon every request, as the configuration will not change in runtime.
     */
    private boolean reportBadConfiguration = true;

    private HttpServletRequest httpRequest;

    /**
     * Injection of HTTP request object from JAX-RS context.
     *
     * @param httpRequest automatically injected by JAX-RS container
     */
    @Context
    public void setHttpRequest(HttpServletRequest httpRequest) {
        this.httpRequest = httpRequest;
    }

    @Override
    public void filter(ContainerRequestContext containerRequestContext,
            ContainerResponseContext containerResponseContext) {

        try {
            writeAudit(containerRequestContext, containerResponseContext);
        } finally {
            LoggingContext.clear();
        }
    }

    private void writeAudit(ContainerRequestContext containerRequestContext,
            ContainerResponseContext containerResponseContext) {

        if (!logger.isAuditEnabled()) {
            return;
        }

        long start = readStartTime(containerRequestContext);
        long end = System.currentTimeMillis();

        Response.StatusType statusInfo = containerResponseContext.getStatusInfo();
        int responseCode = statusInfo.getStatusCode();
        StatusCode statusCode = isSuccess(responseCode) ? COMPLETE : ERROR;

        AuditData auditData = AuditData.builder().startTime(start).endTime(end).statusCode(statusCode)
                                       .responseCode(Integer.toString(responseCode))
                                       .responseDescription(statusInfo.getReasonPhrase())
                                       .clientIpAddress(httpRequest.getRemoteAddr()).build();
        logger.audit(auditData);
    }

    private boolean isSuccess(int responseCode) {
        return responseCode > 199 && responseCode < 400;
    }

    private long readStartTime(ContainerRequestContext containerRequestContext) {

        Object startTime = containerRequestContext.getProperty(LoggingRequestFilter.START_TIME_KEY);
        if (startTime == null) {
            return handleMissingStartTime();
        }

        return parseStartTime(startTime);
    }

    private long handleMissingStartTime() {
        reportConfigProblem("{} key was not found in JAX-RS request context. "
                + "Make sure you configured a request filter", LoggingRequestFilter.START_TIME_KEY);
        return 0;
    }

    private long parseStartTime(Object startTime) {

        try {
            return Long.class.cast(startTime);
        } catch (ClassCastException e) {
            reportConfigProblem("{} key in JAX-RS request context contains an object of type '{}', but 'java.lang.Long'"
                    + " is expected", LoggingRequestFilter.START_TIME_KEY, startTime.getClass().getName());
            return 0;
        }
    }

    private void reportConfigProblem(String message, Object... arguments) {

        if (reportBadConfiguration) {
            reportBadConfiguration = false;
            logger.error(message, arguments);
        }
    }
}