summaryrefslogtreecommitdiffstats
path: root/security-util-lib/src/main/java/org/onap/sdc/security/logging/wrappers/LoggerSdcUtilBase.java
blob: b61259bd2b9706d859284b2a36ecdd96b53edf4d (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
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.sdc.security.logging.wrappers;

import org.apache.commons.lang3.StringUtils;
import org.onap.sdc.security.logging.enums.EcompLoggerErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.container.ContainerRequestContext;
import java.util.List;
import java.util.StringTokenizer;

import static java.net.HttpURLConnection.*;


public class LoggerSdcUtilBase {

    protected static Logger log = LoggerFactory.getLogger(LoggerSdcUtilBase.class.getName());

    String getRequestIDfromHeaders(List<Object> requestHeader) {
        // this method gets list of type object.
        // toString method returns the RequestId with brackets.
        String requestHeaderString = requestHeader.toString();
        return requestHeaderString.replace("[","").replace("]","");
    }



    // this method translates http error code to ECOMP Logger Error code
    // this is a naive translation and is not a result of any documented format ECOMP specification
    protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) {
        if (isSuccessError(httpResponseCode)) {
            return EcompLoggerErrorCode.SUCCESS;
        }

        if (isSchemaError(httpResponseCode)) {
            return EcompLoggerErrorCode.SCHEMA_ERROR;
        }
        if (isDataError(httpResponseCode)) {
            return EcompLoggerErrorCode.DATA_ERROR;
        }
        if (isPermissionsError(httpResponseCode)) {
            return EcompLoggerErrorCode.PERMISSION_ERROR;
        }
        if (isTimeoutOrAvailabilityError(httpResponseCode)) {
            return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR;
        }
        if (isBusinessProcessError(httpResponseCode)) {
            return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
        }
        return EcompLoggerErrorCode.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;
        }

        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;
        }

        return false;
    }

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

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

    private boolean isBusinessProcessError(int httpResponseCode) {
        return httpResponseCode > 499;
    }

    protected String getPartnerName(String userAgent, String userId, String url, String xOnapPartnerName) {

        //On called side (receiver) If the API call is authenticated, then log the userid/mechid (fully qualified if that is what was provided)
        if (isFound(userId)) {
            return userId;
        }

        String urlUser = getUserIdFromUrl(url);
        if (isFound(urlUser)) {
            return urlUser;
        }

        //Otherwise, if X-ONAP-PartnerName was provided, then log that
        if (isFound(xOnapPartnerName)){
            return xOnapPartnerName;
        }

        //Otherwise, for an HTTP API call, log the part of the URI specifying the agent that the caller used to make the call
        String userAgentName = getUserIdFromUserAgent(userAgent);
        if (isFound(userAgentName)) {
            return userAgentName;
        }

        return "UNKNOWN";
    }

    private String getUserIdFromUserAgent(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 null;
    }

    private String getUserIdFromUrl(String url) {
        if (url != null && url.toLowerCase().contains("user")) {
            StringTokenizer st = new StringTokenizer(url, "/");
            while (st.hasMoreElements()) {
                if ("user".equalsIgnoreCase(st.nextToken())) {
                    return st.nextToken();
                }
            }
        }
        return null;
    }

    protected String getUrl(ContainerRequestContext requestContext) {
        String url = "";

        try {
            if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) {
                url = requestContext.getUriInfo().getRequestUri().toURL().toString();
            }
        } catch (Exception ex) {
            log.error("failed to get url from request context ", ex);
        }

        return url;
    }

    protected String getServiceName(ContainerRequestContext requestContext) {
        return (requestContext.getUriInfo().getRequestUri().toString())
                .replace(requestContext.getUriInfo().getBaseUri().toString(), "/");
    }

    private boolean isFound(String value) {
        if (StringUtils.isNotEmpty(value)) {
            return true;
        }
        return false;
    }
}