re base code
[sdc.git] / common / onap-sdc-artifact-generator-lib / onap-sdc-artifact-generator-core / src / main / java / org / onap / sdc / generator / util / ArtifactGeneratorUtil.java
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.onap.sdc.generator.util;
22
23 import org.onap.sdc.generator.data.Artifact;
24 import org.onap.sdc.generator.logging.ArtifactGeneratorLogResponseCode;
25 import org.onap.sdc.generator.logging.CategoryLogLevel;
26 import org.onap.sdc.generator.logging.StatusCode;
27 import org.openecomp.sdc.logging.api.Logger;
28 import org.openecomp.sdc.logging.api.LoggerFactory;
29 import org.slf4j.MDC;
30
31 import java.io.PrintWriter;
32 import java.io.StringWriter;
33 import java.net.InetAddress;
34 import java.net.UnknownHostException;
35 import java.text.DateFormat;
36 import java.text.SimpleDateFormat;
37 import java.util.Date;
38 import java.util.TimeZone;
39
40 import static org.onap.sdc.generator.data.GeneratorConstants.*;
41 import static org.onap.sdc.generator.logging.ArtifactGeneratorLogResponseCode.*;
42
43
44 public class ArtifactGeneratorUtil {
45
46   private static Logger log = LoggerFactory.getLogger(ArtifactGeneratorUtil.class.getName());
47   private static final String LOG_UTC_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
48
49   /**
50    * Artifact Generator Error logging Helper.
51    * @param errorDescription Description of the error
52    */
53   public static void logError(String errorDescription) {
54     logError(errorDescription, "");
55   }
56
57   /**
58    * Artifact Generator Error logging Helper.
59    * @param errorDescription Description of the error
60    * @param ex Exception object for stackstrace
61    */
62   public static void logError(String errorDescription, Exception ex) {
63     StringWriter sw = new StringWriter();
64     ex.printStackTrace(new PrintWriter(sw));
65     String detailMessage = sw.toString();
66     logError(CategoryLogLevel.ERROR, errorDescription, detailMessage);
67   }
68
69   /**
70    * Artifact Generator Error logging Helper.
71    * @param errorDescription Description of the error
72    * @param detailMessage Detailed Error message
73    */
74   public static void logError(String errorDescription, String detailMessage) {
75     logError(CategoryLogLevel.ERROR, errorDescription, detailMessage);
76   }
77
78   /**
79    * Artifact Generator Error logging Helper.
80    * @param errorCategory    ERROR
81    * @param errorDescription Description of the error
82    * @param detailMessage Detailed Error message
83    */
84   public static void logError(CategoryLogLevel errorCategory,
85                               String errorDescription, String detailMessage) {
86     MDC.put(ERROR_CATEGORY, errorCategory.name());
87     MDC.put(STATUS_CODE, StatusCode.ERROR.name());
88     artifactGeneratorErrorLogProcessor(errorCategory,errorDescription);
89     log.error(detailMessage);
90     resetLoggingContext();
91   }
92
93   /**
94    * Initialize generic MDC attributes for logging the current request.
95    *
96    */
97   public static void initializeLoggingContext() {
98     log.debug("Initializing generic logging context ");
99     MDC.put(PARTNER_NAME, GENERATOR_PARTNER_NAME);
100     MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
101     MDC.put(INSTANCE_UUID, MDC_SDC_INSTANCE_UUID);
102     MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
103     MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));
104
105     try {
106       InetAddress ip = InetAddress.getLocalHost();
107       MDC.put(LOCAL_ADDR, ip.getHostAddress());
108       String hostname = ip.getHostName();
109       MDC.put(BE_FQDN, hostname);
110     } catch (UnknownHostException uhe) {
111       log.error("Failed to get server FQDN", uhe);
112     }
113
114     if (log.isDebugEnabled()) {
115       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
116     } else if (log.isInfoEnabled()) {
117       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
118     } else if (log.isWarnEnabled()) {
119       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
120     } else if (log.isErrorEnabled()) {
121       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
122     }
123   }
124
125   /**
126    * Initialize MDC for logging the current artifact request.
127    *
128    * @param artifact Current artifact
129    */
130   public static void initializeArtifactLoggingContext(Artifact artifact) {
131     log.debug("Initializing logging context for " + artifact.getLabel());
132     MDC.put(REQUEST_ID, artifact.getLabel());
133     MDC.put(SERVICE_NAME, artifact.getType());
134     MDC.put(SERVICE_INSTANCE_ID, artifact.getName());
135   }
136
137   /**
138    * Reset the logging context after a Audit/Metrics logging operation.
139    */
140   public static void resetLoggingContext() {
141     MDC.remove(ERROR_CATEGORY);
142     MDC.remove(ERROR_CODE);
143     MDC.remove(STATUS_CODE);
144     MDC.remove(ERROR_DESCRIPTION);
145     MDC.remove(BEGIN_TIMESTAMP);
146     MDC.remove(END_TIMESTAMP);
147     MDC.remove(ELAPSED_TIME);
148     MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
149     MDC.remove(RESPONSE_CODE);
150     MDC.remove(RESPONSE_DESCRIPTION);
151     MDC.remove(TARGET_ENTITY);
152     MDC.remove(TARGET_SERVICE_NAME);
153   }
154
155   /**
156    * Convert timestamp to UTC format date string.
157    *
158    * @param timeStamp UTC timestamp to be converted to the UTC Date format.
159    * @return UTC formatted Date string from timestamp.
160    */
161   public static String getLogUtcDateStringFromTimestamp(Date timeStamp) {
162     DateFormat df = new SimpleDateFormat(LOG_UTC_DATE_FORMAT);
163     df.setTimeZone(TimeZone.getTimeZone("GMT"));
164     return df.format(timeStamp);
165   }
166
167   /**
168    * Artifact Gnenerator Error logging Helper.
169    *
170    * @param errorCategory    WARN or ERROR.
171    * @param errorDescription Description of the error.
172    */
173   public static void artifactGeneratorErrorLogProcessor(CategoryLogLevel errorCategory,
174                                                         String errorDescription) {
175     MDC.put(ERROR_CATEGORY, errorCategory.name());
176     if (errorDescription != null) {
177       String errorType = "";
178       switch (errorCategory) {
179         case WARN:
180           errorType = "W";
181           break;
182         case ERROR:
183           errorType = "E";
184           break;
185         case FATAL:
186           errorType = "F";
187           break;
188         default:
189           break;
190       }
191       MDC.put(ERROR_CODE, getLogResponseCode(errorDescription) + errorType);
192     }
193     MDC.put(ERROR_DESCRIPTION, errorDescription);
194   }
195
196
197   /**
198    *
199    * @return Audit log code corresponding to the Artifact Generator exception.
200    */
201   public static int getLogResponseCode(String errorDescription) {
202     ArtifactGeneratorLogResponseCode responseCode = INTERNAL_SERVER_ERROR;
203     if (errorDescription.contains(GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION_MSG)) {
204       responseCode = MANDATORY_ATTRIBUTE_MISSING;
205     } else if (errorDescription.contains(GENERATOR_AAI_ERROR_INVALID_TOSCA_MSG)) {
206       responseCode = INVALID_TOSCA_YAML;
207     } else if (errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA_MSG)) {
208       responseCode = SERVICE_TOSCA_MISSING;
209     } else if (errorDescription.contains(GENERATOR_ERROR_INVALID_CLIENT_CONFIGURATION_MSG)) {
210       responseCode = INVALID_CLIENT_CONFIGURATION;
211     } else if (errorDescription.contains(GENERATOR_ERROR_ARTIFACT_GENERATION_FAILED_MSG)) {
212       responseCode = UNABLE_TO_GENERATE_ARTIFACT;
213     } else if (errorDescription.contains(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND.split("%s")[0])) {
214       responseCode = MISSING_SYSTME_PROPERY_CONFIGURATION;
215     } else if (errorDescription.contains(GENERATOR_AAI_CONFIGFILE_NOT_FOUND.split("%s")[0])) {
216       responseCode = MISSING_CONFIG_PROPERTIES_FILE;
217     } else if (errorDescription.contains(GENERATOR_AAI_CONFIGLPROP_NOT_FOUND.split("%s")[0])) {
218       responseCode = MISSING_WIDGET_CONFIGURATION;
219     } else if (errorDescription.contains(GENERATOR_AAI_ERROR_INVALID_ID.split("%s")[0])) {
220       responseCode = INVALID_ID_VALUE;
221     } else if (errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_RESOURCE_TOSCA.split("%s")[0]))
222       {
223          responseCode = RESOURCE_TOSCA_MISSING;
224     } else if(errorDescription.contains(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION)) {
225       responseCode = MISSING_SERVICE_VERSION;
226     } else if(errorDescription.contains(GENERATOR_AAI_INVALID_SERVICE_VERSION))
227     {
228       responseCode = INVALID_SERVICE_VERSION;
229     } else if(errorDescription.contains(GENERATOR_AAI_ERROR_NULL_RESOURCE_VERSION_IN_SERVICE_TOSCA.
230         split("%s")[0])) {
231       responseCode = MISSING_RESOURCE_VERSION;
232     } else if(errorDescription.contains(
233         GENERATOR_AAI_ERROR_INVALID_RESOURCE_VERSION_IN_SERVICE_TOSCA.split("%s")[0])) {
234       responseCode = INVALID_RESOURCE_VERSION;
235     } else if(errorDescription.contains(GENERATOR_AAI_PROVIDING_SERVICE_MISSING.split("%s")[0])) {
236       responseCode = MISSING_PRO_SERVICE;
237     } else if(errorDescription.contains(
238         GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING.split("%s")[0])) {
239       responseCode = MISSING_PRO_SERVICE_METADATA;
240     }
241     return responseCode.getValue();
242   }
243 }