28195b334ff6b6046e90f5dd22d0b4fa2b151e1c
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.action.util;
22
23 import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
24 import org.openecomp.sdc.action.logging.CategoryLogLevel;
25 import org.openecomp.sdc.action.types.ActionLogResponseCode;
26 import org.openecomp.sdc.action.types.ActionSubOperation;
27 import org.slf4j.MDC;
28
29 import java.text.DateFormat;
30 import java.text.SimpleDateFormat;
31 import java.time.ZoneOffset;
32 import java.util.*;
33 import java.util.function.LongSupplier;
34
35 import static org.openecomp.sdc.action.ActionConstants.*;
36 import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
37 import static org.openecomp.sdc.action.types.ActionLogResponseCode.*;
38
39 public class ActionUtil {
40
41     private static final String UTC_DATE_FORMAT = "dd MMM yyyy kk:mm:ss z";
42     private static final String LOG_UTC_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
43     private static final ActionLogResponseCode defaultResponseCode = INTERNAL_SERVER_ERROR;
44     private static final Map<String, ActionLogResponseCode> errorCodeMap = initErrorCodeMap();
45     private static final EnumMap<CategoryLogLevel, String> errorTypeMap = initErrorTypeMap();
46
47     private static Map<String, ActionLogResponseCode> initErrorCodeMap() {
48         Map<String, ActionLogResponseCode> map = new HashMap<>();
49         map.put(ACTION_REQUEST_INVALID_GENERIC_CODE, INVALID_REQUEST_PARAM);
50         map.put(ACTION_AUTHENTICATION_ERR_CODE, INTERNAL_SERVER_ERROR);
51         map.put(ACTION_AUTHORIZATION_ERR_CODE, MISSING_AUTHORIZATION);
52         map.put(ACTION_INVALID_INSTANCE_ID_CODE, MISSING_INSTANCE_ID_HEADER);
53         map.put(ACTION_INVALID_REQUEST_ID_CODE, MISSING_REQUEST_ID_HEADER);
54         map.put(ACTION_INVALID_PARAM_CODE, INVALID_REQUEST_PARAM);
55         map.put(ACTION_INVALID_REQUEST_BODY_CODE, MISSING_REQUEST_BODY);
56         map.put(ACTION_UPDATE_NOT_ALLOWED_CODE_NAME, ACTION_NAME_UPDATE_NOT_ALLOWED);
57         map.put(ACTION_CHECKOUT_ON_LOCKED_ENTITY, CHECKOUT_ON_LOCKED_ENTITY);
58         map.put(ACTION_ENTITY_UNIQUE_VALUE_ERROR, ACTION_NAME_ALREADY_EXISTS);
59         map.put(ACTION_INVALID_SEARCH_CRITERIA, INVALID_SEARCH_FILTER_CRITERIA);
60         map.put(ACTION_MULT_SEARCH_CRITERIA, MULTIPLE_FILTER_CRITERIA_NOT_SUPPORTED);
61         map.put(ACTION_UPDATE_ON_UNLOCKED_ENTITY, UPDATE_ON_UNLOCKED_ENTITY);
62         map.put(ACTION_UPDATE_INVALID_VERSION, INVALID_REQUESTED_VERSION);
63         map.put(ACTION_UPDATE_NOT_ALLOWED_CODE, UPDATE_NOT_ALLOWED);
64         map.put(ACTION_CHECKIN_ON_UNLOCKED_ENTITY, CHECKIN_ON_UNLOCKED_ENTITY);
65         map.put(ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED, SUBMIT_ON_FINAL_ENTITY);
66         map.put(ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED, SUBMIT_ON_LOCKED_ENTITY_OTHER_USER);
67         map.put(ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY, UNDO_CHECKOUT_ON_UNLOCKED_ENTITY);
68         map.put(ACTION_NOT_LOCKED_CODE, ACTION_NOT_LOCKED);
69         map.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, CHECKSUM_ERROR);
70         map.put(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ARTIFACT_TOO_BIG);
71         map.put(ACTION_ARTIFACT_ALREADY_EXISTS_CODE, ARTIFACT_ALREADY_EXISTS);
72         map.put(ACTION_ARTIFACT_UPDATE_READ_ONLY, ARTIFACT_UPDATE_READ_ONLY);
73         map.put(ACTION_ARTIFACT_DELETE_READ_ONLY, ARTIFACT_DELETE_READ_ONLY);
74         map.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ARTIFACT_PROTECTION_INVALID);
75         map.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ARTIFACT_NAME_INVALID);
76         map.put(ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER, UPDATE_ON_LOCKED_ENTITY);
77         map.put(ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER, CHECKIN_ON_LOCKED_ENTITY_OTHER_USER);
78         map.put(ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER, CHECKOUT_ON_LOCKED_ENTITY);
79         map.put(ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER, UNDO_CHECKOUT_ON_LOCKED_ENTITY);
80         map.put(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_NOT_FOUND);
81         map.put(ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, ARTIFACT_NOT_FOUND);
82         map.put(ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE, DELETE_ARTIFACT_ON_LOCKED_ENTITY);
83         map.put(ACTION_DELETE_ON_LOCKED_ENTITY_CODE, DELETE_ON_LOCKED_ENTITY_OTHER_USER);
84         map.put(ACTION_INTERNAL_SERVER_ERR_CODE, INTERNAL_SERVER_ERROR);
85         map.put(ACTION_QUERY_FAILURE_CODE, QUERY_FAILURE);
86         return map;
87     }
88
89     private static EnumMap<CategoryLogLevel, String> initErrorTypeMap() {
90         EnumMap<CategoryLogLevel, String> map = new EnumMap<>(CategoryLogLevel.class);
91         map.put(CategoryLogLevel.WARN, "W");
92         map.put(CategoryLogLevel.ERROR, "E");
93         map.put(CategoryLogLevel.FATAL, "F");
94         return map;
95     }
96
97     private ActionUtil() {
98     }
99
100     /**
101      * Get Current Timestamp in UTC format.
102      *
103      * @return Current Timestamp in UTC format
104      */
105     public static Date getCurrentTimeStampUtc() {
106         return Date.from(java.time.ZonedDateTime.now(ZoneOffset.UTC).toInstant());
107     }
108
109     /**
110      * Convert timestamp to UTC format date string.
111      *
112      * @param timeStamp UTC timestamp to be converted to the UTC Date format
113      * @return UTC formatted Date string from timestamp
114      */
115     public static String getUtcDateStringFromTimestamp(Date timeStamp) {
116         DateFormat df = new SimpleDateFormat(UTC_DATE_FORMAT);
117         df.setTimeZone(TimeZone.getTimeZone("GMT"));
118         return df.format(timeStamp);
119     }
120
121     /**
122      * Convert timestamp to UTC format date string.
123      *
124      * @param timeStamp UTC timestamp to be converted to the UTC Date format
125      * @return UTC formatted Date string from timestamp
126      */
127     public static String getLogUtcDateStringFromTimestamp(Date timeStamp) {
128         DateFormat df = new SimpleDateFormat(LOG_UTC_DATE_FORMAT);
129         df.setTimeZone(TimeZone.getTimeZone("GMT"));
130         return df.format(timeStamp);
131     }
132
133     /**
134      * Method to set up specific attributes MDC for the current logging operation.
135      *
136      * @param subOperation Request Name
137      */
138     public static void actionLogPreProcessor(ActionSubOperation subOperation, String targetEntity) {
139         MDC.put(BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
140         if (subOperation != null) {
141             MDC.put(TARGET_SERVICE_NAME, subOperation.name());
142         }
143
144         MDC.put(TARGET_ENTITY, targetEntity);
145     }
146
147     /**
148      * Method to enhance the MDC after the logging operation for Metrics and Audit logs.
149      *
150      * @param statusCode Response code for the current operation
151      */
152     public static void actionLogPostProcessor(ResponseStatus statusCode) {
153         actionLogPostProcessor(statusCode, false);
154     }
155
156     public static void actionLogPostProcessor(ResponseStatus statusCode, boolean isServiceMetricLog) {
157         actionLogPostProcessor(statusCode, null, isServiceMetricLog);
158     }
159
160     public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
161                                               boolean isServiceMetricLog) {
162         actionLogPostProcessor(statusCode, responseCode, null, isServiceMetricLog);
163     }
164
165     /**
166      * Action log post processor.
167      *
168      * @param statusCode          the status code
169      * @param responseCode        the response code
170      * @param responseDescription the response description
171      * @param isServiceMetricLog  the is service metric log
172      */
173     public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
174                                               String responseDescription,
175                                               boolean isServiceMetricLog) {
176         actionLogPostProcessor(statusCode, responseCode, responseDescription, isServiceMetricLog, System::currentTimeMillis);
177     }
178
179     /**
180      * Action log post processor.
181      *
182      * @param statusCode          the status code
183      * @param responseCode        the response code
184      * @param responseDescription the response description
185      * @param isServiceMetricLog  the is service metric log
186      */
187     public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
188                                               String responseDescription,
189                                               boolean isServiceMetricLog,
190                                               LongSupplier getCurrentTime) {
191         MDC.put(STATUS_CODE, statusCode.name());
192         if (responseCode != null) {
193             int logResponseCode = getLogResponseCode(responseCode);
194             MDC.put(RESPONSE_CODE, Integer.toString(logResponseCode));
195         }
196         MDC.put(RESPONSE_DESCRIPTION, responseDescription);
197         long beginTimestamp;
198         if (isServiceMetricLog) {
199             beginTimestamp = Long.parseLong(MDC.get(SERVICE_METRIC_BEGIN_TIMESTAMP));
200         } else {
201             beginTimestamp = Long.parseLong(MDC.get(BEGIN_TIMESTAMP));
202         }
203         long endTimestamp = getCurrentTime.getAsLong();
204         MDC.put(BEGIN_TIMESTAMP, getLogUtcDateStringFromTimestamp(new Date(beginTimestamp)));
205         MDC.put(END_TIMESTAMP, getLogUtcDateStringFromTimestamp(new Date(endTimestamp)));
206         MDC.put(ELAPSED_TIME, String.valueOf(endTimestamp - beginTimestamp));
207     }
208
209     /**
210      * Action Library Error logging Helper.
211      *
212      * @param errorCategory    WARN or ERROR
213      * @param errorCode        Action Library exception code
214      * @param errorDescription Description of the error
215      */
216     public static void actionErrorLogProcessor(CategoryLogLevel errorCategory, String errorCode,
217                                                String errorDescription) {
218         MDC.put(ERROR_CATEGORY, errorCategory.name());
219         if (errorCode != null) {
220             MDC.put(ERROR_CODE, getLogResponseCode(errorCode) + (errorTypeMap.getOrDefault(errorCategory, "")));
221         }
222         MDC.put(ERROR_DESCRIPTION, errorDescription);
223     }
224
225     /**
226      * Method to convert Action Library exception codes to OPENECOMP Audit codes in {@link
227      * ActionLogResponseCode} e.g: ACT1060 --> 201
228      *
229      * @param errorCode Action library exception code
230      * @return Audit log code corresponding to the Action Library exception
231      */
232     public static int getLogResponseCode(String errorCode) {
233         return errorCodeMap.getOrDefault(errorCode, defaultResponseCode).getValue();
234     }
235 }