summaryrefslogtreecommitdiffstats
path: root/dcaedt_be/src/main/java/org/onap/sdc/dcae/filter/LoggingFilter.java
blob: ba9783a060452a9dff2b73f9b29b64639ee04c40 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package org.onap.sdc.dcae.filter;

import static java.net.HttpURLConnection.*;

import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.impl.EnglishReasonPhraseCatalog;
import org.onap.sdc.common.onaplog.OnapLoggerAudit;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapMDCWrapper;
import org.onap.sdc.common.onaplog.enums.OnapLoggerErrorCode;
import org.onap.sdc.common.onaplog.enums.LogLevel;

public class LoggingFilter implements Filter {

    private static final String SERVICE_NAME = "DCAE-D-BE";

    private OnapMDCWrapper commonLoggerArgs = OnapMDCWrapper.getInstance();
    private OnapLoggerAudit auditLogger = OnapLoggerAudit.getInstance();
    private OnapLoggerDebug onapLoggerDebug = OnapLoggerDebug.getInstance();

    public LoggingFilter() {
        super();
    }


    @Override
    public void destroy() {
        // We have nothing to destroy
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        boolean shouldLogRequest = true;

        try {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                if ("/healthCheck".equals(httpRequest.getServletPath())) {
                    shouldLogRequest = false;
                }

                if (shouldLogRequest) {
                    beforeHandle(httpRequest);
                }
            }
        } catch (Exception e) {
            onapLoggerDebug.log(LogLevel.DEBUG,this.getClass().getName(),"Exception:{}",e);
        }

        filterChain.doFilter(request, response); // handle request

        try {
            if (response instanceof HttpServletResponse && shouldLogRequest) {
                afterHandle((HttpServletResponse) response);
            }
        } catch (Exception e) {
            onapLoggerDebug.log(LogLevel.DEBUG,this.getClass().getName(),"Exception:{}",e);
        }
    }


    private void beforeHandle(HttpServletRequest request) {
        String requestId = getRequestId(request);
        request.setAttribute("requestId", requestId); // making requestId available for the API controllers
        commonLoggerArgs
            .clear()
            .startTimer()
            .setRemoteHost(request.getRemoteAddr())
            .setServiceName(SERVICE_NAME)
            .setPartnerName(getPartnerName(request.getHeader("USER_ID"), request.getHeader("user-agent")))
            .setKeyRequestId(requestId)
            .setAutoServerIPAddress(request.getLocalAddr())
            .setOptCustomField1(request.getProtocol())
            .setOptCustomField2(request.getMethod())
            .setOptCustomField3(request.getServletPath());

    }


    private static String getRequestId(HttpServletRequest request) {
        String requestId = request.getHeader("X-ECOMP-RequestID");
        return isNullOrEmpty(requestId)
            ? UUID.randomUUID().toString()
            : requestId;
    }


    private void afterHandle(HttpServletResponse response) {
        String responseDesc = EnglishReasonPhraseCatalog.INSTANCE.getReason(response.getStatus(), Locale.ENGLISH);
        commonLoggerArgs
            .stopTimer()
            .setResponseCode(getLoggingErrorCode(response.getStatus()).getErrorCode())
            .setResponseDesc(responseDesc)
            .setOptCustomField4(Integer.toString(response.getStatus()));

        auditLogger
            .setStatusCode(Integer.toString(response.getStatus()))
            .log(LogLevel.INFO, this.getClass().getName(), responseDesc);
    }


    private OnapLoggerErrorCode getLoggingErrorCode(int httpResponseCode) {
        if (isSuccessError(httpResponseCode)) {
            return OnapLoggerErrorCode.SUCCESS;
        }
        else if (isSchemaError(httpResponseCode)) {
            return OnapLoggerErrorCode.SCHEMA_ERROR;
        }
        else if (isDataError(httpResponseCode)) {
            return OnapLoggerErrorCode.DATA_ERROR;
        }
        else if (isPermissionsError(httpResponseCode)) {
            return OnapLoggerErrorCode.PERMISSION_ERROR;
        }
        else if (isTimeoutOrAvailabilityError(httpResponseCode)) {
            return OnapLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR;
        }
        else if (isBusinessProcessError(httpResponseCode)) {
            return OnapLoggerErrorCode.BUSINESS_PROCESS_ERROR;
        }
        else {
            return OnapLoggerErrorCode.UNKNOWN_ERROR;
        }
    }


    private boolean isTimeoutOrAvailabilityError(int httpResponseCode) {

        switch (httpResponseCode) {
            case HTTP_BAD_REQUEST:
            case HTTP_UNAUTHORIZED:
            case HTTP_NOT_FOUND:
            case HTTP_CLIENT_TIMEOUT:
            case HTTP_GONE:
                return true;
            default:
                return false;
        }
    }

    private boolean isPermissionsError(int httpResponseCode) {

        switch (httpResponseCode) {
            case HTTP_PAYMENT_REQUIRED:
            case HTTP_FORBIDDEN:
            case HTTP_BAD_METHOD:
            case HTTP_PROXY_AUTH:
                return true;
            default:
                return false;
        }
    }

    private boolean isDataError(int httpResponseCode) {

        switch (httpResponseCode) {
            case HTTP_NOT_ACCEPTABLE:
            case HTTP_LENGTH_REQUIRED:
            case HTTP_PRECON_FAILED:
            case HTTP_REQ_TOO_LONG:
            case HTTP_ENTITY_TOO_LARGE:
            case HTTP_UNSUPPORTED_TYPE:
                return true;
            default:
                return false;
        }
    }

    private boolean isSchemaError(int httpResponseCode) {
        return httpResponseCode == HTTP_CONFLICT;
    }

    private boolean isSuccessError(int httpResponseCode) {
        return httpResponseCode < 399;
    }

    private boolean isBusinessProcessError(int httpResponseCode) {
        return httpResponseCode > 499;
    }
    
    private String getPartnerName(String userId, String userAgent) {
        return isNullOrEmpty(userId)
                ? getClientApplication(userAgent)
                : userId;
    }
    
    private String getClientApplication(String userAgent) {
        if (userAgent != null && userAgent.length() > 0) {
            if (userAgent.toLowerCase().contains("firefox")) {
                return "fireFox_FE";
            }

            if (userAgent.toLowerCase().contains("msie")) {
                return "explorer_FE";
            }

            if (userAgent.toLowerCase().contains("chrome")) {
                return "chrome_FE";
            }

            return userAgent;
        }
        return "";
    }

    private static boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }


    @Override
    public void init(FilterConfig config) {
        // We have nothing to do when initializing
    }
}