diff options
author | Thomas Nelson Jr (arthurdent3) <tn1381@att.com> | 2018-02-20 16:50:44 -0500 |
---|---|---|
committer | Thomas Nelson Jr (arthurdent3) <tn1381@att.com> | 2018-02-20 16:50:44 -0500 |
commit | 3acbae6bf3be04f352bfaac340b8303064a2f7c4 (patch) | |
tree | ed5df3391216742cb9bfd20dc798dd5a246bc962 /src/main/java/org/onap/music/main | |
parent | dffae1c7c5cd1f50e2456948942cd7716837a7f2 (diff) |
Applying bug fixes
To many overlapping changes so including all of them.
When pushing individually build was breaking.
Issue-ID: MUSIC-33,MUSIC-34,MUSIC-35,MUSIC-36,MUSIC-37
Change-Id: I15b6f7c683d0d2eeadd99c2376dedd6c43a67a8c
Signed-off-by: Thomas Nelson Jr (arthurdent3) <tn1381@att.com>
Diffstat (limited to 'src/main/java/org/onap/music/main')
-rwxr-xr-x | src/main/java/org/onap/music/main/CachingUtil.java | 74 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/MusicCore.java | 206 | ||||
-rwxr-xr-x | src/main/java/org/onap/music/main/MusicUtil.java | 859 |
3 files changed, 585 insertions, 554 deletions
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java index 0ab055df..cd1d565d 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/main/CachingUtil.java @@ -32,12 +32,13 @@ 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.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 +54,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,16 +69,13 @@ 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"; PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString(query); @@ -85,7 +83,7 @@ public class CachingUtil implements Runnable { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false)); } catch (Exception e1) { e1.printStackTrace(); - logger.error("Exception is " + e1.getMessage() + "during initalizeAafCache"); + logger.error(EELFLoggerDelegate.errorLogger,"Exception is "+ e1.getMessage() + "during initalizeAafCache"); } ResultSet rs = MusicCore.get(pQuery); Iterator<Row> it = rs.iterator(); @@ -121,7 +119,11 @@ public class CachingUtil implements Runnable { @Override public void run() { logger.debug("Scheduled task invoked. Refreshing Cache..."); - initializeAafCache(); + try { + initializeAafCache(); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + } } public static boolean authenticateAAFUser(String nameSpace, String userId, String password, @@ -140,22 +142,20 @@ 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."); + 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,"Cache not authenticated.."); + logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again..."); } } @@ -165,7 +165,7 @@ public class CachingUtil implements Runnable { return true; } - logger.info("Invalid user. Cache not updated"); + logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated"); return false; } @@ -260,7 +260,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) { @@ -277,10 +277,12 @@ public class CachingUtil implements Runnable { 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 +294,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 +311,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,"Exception occured during uuid retrieval from DB."+e.getMessage()); e.printStackTrace(); } return appName; @@ -317,7 +319,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; } @@ -337,8 +339,7 @@ public class CachingUtil implements Runnable { throws Exception { 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,"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; @@ -350,16 +351,15 @@ public class CachingUtil implements Runnable { queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); Row rs = MusicCore.get(queryObject).one(); 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,"Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId); + + resultMap.put("Exception", "Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId); } else { 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,"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."); } diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java index 592bae92..96056160 100644 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ b/src/main/java/org/onap/music/main/MusicCore.java @@ -26,9 +26,11 @@ import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; + import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.eelf.logging.EELFLoggerDelegate; // import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; @@ -36,8 +38,7 @@ import org.onap.music.exceptions.MusicServiceException; import org.onap.music.lockingservice.MusicLockState; import org.onap.music.lockingservice.MusicLockState.LockStatus; import org.onap.music.lockingservice.MusicLockingService; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; + import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; @@ -54,22 +55,20 @@ public class MusicCore { public static MusicLockingService mLockHandle = null; public static MusicDataStore mDstoreHandle = null; - private static EELFLogger logger = EELFManager.getInstance().getLogger(MusicCore.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); public static class Condition { Map<String, Object> conditions; - String selectQueryForTheRow; + PreparedQueryObject selectQueryForTheRow; - public Condition(Map<String, Object> conditions, String selectQueryForTheRow) { + public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) { this.conditions = conditions; this.selectQueryForTheRow = selectQueryForTheRow; } public boolean testCondition() { // first generate the row - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString(selectQueryForTheRow); - ResultSet results = quorumGet(query); + ResultSet results = quorumGet(selectQueryForTheRow); Row row = results.one(); return getDSHandle().doesRowSatisfyCondition(row, conditions); } @@ -77,19 +76,19 @@ public class MusicCore { public static MusicLockingService getLockingServiceHandle() throws MusicLockingException { - logger.info("Acquiring lock store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); long start = System.currentTimeMillis(); if (mLockHandle == null) { try { mLockHandle = new MusicLockingService(); } catch (Exception e) { - logger.error("Failed to aquire Locl store handle" + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquire Locl store handle" + e.getMessage()); throw new MusicLockingException("Failed to aquire Locl store handle " + e); } } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire lock store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms"); return mLockHandle; } @@ -99,13 +98,13 @@ public class MusicCore { * @return */ public static MusicDataStore getDSHandle(String remoteIp) { - logger.info("Acquiring data store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); long start = System.currentTimeMillis(); if (mDstoreHandle == null) { mDstoreHandle = new MusicDataStore(remoteIp); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire data store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); return mDstoreHandle; } @@ -114,27 +113,27 @@ public class MusicCore { * @return */ public static MusicDataStore getDSHandle() { - logger.info("Acquiring data store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); long start = System.currentTimeMillis(); if (mDstoreHandle == null) { mDstoreHandle = new MusicDataStore(); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire data store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); return mDstoreHandle; } public static String createLockReference(String lockName) { - logger.info("Creating lock reference for lock name:" + lockName); + logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName); long start = System.currentTimeMillis(); String lockId = null; try { lockId = getLockingServiceHandle().createLockId("/" + lockName); } catch (MusicLockingException e) { - logger.error("Failed to create Lock Reference " + lockName); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to create Lock Reference " + lockName); } long end = System.currentTimeMillis(); - logger.info("Time taken to create lock reference:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms"); return lockId; } @@ -167,10 +166,10 @@ public class MusicCore { String lockName = keyspaceName + "." + tableName + "." + primaryKey; mls = getLockingServiceHandle().getLockState(lockName); long end = System.currentTimeMillis(); - logger.info("Time taken to get lock state:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms"); return mls; } catch (NullPointerException | MusicLockingException e) { - logger.error("No lock object exists as of now.." + e); + logger.error(EELFLoggerDelegate.errorLogger,"No lock object exists as of now.." + e); } return null; } @@ -182,12 +181,12 @@ public class MusicCore { MusicLockState mls = getMusicLockState(key); if (mls != null) { if (mls.getLockStatus().equals(LockStatus.LOCKED)) { - logger.info("The current lock holder for " + key + " is " + mls.getLockHolder() + logger.info(EELFLoggerDelegate.applicationLogger,"The current lock holder for " + key + " is " + mls.getLockHolder() + ". Checking if it has exceeded lease"); long currentLockPeriod = System.currentTimeMillis() - mls.getLeaseStartTime(); long currentLeasePeriod = mls.getLeasePeriod(); if (currentLockPeriod > currentLeasePeriod) { - logger.info("Lock period " + currentLockPeriod + logger.info(EELFLoggerDelegate.applicationLogger,"Lock period " + currentLockPeriod + " has exceeded lease period " + currentLeasePeriod); boolean voluntaryRelease = false; String currentLockHolder = mls.getLockHolder(); @@ -201,7 +200,7 @@ public class MusicCore { * call the traditional acquire lock now and if the result returned is true, set the * begin time-stamp and lease period */ - if (acquireLock(key, lockId) == true) { + if (acquireLock(key, lockId).getResult() == ResultType.SUCCESS) { mls = getMusicLockState(key);// get latest state if (mls.getLeaseStartTime() == -1) {// set it again only if it is not set already mls.setLeaseStartTime(System.currentTimeMillis()); @@ -209,23 +208,23 @@ public class MusicCore { getLockingServiceHandle().setLockState(key, mls); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire leased lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire leased lock:" + (end - start) + " ms"); return new ReturnType(ResultType.SUCCESS, "Accquired lock"); } else { long end = System.currentTimeMillis(); - logger.info("Time taken to fail to acquire leased lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to fail to acquire leased lock:" + (end - start) + " ms"); return new ReturnType(ResultType.FAILURE, "Could not acquire lock"); } } catch (Exception e) { StringWriter sw = new StringWriter(); - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); String exceptionAsString = sw.toString(); return new ReturnType(ResultType.FAILURE, "Exception thrown in acquireLockWithLease:\n" + exceptionAsString); } } - public static boolean acquireLock(String key, String lockId) { + public static ReturnType acquireLock(String key, String lockId) { /* * first check if I am on top. Since ids are not reusable there is no need to check * lockStatus If the status is unlocked, then the above call will automatically return @@ -235,19 +234,28 @@ public class MusicCore { try { result = getLockingServiceHandle().isMyTurn(lockId); } catch (MusicLockingException e2) { - logger.error("Failed to aquireLock lockId " + lockId + " " + e2); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquireLock lockId " + lockId + " " + e2); } if (result == false) { - logger.info("In acquire lock: Not your turn, someone else has the lock"); - return false; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock"); + try { + if (!getLockingServiceHandle().lockIdExists(lockId)) { + logger.info(EELFLoggerDelegate.applicationLogger, "In acquire lock: this lockId doesn't exist"); + return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist"); + } + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,"Failed to check if lockid exists - lockId " + lockId + " " + e); + } + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure"); + return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock"); } // this is for backward compatibility where locks could also be acquired on just // keyspaces or tables. if (isTableOrKeySpaceLock(key) == true) { - logger.info("In acquire lock: A table or keyspace lock so no need to perform sync...so returning true"); - return true; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: A table or keyspace lock so no need to perform sync...so returning true"); + return new ReturnType(ResultType.SUCCESS, "A table or keyspace lock so no need to perform sync...so returning true"); } // read the lock name corresponding to the key and if the status is locked or being locked, @@ -258,11 +266,11 @@ public class MusicCore { currentMls = getMusicLockState(key); String currentLockHolder = currentMls.getLockHolder(); if (lockId.equals(currentLockHolder)) { - logger.info("In acquire lock: You already have the lock!"); - return true; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: You already have the lock!"); + return new ReturnType(ResultType.SUCCESS, "You already have the lock!"); } } catch (NullPointerException e) { - logger.error("In acquire lock:No one has tried to acquire the lock yet.."); + logger.error(EELFLoggerDelegate.errorLogger,"In acquire lock:No one has tried to acquire the lock yet.."); } // change status to "being locked". This state transition is necessary to ensure syncing @@ -278,13 +286,13 @@ public class MusicCore { try { getLockingServiceHandle().setLockState(key, newMls); } catch (MusicLockingException e1) { - logger.error("Failed to set Lock state " + key + " " + e1); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e1); } - logger.info("In acquire lock: Set lock state to being_locked"); + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to being_locked"); // do syncing if this was a forced lock release if (needToSyncQuorum) { - logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!"); + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!"); syncQuorum(key); } @@ -295,11 +303,12 @@ public class MusicCore { try { getLockingServiceHandle().setLockState(key, newMls); } catch (MusicLockingException e) { - logger.error("Failed to set Lock state " + key + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e); } - logger.info("In acquire lock: Set lock state to locked and assigned current lock ref " + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref " + lockId + " as holder"); - return result; + + return new ReturnType(result?ResultType.SUCCESS:ResultType.FAILURE, "Set lock state to locked and assigned a lock holder"); } @@ -317,7 +326,7 @@ public class MusicCore { private static void syncQuorum(String key) { - logger.info("Performing sync operation---"); + logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); String[] splitString = key.split("\\."); String keyspaceName = splitString[0]; String tableName = splitString[1]; @@ -330,8 +339,8 @@ public class MusicCore { String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();// we only support single // primary key DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); - String cqlFormattedPrimaryKeyValue = - MusicUtil.convertToCQLDataType(primaryKeyType, primaryKeyValue); + Object cqlFormattedPrimaryKeyValue = + MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue); // get the row of data from a quorum selectQuery.appendQueryString("SELECT * FROM " + keyspaceName + "." + tableName + " WHERE " @@ -355,7 +364,7 @@ public class MusicCore { continue; DataType colType = definition.getType(); Object valueObj = getDSHandle().getColValue(row, colName, colType); - String valueString = MusicUtil.convertToCQLDataType(colType, valueObj); + Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); // fieldValueString = fieldValueString+ colName+"="+valueString; fieldValueString.append(colName + " = ?"); updateQuery.addValue(valueString); @@ -371,7 +380,7 @@ public class MusicCore { getDSHandle().executePut(updateQuery, "critical"); } catch (MusicServiceException | MusicQueryException e) { - logger.error("Failed to execute update query " + updateQuery + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to execute update query " + updateQuery + " " + e); } } @@ -396,7 +405,7 @@ public class MusicCore { ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); long lockAcqTime = System.currentTimeMillis(); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockId, conditionInfo); long criticalPutTime = System.currentTimeMillis(); @@ -409,7 +418,7 @@ public class MusicCore { criticalPutResult.setTimingInfo(timingInfo); return criticalPutResult; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); deleteLock(key); return lockAcqResult; } @@ -425,7 +434,7 @@ public class MusicCore { try { results = getDSHandle().executeCriticalGet(query); } catch (MusicServiceException | MusicQueryException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return results; @@ -450,7 +459,7 @@ public class MusicCore { try { return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + ""; } catch (MusicLockingException e) { - logger.error("Failed whoseTurnIsIt " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed whoseTurnIsIt " + lockName + " " + e); } return null; @@ -472,10 +481,10 @@ public class MusicCore { try { getLockingServiceHandle().unlockAndDeleteId(lockId); } catch (MusicLockingException e) { - logger.error("Failed to Destroy Lock Ref " + lockId + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to Destroy Lock Ref " + lockId + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to destroy lock reference:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); } public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) { @@ -483,27 +492,27 @@ public class MusicCore { try { getLockingServiceHandle().unlockAndDeleteId(lockId); } catch (MusicLockingException e1) { - logger.error("Failed to release Lock " + lockId + " " + e1); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + e1); } String lockName = getLockNameFromId(lockId); MusicLockState mls; String lockHolder = null; if (voluntaryRelease) { mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder); - logger.info("In unlock: lock voluntarily released for " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock voluntarily released for " + lockId); } else { boolean needToSyncQuorum = true; mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder, needToSyncQuorum); - logger.info("In unlock: lock forcibly released for " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock forcibly released for " + lockId); } try { getLockingServiceHandle().setLockState(lockName, mls); } catch (MusicLockingException e) { - logger.error("Failed to release Lock " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockName + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to release lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms"); return mls; } @@ -513,14 +522,14 @@ public class MusicCore { */ public static void deleteLock(String lockName) { long start = System.currentTimeMillis(); - logger.info("Deleting lock for " + lockName); + logger.info(EELFLoggerDelegate.applicationLogger,"Deleting lock for " + lockName); try { getLockingServiceHandle().deleteLock("/" + lockName); } catch (MusicLockingException e) { - logger.error("Failed to Delete Lock " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to Delete Lock " + lockName + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to delete lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms"); } @@ -544,7 +553,7 @@ public class MusicCore { try { getLockingServiceHandle().getzkLockHandle().createNode(nodeName); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } } @@ -555,15 +564,15 @@ public class MusicCore { */ public static void pureZkWrite(String nodeName, byte[] data) { long start = System.currentTimeMillis(); - logger.info("Performing zookeeper write to " + nodeName); + logger.info(EELFLoggerDelegate.applicationLogger,"Performing zookeeper write to " + nodeName); try { getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } - logger.info("Performed zookeeper write to " + nodeName); + logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName); long end = System.currentTimeMillis(); - logger.info("Time taken for the actual zk put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); } /** @@ -577,10 +586,10 @@ public class MusicCore { try { data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken for the actual zk put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); return data; } @@ -602,7 +611,7 @@ public class MusicCore { try { result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); } catch (MusicServiceException | MusicQueryException ex) { - logger.error(ex.getMessage() + " " + ex.getCause() + " " + ex); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); } if (result) { return new ReturnType(ResultType.SUCCESS, "Success"); @@ -634,16 +643,18 @@ public class MusicCore { "Lock acquired but the condition is not true"); getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); long end = System.currentTimeMillis(); - logger.info("Time taken for the critical put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); return new ReturnType(ResultType.SUCCESS, "Update performed"); } else return new ReturnType(ResultType.FAILURE, "Cannot perform operation since you are the not the lock holder"); - } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(e.getMessage()); + } catch (MusicQueryException | MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); return new ReturnType(ResultType.FAILURE, "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" + e.getMessage()); + }catch(MusicLockingException ex){ + return new ReturnType(ResultType.FAILURE,ex.getMessage()); } } @@ -653,17 +664,19 @@ public class MusicCore { * @param queryObject * @param consistency * @return Boolean Indicates success or failure + * @throws MusicServiceException * * */ - public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) { + public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException { // this is mainly for some functions like keyspace creation etc which does not // really need the bells and whistles of Music locking. boolean result = false; try { result = getDSHandle().executePut(queryObject, consistency); } catch (MusicQueryException | MusicServiceException ex) { - logger.error(ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage()); + throw new MusicServiceException(ex.getMessage()); } return result; } @@ -673,13 +686,15 @@ public class MusicCore { * * @param queryObject query object containing prepared query and values * @return ResultSet + * @throws MusicServiceException */ - public static ResultSet get(PreparedQueryObject queryObject) { + public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { ResultSet results = null; try { - results = getDSHandle().executeEventualGet(queryObject); + results = getDSHandle().executeEventualGet(queryObject); } catch (MusicQueryException | MusicServiceException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + throw new MusicServiceException(e.getMessage()); } return results; } @@ -706,7 +721,7 @@ public class MusicCore { } else throw new MusicServiceException("YOU DO NOT HAVE THE LOCK"); } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return results; } @@ -730,7 +745,7 @@ public class MusicCore { ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); long lockAcqTime = System.currentTimeMillis(); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockId, conditionInfo); long criticalPutTime = System.currentTimeMillis(); @@ -744,7 +759,7 @@ public class MusicCore { criticalPutResult.setTimingInfo(timingInfo); return criticalPutResult; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); destroyLockRef(lockId); return lockAcqResult; } @@ -768,14 +783,14 @@ public class MusicCore { long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId); boolean voluntaryRelease = true; releaseLock(lockId, voluntaryRelease); return result; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); return null; } } @@ -801,32 +816,35 @@ public class MusicCore { operation); if (!resultMap.isEmpty()) return resultMap; + boolean isAAF = CachingUtil.isAAFApplication(nameSpace); + if (!isAAF && !(operation.equals("createKeySpace"))) { + if(aid == null) { + resultMap.put("Exception", "Aid is mandatory for nonAAF applications "); + return resultMap; + } + resultMap = CachingUtil.authenticateAIDUser(aid, keyspace); + if (!resultMap.isEmpty()) + return resultMap; + } if (aid == null && (userId == null || password == null)) { - logger.error("One or more required headers is missing. userId: " + userId + logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId + " :: password: " + password); resultMap.put("Exception", "UserId and Password are mandatory for the operation " + operation); return resultMap; } - boolean isAAF = CachingUtil.isAAFApplication(nameSpace); - if (!isAAF && aid != null && aid.length() > 0) { // Non AAF app - resultMap = CachingUtil.authenticateAIDUser(aid, keyspace); - if (!resultMap.isEmpty()) - return resultMap; - } + if (isAAF && nameSpace != null && userId != null && password != null) { boolean isValid = true; try { isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace); } catch (Exception e) { - logger.error("Got exception while AAF authentication for namespace " + nameSpace); + logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace); resultMap.put("Exception", e.getMessage()); - // return resultMap; } if (!isValid) { - logger.error("User not authenticated with AAF."); + logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated with AAF."); resultMap.put("Exception", "User not authenticated..."); - // return resultMap; } if (!resultMap.isEmpty()) return resultMap; @@ -834,7 +852,7 @@ public class MusicCore { } if (operation.equals("createKeySpace")) { - logger.info("AID is not provided. Creating new UUID for keyspace."); + logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace."); PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering"); @@ -848,7 +866,7 @@ public class MusicCore { uuid = rs.getUUID("uuid").toString(); resultMap.put("uuid", "existing"); } catch (Exception e) { - logger.info("No UUID found in DB. So creating new UUID."); + logger.info(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID."); uuid = CachingUtil.generateUUID(); resultMap.put("uuid", "new"); } diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index 61d428d1..47e23973 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -21,445 +21,458 @@ */ package org.onap.music.main; - import java.io.File; import java.io.FileNotFoundException; import java.math.BigInteger; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.UUID; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicServiceException; + import com.datastax.driver.core.DataType; /** * @author nelson24 * - * Properties This will take Properties and load them into MusicUtil. This is a hack for - * now. Eventually it would bebest to do this in another way. + * Properties This will take Properties and load them into MusicUtil. + * This is a hack for now. Eventually it would bebest to do this in + * another way. * */ public class MusicUtil { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - - private static int myId = 0; - private static ArrayList<String> allIds = new ArrayList<String>(); - private static String publicIp = ""; - private static ArrayList<String> allPublicIps = new ArrayList<String>(); - private static String myZkHost = "localhost"; - private static String myCassaHost = "localhost"; - private static String defaultMusicIp = "localhost"; - private static boolean debug = true; - private static String version = "2.3.0"; - public static String musicRestIp = "localhost"; - private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties"; - private static long defaultLockLeasePeriod = 6000; - private static final String[] propKeys = new String[] {"zookeeper.host", "cassandra.host", - "music.ip", "debug", "version", "music.rest.ip", "music.properties", - "lock.lease.period", "id", "all.ids", "public.ip", "all.pubic.ips", - "cassandra.user", "cassandra.password", "aaf.endpoint.url"}; - - public static final String ATOMIC = "atomic"; - public static final String EVENTUAL = "eventual"; - public static final String CRITICAL = "critical"; - public static final String DEFAULTKEYSPACENAME = "TBD"; - private static String cassName = "cassandra"; - private static String cassPwd = "cassandra"; - private static String aafEndpointUrl = null; - - /** - * @return the cassName - */ - public static String getCassName() { - return cassName; - } - - /** - * @return the cassPwd - */ - public static String getCassPwd() { - return cassPwd; - } - - /** - * @return the aafEndpointUrl - */ - public static String getAafEndpointUrl() { - return aafEndpointUrl; - } - - /** - * - * @param aafEndpointUrl - */ - public static void setAafEndpointUrl(String aafEndpointUrl) { - MusicUtil.aafEndpointUrl = aafEndpointUrl; - } - - /** - * - * @return - */ - public static int getMyId() { - return myId; - } - - /** - * - * @param myId - */ - public static void setMyId(int myId) { - MusicUtil.myId = myId; - } - - - /** - * - * @return - */ - public static ArrayList<String> getAllIds() { - return allIds; - } - - /** - * - * @param allIds - */ - public static void setAllIds(List<String> allIds) { - MusicUtil.allIds = (ArrayList<String>) allIds; - } - - /** - * - * @return - */ - public static String getPublicIp() { - return publicIp; - } - - /** - * - * @param publicIp - */ - public static void setPublicIp(String publicIp) { - MusicUtil.publicIp = publicIp; - } - - /** - * - * @return - */ - public static ArrayList<String> getAllPublicIps() { - return allPublicIps; - } - - /** - * - * @param allPublicIps - */ - public static void setAllPublicIps(List<String> allPublicIps) { - MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps; - } - - /** - * Returns An array of property names that should be in the Properties files. - * - * @return - */ - public static String[] getPropkeys() { - return propKeys; - } - - /** - * Get MusicRestIp - default = localhost property file value - music.rest.ip - * - * @return - */ - public static String getMusicRestIp() { - return musicRestIp; - } - - /** - * Set MusicRestIp - * - * @param musicRestIp - */ - public static void setMusicRestIp(String musicRestIp) { - MusicUtil.musicRestIp = musicRestIp; - } - - /** - * Get MusicPropertiesFilePath - Default = /opt/music/music.properties property file value - - * music.properties - * - * @return - */ - public static String getMusicPropertiesFilePath() { - return musicPropertiesFilePath; - } - - /** - * Set MusicPropertiesFilePath - * - * @param musicPropertiesFilePath - */ - public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) { - MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath; - } - - /** - * Get DefaultLockLeasePeriod - Default = 6000 property file value - lock.lease.period - * - * @return - */ - public static long getDefaultLockLeasePeriod() { - return defaultLockLeasePeriod; - } - - /** - * Set DefaultLockLeasePeriod - * - * @param defaultLockLeasePeriod - */ - public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) { - MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod; - } - - /** - * Set Debug - * - * @param debug - */ - public static void setDebug(boolean debug) { - MusicUtil.debug = debug; - } - - /** - * Is Debug - Default = true property file value - debug - * - * @return - */ - public static boolean isDebug() { - return debug; - } - - /** - * Set Version - * - * @param version - */ - public static void setVersion(String version) { - MusicUtil.version = version; - } - - /** - * Return the version property file value - version - * - * @return - */ - public static String getVersion() { - return version; - } - - /** - * Get MyZkHost - Zookeeper Hostname - Default = localhost property file value - zookeeper.host - * - * @return - */ - public static String getMyZkHost() { - return myZkHost; - } - - /** - * Set MyZkHost - Zookeeper Hostname - * - * @param myZkHost - */ - public static void setMyZkHost(String myZkHost) { - MusicUtil.myZkHost = myZkHost; - } - - /** - * Get MyCassHost - Cassandra Hostname - Default = localhost property file value - - * cassandra.host - * - * @return - */ - public static String getMyCassaHost() { - return myCassaHost; - } - - /** - * Set MyCassHost - Cassandra Hostname - * - * @param myCassaHost - */ - public static void setMyCassaHost(String myCassaHost) { - MusicUtil.myCassaHost = myCassaHost; - } - - /** - * Get DefaultMusicIp - Default = localhost property file value - music.ip - * - * @return - */ - public static String getDefaultMusicIp() { - return defaultMusicIp; - } - - /** - * Set DefaultMusicIp - * - * @param defaultMusicIp - */ - public static void setDefaultMusicIp(String defaultMusicIp) { - MusicUtil.defaultMusicIp = defaultMusicIp; - } - - /** - * - * @return - */ - public static String getTestType() { - String testType = ""; - try { - Scanner fileScanner = new Scanner(new File("")); - testType = fileScanner.next();// ignore the my id line - String batchSize = fileScanner.next();// ignore the my public ip line - fileScanner.close(); - } catch (FileNotFoundException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - return testType; - - } - - /** - * - * @param time - */ - public static void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - } - - /** - * Utility function to check if the query object is valid. - * - * @param withparams - * @param queryObject - * @return - */ - public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) { - if (withparams) { - int noOfValues = queryObject.getValues().size(); - int noOfParams = 0; - char[] temp = queryObject.getQuery().toCharArray(); - for (int i = 0; i < temp.length; i++) { - if (temp[i] == '?') - noOfParams++; - } - return (noOfValues == noOfParams); - } else { - return !queryObject.getQuery().isEmpty(); - } - - } - - public static void setCassName(String cassName) { - MusicUtil.cassName = cassName; - } - - public static void setCassPwd(String cassPwd) { - MusicUtil.cassPwd = cassPwd; - } - - public static String convertToCQLDataType(DataType type, Object valueObj) { - - String value = ""; - switch (type.getName()) { - case UUID: - value = valueObj + ""; - break; - case TEXT: - case VARCHAR: - String valueString = valueObj + ""; - valueString = valueString.replace("'", "''"); - value = "'" + valueString + "'"; - break; - case MAP: { - Map<String, Object> otMap = (Map<String, Object>) valueObj; - value = "{" + jsonMaptoSqlString(otMap, ",") + "}"; - break; - } - default: - value = valueObj + ""; - break; - } - return value; - } - - - /** - * - * @param colType - * @param valueObj - * @return - * @throws Exception - */ - public static Object convertToActualDataType(DataType colType, Object valueObj) { - String valueObjString = valueObj + ""; - switch (colType.getName()) { - case UUID: - return UUID.fromString(valueObjString); - case VARINT: - return BigInteger.valueOf(Long.parseLong(valueObjString)); - case BIGINT: - return Long.parseLong(valueObjString); - case INT: - return Integer.parseInt(valueObjString); - case FLOAT: - return Float.parseFloat(valueObjString); - case DOUBLE: - return Double.parseDouble(valueObjString); - case BOOLEAN: - return Boolean.parseBoolean(valueObjString); - case MAP: - return (Map<String, Object>) valueObj; - default: - return valueObjString; - } - } - - - /** - * - * Utility function to parse json map into sql like string - * - * @param jMap - * @param lineDelimiter - * @return - */ - - public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) { - StringBuilder sqlString = new StringBuilder(); - int counter = 0; - for (Map.Entry<String, Object> entry : jMap.entrySet()) { - Object ot = entry.getValue(); - String value = ot + ""; - if (ot instanceof String) { - value = "'" + value.replace("'", "''") + "'"; - } - sqlString.append("'" + entry.getKey() + "':" + value); - if (counter != jMap.size() - 1) - sqlString.append(lineDelimiter); - counter = counter + 1; - } - return sqlString.toString(); - } + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + private static int myId = 0; + private static ArrayList<String> allIds = new ArrayList<String>(); + private static String publicIp = ""; + private static ArrayList<String> allPublicIps = new ArrayList<String>(); + private static String myZkHost = "localhost"; + private static String myCassaHost = "localhost"; + private static String defaultMusicIp = "localhost"; + private static boolean debug = true; + private static String version = "2.3.0"; + public static String musicRestIp = "localhost"; + private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties"; + private static long defaultLockLeasePeriod = 6000; + private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug", + "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip", + "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" }; + + public static final String ATOMIC = "atomic"; + public static final String EVENTUAL = "eventual"; + public static final String CRITICAL = "critical"; + public static final String DEFAULTKEYSPACENAME = "TBD"; + private static String cassName = "cassandra"; + private static String cassPwd = "cassandra"; + private static String aafEndpointUrl = null; + + /** + * @return the cassName + */ + public static String getCassName() { + return cassName; + } + + /** + * @return the cassPwd + */ + public static String getCassPwd() { + return cassPwd; + } + + /** + * @return the aafEndpointUrl + */ + public static String getAafEndpointUrl() { + return aafEndpointUrl; + } + + /** + * + * @param aafEndpointUrl + */ + public static void setAafEndpointUrl(String aafEndpointUrl) { + MusicUtil.aafEndpointUrl = aafEndpointUrl; + } + + /** + * + * @return + */ + public static int getMyId() { + return myId; + } + + /** + * + * @param myId + */ + public static void setMyId(int myId) { + MusicUtil.myId = myId; + } + + /** + * + * @return + */ + public static ArrayList<String> getAllIds() { + return allIds; + } + + /** + * + * @param allIds + */ + public static void setAllIds(List<String> allIds) { + MusicUtil.allIds = (ArrayList<String>) allIds; + } + + /** + * + * @return + */ + public static String getPublicIp() { + return publicIp; + } + + /** + * + * @param publicIp + */ + public static void setPublicIp(String publicIp) { + MusicUtil.publicIp = publicIp; + } + + /** + * + * @return + */ + public static ArrayList<String> getAllPublicIps() { + return allPublicIps; + } + + /** + * + * @param allPublicIps + */ + public static void setAllPublicIps(List<String> allPublicIps) { + MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps; + } + + /** + * Returns An array of property names that should be in the Properties + * files. + * + * @return + */ + public static String[] getPropkeys() { + return propKeys; + } + + /** + * Get MusicRestIp - default = localhost property file value - music.rest.ip + * + * @return + */ + public static String getMusicRestIp() { + return musicRestIp; + } + + /** + * Set MusicRestIp + * + * @param musicRestIp + */ + public static void setMusicRestIp(String musicRestIp) { + MusicUtil.musicRestIp = musicRestIp; + } + + /** + * Get MusicPropertiesFilePath - Default = /opt/music/music.properties + * property file value - music.properties + * + * @return + */ + public static String getMusicPropertiesFilePath() { + return musicPropertiesFilePath; + } + + /** + * Set MusicPropertiesFilePath + * + * @param musicPropertiesFilePath + */ + public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) { + MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath; + } + + /** + * Get DefaultLockLeasePeriod - Default = 6000 property file value - + * lock.lease.period + * + * @return + */ + public static long getDefaultLockLeasePeriod() { + return defaultLockLeasePeriod; + } + + /** + * Set DefaultLockLeasePeriod + * + * @param defaultLockLeasePeriod + */ + public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) { + MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod; + } + + /** + * Set Debug + * + * @param debug + */ + public static void setDebug(boolean debug) { + MusicUtil.debug = debug; + } + + /** + * Is Debug - Default = true property file value - debug + * + * @return + */ + public static boolean isDebug() { + return debug; + } + + /** + * Set Version + * + * @param version + */ + public static void setVersion(String version) { + MusicUtil.version = version; + } + + /** + * Return the version property file value - version + * + * @return + */ + public static String getVersion() { + return version; + } + + /** + * Get MyZkHost - Zookeeper Hostname - Default = localhost property file + * value - zookeeper.host + * + * @return + */ + public static String getMyZkHost() { + return myZkHost; + } + + /** + * Set MyZkHost - Zookeeper Hostname + * + * @param myZkHost + */ + public static void setMyZkHost(String myZkHost) { + MusicUtil.myZkHost = myZkHost; + } + + /** + * Get MyCassHost - Cassandra Hostname - Default = localhost property file + * value - cassandra.host + * + * @return + */ + public static String getMyCassaHost() { + return myCassaHost; + } + + /** + * Set MyCassHost - Cassandra Hostname + * + * @param myCassaHost + */ + public static void setMyCassaHost(String myCassaHost) { + MusicUtil.myCassaHost = myCassaHost; + } + + /** + * Get DefaultMusicIp - Default = localhost property file value - music.ip + * + * @return + */ + public static String getDefaultMusicIp() { + return defaultMusicIp; + } + + /** + * Set DefaultMusicIp + * + * @param defaultMusicIp + */ + public static void setDefaultMusicIp(String defaultMusicIp) { + MusicUtil.defaultMusicIp = defaultMusicIp; + } + + /** + * + * @return + */ + public static String getTestType() { + String testType = ""; + try { + Scanner fileScanner = new Scanner(new File("")); + testType = fileScanner.next();// ignore the my id line + String batchSize = fileScanner.next();// ignore the my public ip + // line + fileScanner.close(); + } catch (FileNotFoundException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + return testType; + + } + + /** + * + * @param time + */ + public static void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + } + + /** + * Utility function to check if the query object is valid. + * + * @param withparams + * @param queryObject + * @return + */ + public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) { + if (withparams) { + int noOfValues = queryObject.getValues().size(); + int noOfParams = 0; + char[] temp = queryObject.getQuery().toCharArray(); + for (int i = 0; i < temp.length; i++) { + if (temp[i] == '?') + noOfParams++; + } + return (noOfValues == noOfParams); + } else { + return !queryObject.getQuery().isEmpty(); + } + + } + + public static void setCassName(String cassName) { + MusicUtil.cassName = cassName; + } + + public static void setCassPwd(String cassPwd) { + MusicUtil.cassPwd = cassPwd; + } + + public static String convertToCQLDataType(DataType type, Object valueObj) { + + String value = ""; + switch (type.getName()) { + case UUID: + value = valueObj + ""; + break; + case TEXT: + case VARCHAR: + String valueString = valueObj + ""; + valueString = valueString.replace("'", "''"); + value = "'" + valueString + "'"; + break; + case MAP: { + Map<String, Object> otMap = (Map<String, Object>) valueObj; + value = "{" + jsonMaptoSqlString(otMap, ",") + "}"; + break; + } + default: + value = valueObj + ""; + break; + } + return value; + } + + /** + * + * @param colType + * @param valueObj + * @return + * @throws Exception + */ + public static Object convertToActualDataType(DataType colType, Object valueObj) { + String valueObjString = valueObj + ""; + switch (colType.getName()) { + case UUID: + return UUID.fromString(valueObjString); + case VARINT: + return BigInteger.valueOf(Long.parseLong(valueObjString)); + case BIGINT: + return Long.parseLong(valueObjString); + case INT: + return Integer.parseInt(valueObjString); + case FLOAT: + return Float.parseFloat(valueObjString); + case DOUBLE: + return Double.parseDouble(valueObjString); + case BOOLEAN: + return Boolean.parseBoolean(valueObjString); + case MAP: + return (Map<String, Object>) valueObj; + default: + return valueObjString; + } + } + + /** + * + * Utility function to parse json map into sql like string + * + * @param jMap + * @param lineDelimiter + * @return + */ + + public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) { + StringBuilder sqlString = new StringBuilder(); + int counter = 0; + for (Map.Entry<String, Object> entry : jMap.entrySet()) { + Object ot = entry.getValue(); + String value = ot + ""; + if (ot instanceof String) { + value = "'" + value.replace("'", "''") + "'"; + } + sqlString.append("'" + entry.getKey() + "':" + value); + if (counter != jMap.size() - 1) + sqlString.append(lineDelimiter); + counter = counter + 1; + } + return sqlString.toString(); + } + + public static Map<String, HashMap<String, Object>> setErrorResponse(MusicServiceException ex) { + Map<String, HashMap<String, Object>> results = new HashMap<>(); + HashMap<String, Object> tempMap = new HashMap<>(); + Map<String, Object> result = new HashMap<>(); + result.put("Error Description", ex.getMessage()); + tempMap.put("Error", result); + results.put("Result", tempMap); + return results; + } } |