Docker update and POM fix
[music.git] / src / main / java / org / onap / music / main / CachingUtil.java
index 0ab055d..16a0286 100755 (executable)
@@ -32,12 +32,16 @@ import javax.ws.rs.core.MediaType;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.jcs.JCS;
 import org.apache.commons.jcs.access.CacheAccess;
-import org.apache.log4j.Logger;
 import org.codehaus.jackson.map.ObjectMapper;
+import org.onap.music.datastore.PreparedQueryObject;
 import org.onap.music.datastore.jsonobjects.AAFResponse;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.eelf.logging.format.AppMessages;
+import org.onap.music.eelf.logging.format.ErrorSeverity;
+import org.onap.music.eelf.logging.format.ErrorTypes;
+import org.onap.music.exceptions.MusicServiceException;
+
 import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.onap.music.datastore.PreparedQueryObject;
 import com.datastax.driver.core.DataType;
 import com.datastax.driver.core.ResultSet;
 import com.datastax.driver.core.Row;
@@ -53,7 +57,7 @@ import com.sun.jersey.api.client.WebResource;
  */
 public class CachingUtil implements Runnable {
 
-    private static EELFLogger logger = EELFManager.getInstance().getLogger(CachingUtil.class);
+    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
 
     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
@@ -68,24 +72,21 @@ public class CachingUtil implements Runnable {
     }
 
     public void initializeMusicCache() {
-        logger.info("Initializing Music Cache...");
+        logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
         musicCache.put("isInitialized", "true");
     }
 
-    public void initializeAafCache() {
-        logger.info("Resetting and initializing AAF Cache...");
+    public void initializeAafCache() throws MusicServiceException {
+        logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
 
-        // aafCache.clear();
-        // loop through aafCache ns .. only the authenticated ns will be re cached. and non
-        // authenticated will wait for user to retry.
-        String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
+        String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
         PreparedQueryObject pQuery = new PreparedQueryObject();
         pQuery.appendQueryString(query);
         try {
             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
         } catch (Exception e1) {
+            logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
             e1.printStackTrace();
-            logger.error("Exception is " + e1.getMessage() + "during initalizeAafCache");
         }
         ResultSet rs = MusicCore.get(pQuery);
         Iterator<Row> it = rs.iterator();
@@ -108,11 +109,9 @@ public class CachingUtil implements Runnable {
                                     + nameSpace);
                 }
             } catch (Exception e) {
-                // TODO Auto-generated catch block
+                logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
+                logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
                 e.printStackTrace();
-                logger.error("Something at AAF was changed for ns: " + nameSpace
-                                + ". So not updating Cache for the namespace. ");
-                logger.error("Exception is " + e.getMessage());
             }
         }
 
@@ -120,18 +119,22 @@ public class CachingUtil implements Runnable {
 
     @Override
     public void run() {
-        logger.debug("Scheduled task invoked. Refreshing Cache...");
-        initializeAafCache();
+       logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
+        try {
+                       initializeAafCache();
+               } catch (MusicServiceException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
+               }
     }
 
     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
                     String keySpace) throws Exception {
 
         if (aafCache.get(nameSpace) != null) {
-            if (!musicCache.get(nameSpace).equals(keySpace)) {
-                logger.debug("Create new application for the same namespace.");
+            if (keySpace != null && !musicCache.get(nameSpace).equals(keySpace)) {
+               logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
             } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
-                logger.debug("Authenticated with cache value..");
+               logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
                 // reset invalid attempts to 0
                 userAttempts.put(nameSpace, 0);
                 return true;
@@ -140,38 +143,41 @@ public class CachingUtil implements Runnable {
                 if (userAttempts.get(nameSpace) == null)
                     userAttempts.put(nameSpace, 0);
                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
-                    logger.info("Reached max attempts. Checking if time out..");
-                    logger.info("Failed time: " + lastFailedTime.get(nameSpace).getTime());
+                    logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
+                    logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
                     Calendar calendar = Calendar.getInstance();
-                    long delayTime = (calendar.getTimeInMillis()
-                                    - lastFailedTime.get(nameSpace).getTimeInMillis());
-                    logger.info("Delayed time: " + delayTime);
-                    if (delayTime > 120000) {
-                        logger.info("Resetting failed attempt.");
+                    long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
+                    logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
+                    if( delayTime > 120000) {
+                        logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
                         userAttempts.put(nameSpace, 0);
                     } else {
-                        throw new Exception(
-                                        "No more attempts allowed. Please wait for atleast 2 min.");
+                       logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
+                        throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
                     }
                 }
-                logger.error("Cache not authenticated..");
-                logger.info("Check AAF again...");
+                logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+                logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
             }
         }
 
         AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
         if (responseObj.getNs().size() > 0) {
-            if (responseObj.getNs().get(0).getAdmin().contains(userId))
-                return true;
-
+            if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
+               //Map<String, String> map = new HashMap<>();
+                //map.put(userId, password);
+                //aafCache.put(nameSpace, map);
+               return true;
+            }
         }
-        logger.info("Invalid user. Cache not updated");
+        logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
         return false;
     }
 
     private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
                     throws Exception {
         if (MusicUtil.getAafEndpointUrl() == null) {
+               logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
         }
         Client client = Client.create();
@@ -207,6 +213,7 @@ public class CachingUtil implements Runnable {
         response.bufferEntity();
         String x = response.getEntity(String.class);
         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
+        
         return responseObj;
     }
 
@@ -229,7 +236,7 @@ public class CachingUtil implements Runnable {
                 musicCache.put(keyspace, uuid);
             } catch (Exception e) {
                 String msg = e.getMessage();
-                logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
+                logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
                 resultMap.put("Exception", "Unauthorized operation. Check AID and Keyspace. "
                                 + "Exception from MUSIC is: "
                                 + (msg == null ? "Keyspace is new so no AID should be passed in Header."
@@ -252,7 +259,7 @@ public class CachingUtil implements Runnable {
     }
 
     public static void updateMusicCache(String aid, String keyspace) {
-        logger.info("Updating musicCache for keyspace " + keyspace + " with aid " + aid);
+       logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with aid " + aid);
         musicCache.put(keyspace, aid);
     }
 
@@ -260,7 +267,7 @@ public class CachingUtil implements Runnable {
         appNameCache.put(namespace, isAAF);
     }
 
-    public static Boolean isAAFApplication(String namespace) {
+    public static Boolean isAAFApplication(String namespace) throws MusicServiceException {
 
         String isAAF = appNameCache.get(namespace);
         if (isAAF == null) {
@@ -273,14 +280,15 @@ public class CachingUtil implements Runnable {
                 isAAF = String.valueOf(rs.getBool("is_aaf"));
                 appNameCache.put(namespace, isAAF);
             } catch (Exception e) {
-                logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
-                e.printStackTrace();
+               logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+               e.printStackTrace();
             }
         }
+
         return Boolean.valueOf(isAAF);
     }
 
-    public static String getUuidFromMusicCache(String keyspace) {
+    public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
         String uuid = musicCache.get(keyspace);
         if (uuid == null) {
             PreparedQueryObject pQuery = new PreparedQueryObject();
@@ -292,14 +300,14 @@ public class CachingUtil implements Runnable {
                 uuid = rs.getUUID("uuid").toString();
                 musicCache.put(keyspace, uuid);
             } catch (Exception e) {
-                logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
+                logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
                 e.printStackTrace();
             }
         }
         return uuid;
     }
 
-    public static String getAppName(String keyspace) {
+    public static String getAppName(String keyspace) throws MusicServiceException {
         String appName = null;
         PreparedQueryObject pQuery = new PreparedQueryObject();
         pQuery.appendQueryString(
@@ -309,7 +317,7 @@ public class CachingUtil implements Runnable {
         try {
             appName = rs.getString("application_name");
         } catch (Exception e) {
-            logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
             e.printStackTrace();
         }
         return appName;
@@ -317,7 +325,7 @@ public class CachingUtil implements Runnable {
 
     public static String generateUUID() {
         String uuid = UUID.randomUUID().toString();
-        logger.info("New AID generated: " + uuid);
+        logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
         return uuid;
     }
 
@@ -333,33 +341,50 @@ public class CachingUtil implements Runnable {
 
     }
 
-    public static Map<String, Object> verifyOnboarding(String ns, String userId, String password)
-                    throws Exception {
+    public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
         Map<String, Object> resultMap = new HashMap<>();
         if (ns == null || userId == null || password == null) {
-            logger.error("One or more required headers is missing. userId: " + userId
-                            + " :: password: " + password);
+               logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+               logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
             resultMap.put("Exception",
                             "One or more required headers appName(ns), userId, password is missing. Please check.");
             return resultMap;
         }
         PreparedQueryObject queryObject = new PreparedQueryObject();
         queryObject.appendQueryString(
-                        "select * from admin.keyspace_master where application_name=? and username=? allow filtering");
-        queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
-        queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
-        Row rs = MusicCore.get(queryObject).one();
+                        "select * from admin.keyspace_master where application_name = ? allow filtering");
+        try {
+               queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
+        } catch(Exception e) {
+               resultMap.put("Exception",
+                    "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
+               return resultMap;
+        }
+        Row rs = null;
+               try {
+                       rs = MusicCore.get(queryObject).one();
+               } catch (MusicServiceException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+                       resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
+                       return resultMap;
+               }
         if (rs == null) {
-            logger.error("Namespace and UserId doesn't match. namespace: " + ns + " and userId: "
-                            + userId);
-            resultMap.put("Exception", "Application " + ns
-                            + " doesn't seem to be Onboarded. Please onboard your application with MUSIC. If already onboarded contact Admin");
+            logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
+            resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
         } else {
+            if(!(rs.getString("username").equals(userId)) && !(rs.getString("password").equals("password"))) {
+                logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+                logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
+                resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
+                return resultMap;
+            }
             boolean is_aaf = rs.getBool("is_aaf");
             String keyspace = rs.getString("keyspace_name");
             if (!is_aaf) {
                 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
-                    logger.error("Non AAF applications are allowed to have only one keyspace per application.");
+                    logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
+                    logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application.");
                     resultMap.put("Exception",
                                     "Non AAF applications are allowed to have only one keyspace per application.");
                 }