Enhancements for the aai-common library
[aai/aai-common.git] / aai-els-onap-logging / src / main / java / org / onap / aai / logging / ErrorLogHelper.java
 
 package org.onap.aai.logging;
 
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.apache.commons.lang.StringUtils;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.util.AAIConstants;
+import org.onap.aai.util.MapperUtil;
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.filter.base.MDCSetup;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
 
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 import java.util.Map.Entry;
-import java.util.Properties;
-
-import javax.ws.rs.core.MediaType;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-
-import org.apache.commons.lang.StringUtils;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.LoggingContext.StatusCode;
-import org.onap.aai.util.AAIConfig;
-import org.onap.aai.util.AAIConstants;
-import org.onap.aai.util.MapperUtil;
-import org.slf4j.MDC;
 
 /**
- * 
+ *
  * This classes loads the application error properties file
  * and provides a method that returns an ErrorObject
- * 
+ *
  */
 
 public class ErrorLogHelper {
-
-    private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ErrorLogHelper.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorLogHelper.class);
     private static final HashMap<String, ErrorObject> ERROR_OBJECTS = new HashMap<String, ErrorObject>();
 
     static {
@@ -71,20 +64,23 @@ public class ErrorLogHelper {
 
     /**
      * Load properties.
-     * 
+     * @throws IOException the exception
      * @throws ErrorObjectFormatException
-     * @throws Exception the exception
      */
     public static void loadProperties() throws IOException, ErrorObjectFormatException {
         final String filePath = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "error.properties";
-        final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
+        final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("error.properties");
         final Properties properties = new Properties();
 
-        if (is != null) {
-            properties.load(is);
-        } else {
-            try (final FileInputStream fis = new FileInputStream(filePath)) {
-                properties.load(fis);
+        try (final FileInputStream fis = new FileInputStream(filePath)) {
+            LOGGER.info("Found the error.properties in the following location: {}", AAIConstants.AAI_HOME_ETC_APP_PROPERTIES);
+            properties.load(fis);
+        } catch(Exception ex){
+            LOGGER.info("Unable to find the error.properties from filesystem so using file in jar");
+            if (is != null) {
+                properties.load(is);
+            } else {
+                LOGGER.error("Expected to find the error.properties in the jar but unable to find it");
             }
         }
 
@@ -93,7 +89,7 @@ public class ErrorLogHelper {
             final String value = (String) entry.getValue();
             final String[] errorProperties = value.split(":");
 
-            if (errorProperties.length != 7)
+            if (errorProperties.length < 7)
                 throw new ErrorObjectFormatException();
 
             final ErrorObject errorObject = new ErrorObject();
@@ -105,6 +101,9 @@ public class ErrorLogHelper {
             errorObject.setHTTPResponseCode(errorProperties[4].trim());
             errorObject.setRESTErrorCode(errorProperties[5].trim());
             errorObject.setErrorText(errorProperties[6].trim());
+            if (errorProperties.length > 7) {
+                errorObject.setAaiElsErrorCode(errorProperties[7].trim());
+            }
 
             ERROR_OBJECTS.put(key, errorObject);
         }
@@ -113,10 +112,9 @@ public class ErrorLogHelper {
     /**
      * Logs a known A&AI exception (i.e. one that can be found in error.properties)
      *
-     * @param key The key for the error in the error.properties file
+     * @param code for the error in the error.properties file
      * @throws IOException
      * @throws ErrorObjectNotFoundException
-     * @throws ErrorObjectFormatException
      */
     public static ErrorObject getErrorObject(String code) throws ErrorObjectNotFoundException {
 
@@ -139,12 +137,10 @@ public class ErrorLogHelper {
      * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
      * If no error object is embedded in the AAIException, one will be created using the error object from the
      * AAIException.
-     * 
+     *
      * @param are must have a restError value whose numeric value must match what should be returned in the REST API
      * @param variables optional list of variables to flesh out text in error string
      * @return appropriately formatted JSON response per the REST API spec.
-     * @throws ErrorObjectFormatException
-     * @throws ErrorObjectNotFoundException
      * @throws IOException
      * @deprecated
      */
@@ -166,9 +162,6 @@ public class ErrorLogHelper {
      * @param are must have a restError value whose numeric value must match what should be returned in the REST API
      * @param variables optional list of variables to flesh out text in error string
      * @return appropriately formatted JSON response per the REST API spec.
-     * @throws ErrorObjectFormatException
-     * @throws ErrorObjectNotFoundException
-     * @throws IOException
      */
     public static String getRESTAPIErrorResponse(List<MediaType> acceptHeadersOrig, AAIException are,
             ArrayList<String> variables) {
@@ -333,7 +326,7 @@ public class ErrorLogHelper {
                         restresp.setRequestError(reqerr);
                         response = (MapperUtil.writeAsJSONString((Object) restresp));
                     }
-                } catch (AAIException ex) {
+                } catch (Exception ex) {
                     LOGGER.error(
                             "We were unable to create a rest exception to return on an API because of a parsing error "
                                     + ex.getMessage());
@@ -350,18 +343,11 @@ public class ErrorLogHelper {
      * @param acceptHeadersOrig the accept headers orig
      * @param are the are
      * @param variables the variables
-     * @param logline the logline
-     * @return the RESTAPI error response with logging
-     * @throws ErrorObjectFormatException
-     * @throws ErrorObjectNotFoundException
-     * @throws IOException
      */
     public static String getRESTAPIErrorResponseWithLogging(List<MediaType> acceptHeadersOrig, AAIException are,
             ArrayList<String> variables) {
         String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables);
-
-        LOGGER.error(are.getMessage() + " " + LogFormatTools.getStackTop(are));
-
+        logException(are);
         return response;
     }
 
@@ -371,9 +357,6 @@ public class ErrorLogHelper {
      * @param acceptHeaders the accept headers
      * @param areList the are list
      * @return the RESTAPI info response
-     * @throws ErrorObjectFormatException
-     * @throws ErrorObjectNotFoundException
-     * @throws IOException
      */
     public static Object getRESTAPIInfoResponse(List<MediaType> acceptHeaders,
             HashMap<AAIException, ArrayList<String>> areList) {
@@ -463,13 +446,10 @@ public class ErrorLogHelper {
      * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
      * If no error object is embedded in the AAIException, one will be created using the error object from the
      * AAIException.
-     * 
+     *
      * @param are must have a restError value whose numeric value must match what should be returned in the REST API
      * @param variables optional list of variables to flesh out text in error string
      * @return appropriately formatted JSON response per the REST API spec.
-     * @throws ErrorObjectFormatException
-     * @throws ErrorObjectNotFoundException
-     * @throws IOException
      */
     public static String getRESTAPIPolicyErrorResponseXML(AAIException are, ArrayList<String> variables) {
 
@@ -586,16 +566,17 @@ public class ErrorLogHelper {
 
     public static void logException(AAIException e) {
         final ErrorObject errorObject = e.getErrorObject();
-
-        // MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity)
+        /*
         String severityCode = errorObject.getSeverityCode(errorObject.getSeverity());
 
-        if (!AAIConfig.isEmpty(severityCode)) {
+        Severify should be left empty per Logging Specification 2019.11
+        if (!StringUtils.isEmpty(severityCode)) {
             int sevCode = Integer.parseInt(severityCode);
             if (sevCode > 0 && sevCode <= 3) {
                 LoggingContext.severity(sevCode);
             }
         }
+        */
         String stackTrace = "";
         try {
             stackTrace = LogFormatTools.getStackTop(e);
@@ -606,10 +587,14 @@ public class ErrorLogHelper {
                 .append(errorObject.getRESTErrorCode()).append(":").append(errorObject.getHTTPResponseCode())
                 .append(":").append(e.getMessage()).toString().replaceAll("\\n", "^");
 
-        LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode()));
-        LoggingContext.responseDescription(errorMessage);
-        LoggingContext.statusCode(StatusCode.ERROR);
-
+        MDCSetup mdcSetup = new MDCSetup();
+        mdcSetup.setResponseStatusCode(errorObject.getHTTPResponseCode().getStatusCode());
+        mdcSetup.setErrorCode(Integer.parseInt(errorObject.getAaiElsErrorCode()));
+        String serviceName = MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME);
+        if (serviceName == null || serviceName.isEmpty()) {
+            MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, Constants.DefaultValues.UNKNOWN);
+        }
+        MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, errorMessage);
         final String details =
                 new StringBuilder().append(errorObject.getErrorCodeString()).append(" ").append(stackTrace).toString();