diff options
author | Nelson,Thomas(tn1381)(arthurdent3) <tn1381@att.com> | 2019-01-29 15:55:37 -0500 |
---|---|---|
committer | Nelson,Thomas(tn1381)(arthurdent3) <tn1381@att.com> | 2019-01-29 16:05:01 -0500 |
commit | a27be9fdbbf2d271c9c5780ba70fe15a24dbdb63 (patch) | |
tree | 1fa631eae149ed6be33b636e7eac03dadbef64c3 /src/main/java/org/onap/music/main | |
parent | 95489883ce973e84267fcbcee685f1598d4bdd6e (diff) |
Push variuos changes
- Spring Boot
- Cadi
- Cassandra Locking
Change-Id: Ie9882f81f0ca141bdb7862cdabf978481fcd7c4a
Issue-ID: MUSIC-296,MUSIC-272
Signed-off-by: Nelson,Thomas(tn1381)(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 | 140 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/CronJobManager.java | 55 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/MusicCore.java | 1028 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/MusicDigest.java | 1 | ||||
-rwxr-xr-x | src/main/java/org/onap/music/main/MusicUtil.java | 409 | ||||
-rwxr-xr-x | src/main/java/org/onap/music/main/PropertiesListener.java | 112 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/PropertiesLoader.java | 192 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/ResultType.java | 7 | ||||
-rw-r--r-- | src/main/java/org/onap/music/main/ReturnType.java | 1 |
9 files changed, 815 insertions, 1130 deletions
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java index 18cf90d9..9c975191 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/main/CachingUtil.java @@ -21,6 +21,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; import java.util.Calendar; @@ -29,10 +30,16 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; + 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.commons.jcs.engine.CompositeCacheAttributes; +import org.apache.commons.jcs.engine.ElementAttributes; +import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes; +import org.apache.commons.jcs.engine.behavior.IElementAttributes; import org.mindrot.jbcrypt.BCrypt; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; @@ -40,8 +47,10 @@ 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 org.onap.music.datastore.jsonobjects.JsonCallback; +import org.onap.music.service.impl.MusicZKCore; + import com.datastax.driver.core.DataType; +import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.exceptions.InvalidQueryException; @@ -63,36 +72,50 @@ public class CachingUtil implements Runnable { private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache"); private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache"); private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache"); - private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache"); - private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList"); + private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("eternalCache"); private static Map<String, Number> userAttempts = new HashMap<>(); private static Map<String, Calendar> lastFailedTime = new HashMap<>(); + private static CacheAccess<String, PreparedStatement> queryBank = JCS.getInstance("statementBank"); + private static CacheAccess<String, String> adminUserCache = JCS.getInstance("adminUserCache"); + + public static CacheAccess<String, String> getAdminUserCache() { + return adminUserCache; + } + + public static void updateAdminUserCache(String authorization,String userId) { + adminUserCache.put(authorization,userId); + } + + + public static void updateStatementBank(String query,PreparedStatement statement) { + queryBank.put(query, statement); + } + + public static void resetStatementBank() { + queryBank.clear(); + } + + public static CacheAccess<String, PreparedStatement> getStatementBank() { + return queryBank; + } private static final String USERNAME="username"; private static final String PASSWORD="password"; + public boolean isCacheRefreshNeeded() { if (aafCache.get("initBlankMap") == null) return true; return false; } - public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) { - logger.info("updateCallBackCache: updating cache....."); - callBackCache.put(appName, jsonCallBack); - } - - public static JsonCallback getCallBackCache(String appName) { - return callBackCache.get(appName); - } - public static void updateCallbackNotifyList(List<String> notifyList) { - logger.info("callbackNotifyList: updating cache....."); - callbackNotifyList.put("callbackNotify", notifyList); + logger.info("callbackNotifyList: updating cache....."); + callbackNotifyList.put("callbackNotify", notifyList); } public static List<String> getCallbackNotifyList() { - return callbackNotifyList.get("callbackNotify"); + return callbackNotifyList.get("callbackNotify"); } public void initializeMusicCache() { @@ -110,6 +133,7 @@ public class CachingUtil implements Runnable { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false)); } catch (Exception e1) { logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + e1.printStackTrace(); } ResultSet rs = MusicCore.get(pQuery); Iterator<Row> it = rs.iterator(); @@ -134,6 +158,7 @@ public class CachingUtil implements Runnable { } catch (Exception e) { 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(); } } @@ -141,12 +166,12 @@ public class CachingUtil implements Runnable { @Override public void run() { - logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache..."); + 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); - } + 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, @@ -154,9 +179,9 @@ public class CachingUtil implements Runnable { if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) { if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) { - logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace."); + logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace."); } else if (aafCache.get(nameSpace).get(userId).equals(password)) { - logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value.."); + logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value.."); // reset invalid attempts to 0 userAttempts.put(nameSpace, 0); return true; @@ -174,7 +199,7 @@ public class CachingUtil implements Runnable { logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt."); userAttempts.put(nameSpace, 0); } else { - logger.info(EELFLoggerDelegate.applicationLogger,"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."); } } @@ -183,15 +208,21 @@ public class CachingUtil implements Runnable { } } - boolean responseObj = triggerAAF(nameSpace, userId, password); + boolean responseObj = false; + try { + responseObj = triggerAAF(nameSpace, userId, password); + }catch (Exception ex) { + logger.info("Exception while trigger aaf"); + logger.info("Exception: " + ex.getMessage()); + throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage()); + } if (responseObj) { - //if (responseObj.getNs().get(0).getAdmin().contains(userId)) { - Map<String, String> map = new HashMap<>(); + logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace); + Map<String, String> map = new HashMap<>(); map.put(userId, password); aafCache.put(nameSpace, map); - CachingUtil.updateMusicCache(keySpace, nameSpace); - return true; - //} + musicCache.put(keySpace, nameSpace); + return true; } logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated"); return false; @@ -199,8 +230,9 @@ public class CachingUtil implements Runnable { private static boolean triggerAAF(String nameSpace, String userId, String password) throws Exception { + logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization"); if (MusicUtil.getAafEndpointUrl() == null) { - logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); throw new Exception("AAF endpoint is not set. Please specify in the properties file."); } Client client = Client.create(); @@ -215,6 +247,7 @@ public class CachingUtil implements Runnable { ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) .header("Authorization", "Basic " + base64Creds) .header("content-type", "application/json").get(ClientResponse.class); + logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString()); if (response.getStatus() != 200) { if (userAttempts.get(nameSpace) == null) userAttempts.put(nameSpace, 0); @@ -245,6 +278,14 @@ public class CachingUtil implements Runnable { musicCache.put(keyspace, nameSpace); } + public static void updateCadiCache(String user, String keyspace) { + musicCache.put(user, keyspace); + } + + public static String getKSFromCadiCache(String user) { + return musicCache.get(user); + } + public static void updateMusicValidateCache(String nameSpace, String userId, String password) { logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId); Map<String, String> map = new HashMap<>(); @@ -275,7 +316,8 @@ public class CachingUtil implements Runnable { if(isAAF != null) appNameCache.put(namespace, isAAF); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + e.printStackTrace(); } } return isAAF; @@ -293,6 +335,7 @@ public class CachingUtil implements Runnable { uuid = rs.getUUID("uuid").toString(); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage()); + e.printStackTrace(); } } return uuid; @@ -308,7 +351,8 @@ public class CachingUtil implements Runnable { try { appName = rs.getString("application_name"); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + e.printStackTrace(); } return appName; } @@ -334,8 +378,8 @@ public class CachingUtil implements Runnable { 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(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - logger.error(EELFLoggerDelegate.errorLogger,"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; @@ -344,19 +388,20 @@ public class CachingUtil implements Runnable { queryObject.appendQueryString( "select * from admin.keyspace_master where application_name = ? allow filtering"); try { - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); } catch(Exception e) { - resultMap.put("Exception", + resultMap.put("Exception", "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage()); - return resultMap; + return resultMap; } Row rs = null; - try { - rs = MusicCore.get(queryObject).one(); - } catch (MusicServiceException e) { - // TODO Auto-generated catch block - resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage()); - return resultMap; + 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; } catch (InvalidQueryException e) { logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage()); resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured."); @@ -366,7 +411,7 @@ public class CachingUtil implements Runnable { 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)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) { + if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(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); @@ -398,13 +443,14 @@ public class CachingUtil implements Runnable { try { queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace)); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + e.printStackTrace(); } Row rs = null; try { rs = MusicCore.get(queryObject).one(); } catch (MusicServiceException e) { - resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage()); + e.printStackTrace(); + resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage()); return resultMap; } if(rs == null) { @@ -440,7 +486,7 @@ public class CachingUtil implements Runnable { try { MusicCore.nonKeyRelatedPut(pQuery, "eventual"); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB"); + e.printStackTrace(); } } } diff --git a/src/main/java/org/onap/music/main/CronJobManager.java b/src/main/java/org/onap/music/main/CronJobManager.java index 504ff20e..9cd9f33f 100644 --- a/src/main/java/org/onap/music/main/CronJobManager.java +++ b/src/main/java/org/onap/music/main/CronJobManager.java @@ -19,8 +19,11 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Iterator; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -31,48 +34,46 @@ import javax.servlet.annotation.WebListener; import org.onap.music.datastore.PreparedQueryObject; 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.MusicLockingException; import org.onap.music.exceptions.MusicServiceException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; -//@WebListener -public class CronJobManager implements ServletContextListener { +@Component +public class CronJobManager { - private ScheduledExecutorService scheduler; private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronJobManager.class); - @Override - public void contextInitialized(ServletContextEvent event) { - scheduler = Executors.newSingleThreadScheduledExecutor(); - scheduler.scheduleAtFixedRate(new CachingUtil(), 0, 24, TimeUnit.HOURS); + private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + + + @Scheduled(cron = "0 0 0 * * ?") + public void scheduleTaskWithFixedRate() { + logger.info("Executing cronjob to cleanup locks..", dateTimeFormatter.format(LocalDateTime.now()) ); + deleteLocksFromDB(); + } + + public void deleteLocksFromDB() { PreparedQueryObject pQuery = new PreparedQueryObject(); String consistency = MusicUtil.EVENTUAL; pQuery.appendQueryString("CREATE TABLE IF NOT EXISTS admin.locks ( lock_id text PRIMARY KEY, ctime text)"); try { ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + if ( result.equals(ResultType.FAILURE)) { + logger.error(EELFLoggerDelegate.errorLogger,"Error creating Admin.locks table.",AppMessages.QUERYERROR,ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR); + } } catch (MusicServiceException e1) { - logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),ErrorSeverity.ERROR); + logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(),AppMessages.QUERYERROR,ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR); + e1.printStackTrace(); } - - //Zookeeper cleanup - scheduler.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - deleteLocksFromDB(); - } - } , 0, 24, TimeUnit.HOURS); - } - - @Override - public void contextDestroyed(ServletContextEvent event) { - scheduler.shutdownNow(); - } - - public void deleteLocksFromDB() { - PreparedQueryObject pQuery = new PreparedQueryObject(); + + pQuery = new PreparedQueryObject(); pQuery.appendQueryString( "select * from admin.locks"); try { @@ -101,8 +102,8 @@ public class CronJobManager implements ServletContextListener { CachingUtil.deleteKeysFromDB(deleteKeys.toString()); } } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),ErrorSeverity.ERROR); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),AppMessages.CACHEERROR,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + e.printStackTrace(); } } - } diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java index 98696bab..221e680b 100644 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ b/src/main/java/org/onap/music/main/MusicCore.java @@ -7,996 +7,156 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ============LICENSE_END============================================= * ==================================================================== */ -package org.onap.music.main; +package org.onap.music.main; -import java.io.StringWriter; -import java.util.HashMap; +import java.util.List; import java.util.Map; -import java.util.StringTokenizer; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.KeeperException.NoNodeException; -import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.Condition; 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.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; 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 org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; -import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.TableMetadata; -/** - * This class ..... - * - * - */ public class MusicCore { - public static MusicLockingService mLockHandle = null; - public static MusicDataStore mDstoreHandle = null; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); - - public static class Condition { - Map<String, Object> conditions; - PreparedQueryObject selectQueryForTheRow; - - public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) { - this.conditions = conditions; - this.selectQueryForTheRow = selectQueryForTheRow; - } - - public boolean testCondition() throws Exception { - // first generate the row - ResultSet results = quorumGet(selectQueryForTheRow); - Row row = null; - if(results != null) { - row = results.one(); - } - return getDSHandle().doesRowSatisfyCondition(row, conditions); - } - } - - - public static MusicLockingService getLockingServiceHandle() throws MusicLockingException { - logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); - long start = System.currentTimeMillis(); - - if (mLockHandle == null) { - try { - mLockHandle = new MusicLockingService(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - throw new MusicLockingException("Failed to aquire Locl store handle " + e); - } - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms"); - return mLockHandle; - } - - /** - * - * @param remoteIp - * @return - */ - public static MusicDataStore getDSHandle(String remoteIp) { - 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(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); - return mDstoreHandle; - } - - /** - * - * @return - * @throws MusicServiceException - */ - public static MusicDataStore getDSHandle() throws MusicServiceException { - logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); - long start = System.currentTimeMillis(); - if (mDstoreHandle == null) { - // Quick Fix - Best to put this into every call to getDSHandle? - if (! "localhost".equals(MusicUtil.getMyCassaHost())) { - mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost()); - } else { - mDstoreHandle = new MusicDataStore(); - } - } - if(mDstoreHandle.getSession() == null) { - String message = "Connection to Cassandra has not been enstablished." - + " Please check connection properites and reboot."; - logger.info(EELFLoggerDelegate.applicationLogger, message); - throw new MusicServiceException(message); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); - return mDstoreHandle; - } - - public static String createLockReference(String 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(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.CREATELOCK+lockName,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms"); - return lockId; - } - - /** - * - * @param key - * @return - */ - public static boolean isTableOrKeySpaceLock(String key) { - String[] splitString = key.split("\\."); - if (splitString.length > 2) - return false; - else - return true; - } - + private static boolean unitTestRun=true; + + private static MusicCoreService musicCore = MusicUtil.getMusicCoreService(); + public static CassaLockStore mLockHandle; + + /** - * - * @param key + * Acquire lock + * @param fullyQualifiedKey DO NOT RELY ON THIS KEY WORKING. INCLUDE THE KEY IN THE LOCKID. + * @param lockId - the full lock id (key + lockRef) * @return + * @throws MusicLockingException + * @throws MusicQueryException + * @throws MusicServiceException */ - public static MusicLockState getMusicLockState(String key) { - long start = System.currentTimeMillis(); - try { - String[] splitString = key.split("\\."); - String keyspaceName = splitString[0]; - String tableName = splitString[1]; - String primaryKey = splitString[2]; - MusicLockState mls; - String lockName = keyspaceName + "." + tableName + "." + primaryKey; - mls = getLockingServiceHandle().getLockState(lockName); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms"); - return mls; - } catch (NullPointerException | MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - return null; - } - - public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod) { - try { - long start = System.currentTimeMillis(); - /* check if the current lock has exceeded its lease and if yes, release that lock */ - MusicLockState mls = getMusicLockState(key); - if (mls != null) { - if (mls.getLockStatus().equals(LockStatus.LOCKED)) { - 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(EELFLoggerDelegate.applicationLogger,"Lock period " + currentLockPeriod - + " has exceeded lease period " + currentLeasePeriod); - boolean voluntaryRelease = false; - String currentLockHolder = mls.getLockHolder(); - mls = releaseLock(currentLockHolder, voluntaryRelease); - } - } - } else { - logger.error(EELFLoggerDelegate.errorLogger,key, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - /* - * 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).getResult() == ResultType.SUCCESS) { - mls = getMusicLockState(key);// get latest state - if ( mls == null ) { - logger.info(EELFLoggerDelegate.applicationLogger,"Music Lock State is null"); - return new ReturnType(ResultType.FAILURE, "Could not acquire lock, Lock State is null"); - } - if (mls.getLeaseStartTime() == -1) {// set it again only if it is not set already - mls.setLeaseStartTime(System.currentTimeMillis()); - mls.setLeasePeriod(leasePeriod); - getLockingServiceHandle().setLockState(key, mls); - } - long end = System.currentTimeMillis(); - 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(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(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - - String exceptionAsString = sw.toString(); - return new ReturnType(ResultType.FAILURE, - "Exception thrown in acquireLockWithLease:\n" + exceptionAsString); - } + public static ReturnType acquireLock(String fullyQualifiedKey, String lockId) + throws MusicLockingException, MusicQueryException, MusicServiceException { + return musicCore.acquireLock(fullyQualifiedKey, lockId); } - - public static ReturnType acquireLock(String key, String lockId) throws MusicLockingException { - /* - * 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 - * false. - */ - Boolean result = false; - try { - result = getLockingServiceHandle().isMyTurn(lockId); - } catch (MusicLockingException e2) { - logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId + " " + e2); - throw new MusicLockingException(); - } - if (!result) { - 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,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - throw new MusicLockingException(); - } - 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)) { - 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, - // then return false - MusicLockState currentMls = null; - MusicLockState newMls = null; - try { - currentMls = getMusicLockState(key); - String currentLockHolder = null; - if(currentMls != null) { currentLockHolder = currentMls.getLockHolder(); }; - if (lockId.equals(currentLockHolder)) { - 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(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - - // change status to "being locked". This state transition is necessary to ensure syncing - // before granting the lock - String lockHolder = null; - boolean needToSyncQuorum = false; - if (currentMls != null) - needToSyncQuorum = currentMls.isNeedToSyncQuorum(); - - - newMls = new MusicLockState(MusicLockState.LockStatus.BEING_LOCKED, lockHolder, - needToSyncQuorum); - try { - getLockingServiceHandle().setLockState(key, newMls); - } catch (MusicLockingException e1) { - logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - 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(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!"); - try { - syncQuorum(key); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + e); - } - } - - // change status to locked - lockHolder = lockId; - needToSyncQuorum = false; - newMls = new MusicLockState(MusicLockState.LockStatus.LOCKED, lockHolder, needToSyncQuorum); - try { - getLockingServiceHandle().setLockState(key, newMls); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref " - + lockId + " as holder"); - - return new ReturnType(result?ResultType.SUCCESS:ResultType.FAILURE, "Set lock state to locked and assigned a lock holder"); + + public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException { + return musicCore.acquireLockWithLease(key, lockId, leasePeriod); } - - - - /** - * - * @param keyspaceName - * @param kspObject - * @return - * @throws Exception - */ - public boolean createKeyspace(String keyspaceName, JsonKeySpace kspObject) throws Exception { - return true; + + public static String createLockReference(String fullyQualifiedKey) { + return musicCore.createLockReference(fullyQualifiedKey); } - - - private static void syncQuorum(String key) throws Exception { - logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); - String[] splitString = key.split("\\."); - String keyspaceName = splitString[0]; - String tableName = splitString[1]; - String primaryKeyValue = splitString[2]; - PreparedQueryObject selectQuery = new PreparedQueryObject(); - PreparedQueryObject updateQuery = new PreparedQueryObject(); - - // get the primary key d - TableMetadata tableInfo = returnColumnMetadata(keyspaceName, tableName); - String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();// we only support single - // primary key - DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); - Object cqlFormattedPrimaryKeyValue = - MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue); - - // get the row of data from a quorum - selectQuery.appendQueryString("SELECT * FROM " + keyspaceName + "." + tableName + " WHERE " - + primaryKeyName + "= ?" + ";"); - selectQuery.addValue(cqlFormattedPrimaryKeyValue); - ResultSet results = null; - try { - results = getDSHandle().executeCriticalGet(selectQuery); - // write it back to a quorum - Row row = results.one(); - ColumnDefinitions colInfo = row.getColumnDefinitions(); - int totalColumns = colInfo.size(); - int counter = 1; - StringBuilder fieldValueString = new StringBuilder(""); - for (Definition definition : colInfo) { - String colName = definition.getName(); - if (colName.equals(primaryKeyName)) - continue; - DataType colType = definition.getType(); - Object valueObj = getDSHandle().getColValue(row, colName, colType); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); - fieldValueString.append(colName + " = ?"); - updateQuery.addValue(valueString); - if (counter != (totalColumns - 1)) - fieldValueString.append(","); - counter = counter + 1; - } - updateQuery.appendQueryString("UPDATE " + keyspaceName + "." + tableName + " SET " - + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";"); - updateQuery.addValue(cqlFormattedPrimaryKeyValue); - - getDSHandle().executePut(updateQuery, "critical"); - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR); - } + + public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, + String consistency) throws MusicServiceException { + return musicCore.createTable(keyspace, table, tableQueryObject, consistency); } - - - - - /** - * - * @param query - * @return ResultSet - */ + public static ResultSet quorumGet(PreparedQueryObject query) { - ResultSet results = null; - try { - results = getDSHandle().executeCriticalGet(query); - } catch (MusicServiceException | MusicQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR); - - } - return results; - + return musicCore.quorumGet(query); } - - /** - * - * @param results - * @return - * @throws MusicServiceException - */ - public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException { - return getDSHandle().marshalData(results); - } - - /** - * - * @param lockName - * @return - */ - public static String whoseTurnIsIt(String lockName) { - - try { - return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + ""; - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - return null; - - - } - - /** - * - * @param lockId - * @return - */ - public static String getLockNameFromId(String lockId) { - StringTokenizer st = new StringTokenizer(lockId); - return st.nextToken("$"); + + public static String whoseTurnIsIt(String fullyQualifiedKey) { + return musicCore.whoseTurnIsIt(fullyQualifiedKey); } - + public static void destroyLockRef(String lockId) { - long start = System.currentTimeMillis(); - try { - getLockingServiceHandle().unlockAndDeleteId(lockId); - } catch (MusicLockingException | NoNodeException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); - } - - public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) { - long start = System.currentTimeMillis(); - try { - getLockingServiceHandle().unlockAndDeleteId(lockId); - } catch (MusicLockingException e1) { - logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } catch (KeeperException.NoNodeException nne) { - logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne); - MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed."); - return mls; - } - String lockName = getLockNameFromId(lockId); - MusicLockState mls; - String lockHolder = null; - if (voluntaryRelease) { - mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder); - 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(EELFLoggerDelegate.applicationLogger,"In unlock: lock forcibly released for " + lockId); - } - try { - getLockingServiceHandle().setLockState(lockName, mls); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms"); - return mls; + musicCore.destroyLockRef(lockId); } - public static void voluntaryReleaseLock(String lockId) throws MusicLockingException{ - try { - getLockingServiceHandle().unlockAndDeleteId(lockId); - } catch (KeeperException.NoNodeException e) { - // ??? No way - } - } - - /** - * - * @param lockName - * @throws MusicLockingException - */ - public static void deleteLock(String lockName) throws MusicLockingException { - long start = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Deleting lock for " + lockName); - try { - getLockingServiceHandle().deleteLock("/" + lockName); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DELTELOCK+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - throw new MusicLockingException(e.getMessage()); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms"); + public static ReturnType eventualPut(PreparedQueryObject queryObject) { + return musicCore.eventualPut(queryObject); } - - - - /** - * - * @param keyspace - * @param tablename - * @return - * @throws MusicServiceException - */ - public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { - return getDSHandle().returnColumnMetadata(keyspace, tablename); + + public static ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace, + String tablename,String primaryKey) { + return musicCore.eventualPut_nb(queryObject, keyspace, tablename, primaryKey); } - - - /** - * - * @param nodeName - */ - public static void pureZkCreate(String nodeName) { - try { - getLockingServiceHandle().getzkLockHandle().createNode(nodeName); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } + + public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) { + return musicCore.criticalPut(keyspace, table, primaryKeyValue, queryObject, lockReference, conditionInfo); } - - /** - * - * @param nodeName - * @param data - */ - public static void pureZkWrite(String nodeName, byte[] data) { - long start = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Performing zookeeper write to " + nodeName); - try { - getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); + + public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) + throws MusicServiceException { + return musicCore.nonKeyRelatedPut(queryObject, consistency); } - - /** - * - * @param nodeName - * @return - */ - public static byte[] pureZkRead(String nodeName) { - long start = System.currentTimeMillis(); - byte[] data = null; - try { - data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName); - } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); - } - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); - return data; + + public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException{ + return musicCore.get(queryObject); } - - - - // Prepared Query Additions. - - /** - * - * @param keyspaceName - * @param tableName - * @param primaryKey - * @param queryObject - * @return ReturnType - * @throws MusicServiceException - */ - public static ReturnType eventualPut(PreparedQueryObject queryObject) { - boolean result = false; - try { - result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); - } catch (MusicServiceException | MusicQueryException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); - return new ReturnType(ResultType.FAILURE, ex.getMessage()); - } - if (result) { - return new ReturnType(ResultType.SUCCESS, "Success"); - } else { - return new ReturnType(ResultType.FAILURE, "Failure"); - } + + public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, + PreparedQueryObject queryObject, String lockReference) throws MusicServiceException { + return musicCore.criticalGet(keyspace, table, primaryKeyValue, queryObject,lockReference); } - - /** - * - * @param keyspaceName - * @param tableName - * @param primaryKey - * @param queryObject - * @param lockId - * @return - */ - public static ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, String lockId, Condition conditionInfo) { - long start = System.currentTimeMillis(); - - try { - MusicLockState mls = getLockingServiceHandle() - .getLockState(keyspaceName + "." + tableName + "." + primaryKey); - if (mls.getLockHolder().equals(lockId) == true) { - if (conditionInfo != null) - try { - if (conditionInfo.testCondition() == false) - return new ReturnType(ResultType.FAILURE, - "Lock acquired but the condition is not true"); - } catch (Exception e) { - return new ReturnType(ResultType.FAILURE, - "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" - + e.getMessage()); - } - getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); - long end = System.currentTimeMillis(); - 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 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()); - } - + + public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException, + MusicQueryException,MusicServiceException { + return musicCore.atomicPut(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); } - - /** - * - * @param queryObject - * @param consistency - * @return Boolean Indicates success or failure - * @throws MusicServiceException - * - * - */ - public static ResultType 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(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - throw new MusicServiceException(ex.getMessage()); - } - return result?ResultType.SUCCESS:ResultType.FAILURE; + + public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { + return musicCore.atomicGet(keyspaceName, tableName, primaryKey, queryObject); } - - /** - * This method performs DDL operation on cassandra. - * - * @param queryObject query object containing prepared query and values - * @return ResultSet - * @throws MusicServiceException - */ - public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { - ResultSet results = null; - try { - results = getDSHandle().executeEventualGet(queryObject); - } catch (MusicQueryException | MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); - throw new MusicServiceException(e.getMessage()); - } - return results; + + public static List<String> getLockQueue(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + return musicCore.getLockQueue(fullyQualifiedKey); } - public static String getMyHostId() { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("SELECT HOST_ID FROM SYSTEM.LOCAL"); - ResultSet rs = null; - try { - rs = getDSHandle().executeEventualGet(pQuery); - Row row = rs.one(); - return (row == null) ? "UNKNOWN" : row.getUUID("HOST_ID").toString(); - } catch (Exception e) { - e.printStackTrace(); - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); - } - logger.error(EELFLoggerDelegate.errorLogger, "Some issue during MusicCore.getMyHostId"); - return "UNKNOW"; - } - - /** - * This method performs DDL operations on cassandra, if the the resource is available. Lock ID - * is used to check if the resource is free. - * - * @param keyspaceName name of the keyspace - * @param tableName name of the table - * @param primaryKey primary key value - * @param queryObject query object containing prepared query and values - * @param lockId lock ID to check if the resource is free to perform the operation. - * @return ResultSet - */ - public static ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, String lockId) throws MusicServiceException { - ResultSet results = null; - try { - MusicLockState mls = getLockingServiceHandle() - .getLockState(keyspaceName + "." + tableName + "." + primaryKey); - if (mls.getLockHolder().equals(lockId)) { - results = getDSHandle().executeCriticalGet(queryObject); - } else - throw new MusicServiceException("YOU DO NOT HAVE THE LOCK"); - } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - } - return results; + public static long getLockQueueSize(String fullyQualifiedKey) + throws MusicServiceException, MusicQueryException, MusicLockingException { + return musicCore.getLockQueueSize(fullyQualifiedKey); } - /** - * This method performs DML operation on cassandra, when the lock of the dd is acquired. - * - * @param keyspaceName name of the keyspace - * @param tableName name of the table - * @param primaryKey primary key value - * @param queryObject query object containing prepared query and values - * @return ReturnType - * @throws MusicLockingException - */ - public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { - - long start = System.currentTimeMillis(); - String key = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(key); - long lockCreationTime = System.currentTimeMillis(); - ReturnType lockAcqResult = acquireLock(key, lockId); - long lockAcqTime = System.currentTimeMillis(); - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); - ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, - queryObject, lockId, conditionInfo); - long criticalPutTime = System.currentTimeMillis(); - voluntaryReleaseLock(lockId); - long lockDeleteTime = System.currentTimeMillis(); - String timingInfo = "|lock creation time:" + (lockCreationTime - start) - + "|lock accquire time:" + (lockAcqTime - lockCreationTime) - + "|critical put time:" + (criticalPutTime - lockAcqTime) - + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|"; - criticalPutResult.setTimingInfo(timingInfo); - return criticalPutResult; - } else { - logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); - destroyLockRef(lockId); - return lockAcqResult; - } + public static void deleteLock(String lockName) throws MusicLockingException { + musicCore.deleteLock(lockName); } - /** - * this function is mainly for the benchmarks to see the effect of lock deletion. - * - * @param keyspaceName - * @param tableName - * @param primaryKey - * @param queryObject - * @param conditionInfo - * @return - * @throws MusicLockingException - */ public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, - String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { - - long start = System.currentTimeMillis(); - String key = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(key); - long lockCreationTime = System.currentTimeMillis(); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = acquireLock(key, lockId); - long lockAcqTime = System.currentTimeMillis(); - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); - ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, - queryObject, lockId, conditionInfo); - long criticalPutTime = System.currentTimeMillis(); - deleteLock(key); - long lockDeleteTime = System.currentTimeMillis(); - String timingInfo = "|lock creation time:" + (lockCreationTime - start) - + "|lock accquire time:" + (lockAcqTime - lockCreationTime) - + "|critical put time:" + (criticalPutTime - lockAcqTime) - + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|"; - criticalPutResult.setTimingInfo(timingInfo); - return criticalPutResult; - } else { - logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); - deleteLock(key); - return lockAcqResult; - } + String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { + return musicCore.atomicPutWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject, conditionInfo); } - - - - /** - * This method performs DDL operation on cassasndra, when the lock for the resource is acquired. - * - * @param keyspaceName name of the keyspace - * @param tableName name of the table - * @param primaryKey primary key value - * @param queryObject query object containing prepared query and values - * @return ResultSet - * @throws MusicServiceException - * @throws MusicLockingException - */ - public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { - String key = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(key); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = acquireLock(key, lockId); - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); - ResultSet result = - criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId); - voluntaryReleaseLock(lockId); - return result; - } else { - destroyLockRef(lockId); - logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); - return null; - } + public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { + return musicCore.atomicGetWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject); } - - public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey, - PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException { - String key = keyspaceName + "." + tableName + "." + primaryKey; - String lockId = createLockReference(key); - long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - - ReturnType lockAcqResult = acquireLock(key, lockId); - - if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId); - ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId); - deleteLock(key); - return result; - } else { - deleteLock(key); - logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId); - return null; - } - } - - - - /** - * authenticate user logic - * - * @param nameSpace - * @param userId - * @param password - * @param keyspace - * @param aid - * @param operation - * @return - * @throws Exception - */ - public static Map<String, Object> autheticateUser(String nameSpace, String userId, - String password, String keyspace, String aid, String operation) - throws Exception { - Map<String, Object> resultMap = new HashMap<>(); - String uuid = null; - resultMap = CachingUtil.validateRequest(nameSpace, userId, password, keyspace, aid, - operation); - if (!resultMap.isEmpty()) - return resultMap; - String isAAFApp = null; - try { - isAAFApp= CachingUtil.isAAFApplication(nameSpace); - } catch(MusicServiceException e) { - resultMap.put("Exception", e.getMessage()); - return resultMap; - } - if(isAAFApp == null) { - resultMap.put("Exception", "Namespace: "+nameSpace+" doesn't exist. Please make sure ns(appName)" - + " is correct and Application is onboarded."); - return resultMap; - } - boolean isAAF = Boolean.valueOf(isAAFApp); - if (userId == null || password == null) { - 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", - "UserId and Password are mandatory for the operation " + operation); - return resultMap; - } - if(!isAAF && !(operation.equals("createKeySpace"))) { - resultMap = CachingUtil.authenticateAIDUser(nameSpace, userId, password, 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(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace); - resultMap.put("Exception", e.getMessage()); - } - if (!isValid) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - resultMap.put("Exception", "User not authenticated..."); - } - if (!resultMap.isEmpty()) - return resultMap; - } - - if (operation.equals("createKeySpace")) { - 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"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), nameSpace)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - - try { - Row rs = MusicCore.get(pQuery).one(); - uuid = rs.getUUID("uuid").toString(); - resultMap.put("uuid", "existing"); - } catch (Exception e) { - logger.info(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID."); - uuid = CachingUtil.generateUUID(); - resultMap.put("uuid", "new"); - } - resultMap.put("aid", uuid); - } + public static Map<String, Object> validateLock(String lockName) { + return musicCore.validateLock(lockName); + } - return resultMap; + public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) { + return musicCore.releaseLock(lockId, voluntaryRelease); } - /** - * @param lockName - * @return - */ - public static Map<String, Object> validateLock(String lockName) { - Map<String, Object> resultMap = new HashMap<>(); - String[] locks = lockName.split("\\."); - if(locks.length < 3) { - resultMap.put("Exception", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey"); - return resultMap; - } - String keyspace= locks[0]; - if(keyspace.startsWith("$")) - keyspace = keyspace.substring(1); - resultMap.put("keyspace",keyspace); - return resultMap; - } -} + +}
\ No newline at end of file diff --git a/src/main/java/org/onap/music/main/MusicDigest.java b/src/main/java/org/onap/music/main/MusicDigest.java index 893cb51f..d05969e3 100644 --- a/src/main/java/org/onap/music/main/MusicDigest.java +++ b/src/main/java/org/onap/music/main/MusicDigest.java @@ -19,6 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; /** diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index d2e8591c..805f459f 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -9,18 +9,19 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; import java.io.File; @@ -45,24 +46,34 @@ import javax.ws.rs.core.Response.ResponseBuilder; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; +import org.onap.music.service.impl.MusicZKCore; +import com.datastax.driver.core.ConsistencyLevel; import com.datastax.driver.core.DataType; import com.sun.jersey.core.util.Base64; /** * @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. - * + * */ public class MusicUtil { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - + public static final String ATOMIC = "atomic"; public static final String EVENTUAL = "eventual"; public static final String CRITICAL = "critical"; + public static final String EVENTUAL_NB = "eventual_nb"; + public static final String ALL = "all"; + public static final String QUORUM = "quorum"; + public static final String ONE = "one"; public static final String ATOMICDELETELOCK = "atomic_delete_lock"; public static final String DEFAULTKEYSPACENAME = "TBD"; private static final String XLATESTVERSION = "X-latestVersion"; @@ -74,12 +85,14 @@ public class MusicUtil { public static final String UPSERT = "upsert"; public static final String USERID = "userId"; public static final String PASSWORD = "password"; + public static final String CASSANDRA = "cassandra"; + public static final String ZOOKEEPER = "zookeeper"; - public static final String AUTHORIZATION = "Authorization"; + public static final String AUTHORIZATION = "Authorization"; private static final String LOCALHOST = "localhost"; private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties"; - + private static int myId = 0; private static ArrayList<String> allIds = new ArrayList<>(); private static String publicIp = ""; @@ -90,6 +103,9 @@ public class MusicUtil { private static int cassandraPort = 9042; private static int notifytimeout = 30000; private static int notifyinterval = 5000; + private static int cacheObjectMaxLife = -1; + private static String lockUsing = MusicUtil.CASSANDRA; + private static boolean isCadi = false; private static boolean debug = true; private static String version = "2.3.0"; @@ -98,31 +114,118 @@ public class MusicUtil { 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","cassandra.port", "notify.timeout", "notify.interval" }; + "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","admin.username","admin.password","aaf.admin.url", + "music.namespace","admin.aaf.role","cassandra.port","lock.using"}; + private static final String[] cosistencyLevel = new String[] { + "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO","THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"}; + private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>(); + static { + consistencyName.put("ONE",ConsistencyLevel.ONE); + consistencyName.put("TWO",ConsistencyLevel.TWO); + consistencyName.put("THREE",ConsistencyLevel.THREE); + consistencyName.put("SERIAL",ConsistencyLevel.SERIAL); + consistencyName.put("ALL",ConsistencyLevel.ALL); + consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM); + consistencyName.put("QUORUM",ConsistencyLevel.QUORUM); + consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM); + consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE); + consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL); + } private static String cassName = "cassandra"; private static String cassPwd; private static String aafEndpointUrl = null; - public static final ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>(); + public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>(); + private static String adminId = "username"; + private static String adminPass= "password"; + private static String aafAdminUrl= null; + private static String musicNamespace= "com.att.music.api"; + private static String adminAafRole= "com.att.music.api.admin_api"; + + public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM + + public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050) + + public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day + + + public static String getLockUsing() { + return lockUsing; + } + + + public static void setLockUsing(String lockUsing) { + MusicUtil.lockUsing = lockUsing; + } + + public static String getAafAdminUrl() { + return aafAdminUrl; + } + + + public static void setAafAdminUrl(String aafAdminUrl) { + MusicUtil.aafAdminUrl = aafAdminUrl; + } + + + public static String getMusicNamespace() { + return musicNamespace; + } + + + public static void setMusicNamespace(String musicNamespace) { + MusicUtil.musicNamespace = musicNamespace; + } + + + public static String getAdminAafRole() { + return adminAafRole; + } + + + public static void setAdminAafRole(String adminAafRole) { + MusicUtil.adminAafRole = adminAafRole; + } + + + + public static String getAdminId() { + return adminId; + } + + + public static void setAdminId(String adminId) { + MusicUtil.adminId = adminId; + } + + + public static String getAdminPass() { + return adminPass; + } + + public static void setAdminPass(String adminPass) { + MusicUtil.adminPass = adminPass; + } + private MusicUtil() { throw new IllegalStateException("Utility Class"); } /** - * + * * @return cassandra port */ public static int getCassandraPort() { - return cassandraPort; - } + return cassandraPort; + } /** * set cassandra port * @param cassandraPort */ - public static void setCassandraPort(int cassandraPort) { - MusicUtil.cassandraPort = cassandraPort; - } + public static void setCassandraPort(int cassandraPort) { + MusicUtil.cassandraPort = cassandraPort; + } /** * @return the cassName */ @@ -145,7 +248,7 @@ public class MusicUtil { } /** - * + * * @param aafEndpointUrl */ public static void setAafEndpointUrl(String aafEndpointUrl) { @@ -153,7 +256,7 @@ public class MusicUtil { } /** - * + * * @return */ public static int getMyId() { @@ -161,7 +264,7 @@ public class MusicUtil { } /** - * + * * @param myId */ public static void setMyId(int myId) { @@ -169,7 +272,7 @@ public class MusicUtil { } /** - * + * * @return */ public static List<String> getAllIds() { @@ -177,7 +280,7 @@ public class MusicUtil { } /** - * + * * @param allIds */ public static void setAllIds(List<String> allIds) { @@ -185,7 +288,7 @@ public class MusicUtil { } /** - * + * * @return */ public static String getPublicIp() { @@ -193,7 +296,7 @@ public class MusicUtil { } /** - * + * * @param publicIp */ public static void setPublicIp(String publicIp) { @@ -201,7 +304,7 @@ public class MusicUtil { } /** - * + * * @return */ public static List<String> getAllPublicIps() { @@ -209,7 +312,7 @@ public class MusicUtil { } /** - * + * * @param allPublicIps */ public static void setAllPublicIps(List<String> allPublicIps) { @@ -219,7 +322,7 @@ public class MusicUtil { /** * Returns An array of property names that should be in the Properties * files. - * + * * @return */ public static String[] getPropkeys() { @@ -228,7 +331,7 @@ public class MusicUtil { /** * Get MusicRestIp - default = localhost property file value - music.rest.ip - * + * * @return */ public static String getMusicRestIp() { @@ -237,7 +340,7 @@ public class MusicUtil { /** * Set MusicRestIp - * + * * @param musicRestIp */ public static void setMusicRestIp(String musicRestIp) { @@ -247,7 +350,7 @@ public class MusicUtil { /** * Get MusicPropertiesFilePath - Default = /opt/music/music.properties * property file value - music.properties - * + * * @return */ public static String getMusicPropertiesFilePath() { @@ -256,7 +359,7 @@ public class MusicUtil { /** * Set MusicPropertiesFilePath - * + * * @param musicPropertiesFilePath */ public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) { @@ -266,7 +369,7 @@ public class MusicUtil { /** * Get DefaultLockLeasePeriod - Default = 6000 property file value - * lock.lease.period - * + * * @return */ public static long getDefaultLockLeasePeriod() { @@ -275,7 +378,7 @@ public class MusicUtil { /** * Set DefaultLockLeasePeriod - * + * * @param defaultLockLeasePeriod */ public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) { @@ -284,7 +387,7 @@ public class MusicUtil { /** * Set Debug - * + * * @param debug */ public static void setDebug(boolean debug) { @@ -293,7 +396,7 @@ public class MusicUtil { /** * Is Debug - Default = true property file value - debug - * + * * @return */ public static boolean isDebug() { @@ -302,7 +405,7 @@ public class MusicUtil { /** * Set Version - * + * * @param version */ public static void setVersion(String version) { @@ -311,7 +414,7 @@ public class MusicUtil { /** * Return the version property file value - version - * + * * @return */ public static String getVersion() { @@ -321,7 +424,7 @@ public class MusicUtil { /** * Get MyZkHost - Zookeeper Hostname - Default = localhost property file * value - zookeeper.host - * + * * @return */ public static String getMyZkHost() { @@ -330,7 +433,7 @@ public class MusicUtil { /** * Set MyZkHost - Zookeeper Hostname - * + * * @param myZkHost */ public static void setMyZkHost(String myZkHost) { @@ -340,7 +443,7 @@ public class MusicUtil { /** * Get MyCassHost - Cassandra Hostname - Default = localhost property file * value - cassandra.host - * + * * @return */ public static String getMyCassaHost() { @@ -349,7 +452,7 @@ public class MusicUtil { /** * Set MyCassHost - Cassandra Hostname - * + * * @param myCassaHost */ public static void setMyCassaHost(String myCassaHost) { @@ -358,7 +461,7 @@ public class MusicUtil { /** * Get DefaultMusicIp - Default = localhost property file value - music.ip - * + * * @return */ public static String getDefaultMusicIp() { @@ -367,7 +470,7 @@ public class MusicUtil { /** * Set DefaultMusicIp - * + * * @param defaultMusicIp */ public static void setDefaultMusicIp(String defaultMusicIp) { @@ -375,7 +478,7 @@ public class MusicUtil { } /** - * + * * @return */ public static String getTestType() { @@ -384,7 +487,7 @@ public class MusicUtil { Scanner fileScanner = new Scanner(new File("")); testType = fileScanner.next();// ignore the my id line @SuppressWarnings("unused") - String batchSize = fileScanner.next();// ignore the my public ip + String batchSize = fileScanner.next();// ignore the my public ip // line fileScanner.close(); } catch (FileNotFoundException e) { @@ -395,7 +498,7 @@ public class MusicUtil { } /** - * + * * @param time */ public static void sleep(long time) { @@ -409,7 +512,7 @@ public class MusicUtil { /** * Utility function to check if the query object is valid. - * + * * @param withparams * @param queryObject * @return @@ -439,7 +542,7 @@ public class MusicUtil { } @SuppressWarnings("unchecked") - public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception { + public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception { String value = ""; switch (type.getName()) { @@ -465,15 +568,15 @@ public class MusicUtil { } /** - * + * * @param colType * @param valueObj * @return - * @throws MusicTypeConversionException + * @throws MusicTypeConversionException * @throws Exception */ @SuppressWarnings("unchecked") - public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception { + public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception { String valueObjString = valueObj + ""; switch (colType.getName()) { case UUID: @@ -492,8 +595,10 @@ public class MusicUtil { return Boolean.parseBoolean(valueObjString); case MAP: return (Map<String, Object>) valueObj; + case LIST: + return (List<Object>)valueObj; case BLOB: - + default: return valueObjString; } @@ -503,11 +608,11 @@ public class MusicUtil { ByteBuffer buffer = ByteBuffer.wrap(valueObj); return buffer; } - + /** * * Utility function to parse json map into sql like string - * + * * @param jMap * @param lineDelimiter * @return @@ -540,13 +645,13 @@ public class MusicUtil { } return major; } - + /** * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion * X-latestVerstion will be equal to the latest full version. * X-minorVersion - will be equal to the latest minor version. * X-pathVersion - will be equal to the latest patch version. - * Future plans will change this. + * Future plans will change this. * @param response * @param major * @param minor @@ -558,78 +663,156 @@ public class MusicUtil { String versionIn = buildVersion(major,minor,patch); String version = MusicUtil.getVersion(); String[] verArray = version.split("\\.",3); - if ( minor != null ) { + if ( minor != null ) { response.header(XMINORVERSION,minor); } else { response.header(XMINORVERSION,verArray[1]); - } + } if ( patch != null ) { response.header(XPATCHVERSION,patch); } else { response.header(XPATCHVERSION,verArray[2]); - } + } response.header(XLATESTVERSION,version); logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn); return response; } + + + public static Map<String,String> extractBasicAuthentication(String authorization){ + Map<String,String> authValues = new HashMap<>(); + if(authorization == null) { + authValues.put("ERROR", "Authorization cannot be null"); + return authValues; + } + authorization = authorization.replaceFirst("Basic", ""); + String decoded = Base64.base64Decode(authorization); + StringTokenizer token = new StringTokenizer(decoded, ":"); + authValues.put(MusicUtil.USERID, token.nextToken()); + authValues.put(MusicUtil.PASSWORD,token.nextToken()); + return authValues; + + } + + public static boolean isValidConsistency(String consistency) { + for (String string : cosistencyLevel) { + if (string.equalsIgnoreCase(consistency)) + return true; + } + return false; + + } + + public static ConsistencyLevel getConsistencyLevel(String consistency) { + return consistencyName.get(consistency.toUpperCase()); + } + + public static void loadProperties() throws Exception { + Properties prop = new Properties(); + InputStream input = null; + try { + // load the properties file + input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties"); + prop.load(input); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file."); + throw new Exception(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + // get the property value and return it + MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host")); + String zkHosts = prop.getProperty("zookeeper.host"); + MusicUtil.setMyZkHost(zkHosts); + MusicUtil.setCassName(prop.getProperty("cassandra.user")); + MusicUtil.setCassPwd(prop.getProperty("cassandra.password")); + MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port"))); + MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout"))); + MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval"))); + MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife"))); + } + + public static void setNotifyInterval(int notifyinterval) { + MusicUtil.notifyinterval = notifyinterval; + } + public static void setNotifyTimeOut(int notifytimeout) { + MusicUtil.notifytimeout = notifytimeout; + } + + public static int getNotifyInterval() { + return MusicUtil.notifyinterval; + } + + public static int getNotifyTimeout() { + return MusicUtil.notifytimeout; + } + + public static int getCacheObjectMaxLife() { + return MusicUtil.cacheObjectMaxLife; + } + + public static void setCacheObjectMaxLife(int cacheObjectMaxLife) { + MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife; + } + /** + * Given the time of write for an update in a critical section, this method provides a transformed timestamp + * that ensures that a previous lock holder who is still alive can never corrupt a later critical section. + * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections. + * @param the UUID lock reference associated with the write. + * @param the long timeOfWrite which is the actual time at which the write took place + * @throws MusicServiceException + * @throws MusicQueryException + */ + public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException { + // TODO: use acquire time instead of music eternity epoch + long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis); + + return ts; + } - public static Map<String,String> extractBasicAuthentication(String authorization){ - - Map<String,String> authValues = new HashMap<>(); - authorization = authorization.replaceFirst("Basic", ""); - String decoded = Base64.base64Decode(authorization); - StringTokenizer token = new StringTokenizer(decoded, ":"); - authValues.put(MusicUtil.USERID, token.nextToken()); - authValues.put(MusicUtil.PASSWORD,token.nextToken()); - return authValues; - + public static MusicCoreService getMusicCoreService() { + if(getLockUsing().equals(MusicUtil.CASSANDRA)) + return MusicCassaCore.getInstance(); + else if (getLockUsing().equals(MusicUtil.ZOOKEEPER)) + return MusicZKCore.getInstance(); + else + return MusicCassaCore.getInstance(); } - public static void loadProperties() throws Exception { - Properties prop = new Properties(); - InputStream input = null; - try { - // load the properties file - input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties"); - prop.load(input); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file."); - throw new Exception(); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.applicationLogger,"Load properties failed "+e.getMessage(),e); - } - } - } - // get the property value and return it - MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host")); - String zkHosts = prop.getProperty("zookeeper.host"); - MusicUtil.setMyZkHost(zkHosts); - MusicUtil.setCassName(prop.getProperty("cassandra.user")); - MusicUtil.setCassPwd(prop.getProperty("cassandra.password")); - MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port"))); - MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout"))); - MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval"))); - - } + /** + * @param lockName + * @return + */ + public static Map<String, Object> validateLock(String lockName) { + Map<String, Object> resultMap = new HashMap<>(); + String[] locks = lockName.split("\\."); + if(locks.length < 3) { + resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey"); + return resultMap; + } + String keyspace= locks[0]; + if(keyspace.startsWith("$")) + keyspace = keyspace.substring(1); + resultMap.put("keyspace",keyspace); + return resultMap; + } + + + public static void setIsCadi(boolean isCadi) { + // TODO Auto-generated method stub + MusicUtil.isCadi = isCadi; + } - public static void setNotifyInterval(int notifyinterval) { - MusicUtil.notifyinterval = notifyinterval; - } - public static void setNotifyTimeOut(int notifytimeout) { - MusicUtil.notifytimeout = notifytimeout; - } - - public static int getNotifyInterval() { - return MusicUtil.notifyinterval; - } - - public static int getNotifyTimeout() { - return MusicUtil.notifytimeout; - - } + public static boolean getIsCadi() { + return MusicUtil.isCadi; + } + } + diff --git a/src/main/java/org/onap/music/main/PropertiesListener.java b/src/main/java/org/onap/music/main/PropertiesListener.java index 026790ee..c5e8c37c 100755 --- a/src/main/java/org/onap/music/main/PropertiesListener.java +++ b/src/main/java/org/onap/music/main/PropertiesListener.java @@ -20,6 +20,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; import java.io.FileInputStream; @@ -28,17 +29,33 @@ import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; +import java.util.Iterator; import java.util.Properties; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; + +import org.onap.music.datastore.PreparedQueryObject; 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; -public class PropertiesListener implements ServletContextListener { +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicServiceException; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +public class PropertiesListener { // implements ServletContextListener { private Properties prop; private static final String MUSIC_PROPERTIES="music.properties"; +/* private Properties prop; + +>>>>>>> c8db07f77a945bc22046ef50d773c3c3608b014a private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesListener.class); @Override @@ -120,15 +137,37 @@ public class PropertiesListener implements ServletContextListener { case "aaf.endpoint.url": MusicUtil.setAafEndpointUrl(prop.getProperty(key)); break; + case "admin.username": + MusicUtil.setAdminId(prop.getProperty(key)); + break; + case "admin.password": + MusicUtil.setAdminPass(prop.getProperty(key)); + break; case "cassandra.port": MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty(key))); break; + case "aaf.admin.url": + MusicUtil.setAafAdminUrl(prop.getProperty(key)); + break; + case "music.namespace": + MusicUtil.setMusicNamespace(prop.getProperty(key)); + break; + case "admin.aaf.role": + MusicUtil.setAdminAafRole(prop.getProperty(key)); + break; case "notify.interval": - MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty(key))); - break; + MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty(key))); + break; case "notify.timeout": - MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty(key))); - break; + MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty(key))); + break; + case "lock.using": + MusicUtil.setLockUsing(prop.getProperty(key)); + break; + case "cacheobject.maxlife": + MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty(key))); + CachingUtil.setCacheEternalProps(); + break; default: logger.error(EELFLoggerDelegate.errorLogger, "No case found for " + key); @@ -136,7 +175,7 @@ public class PropertiesListener implements ServletContextListener { } } } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR); logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } @@ -148,10 +187,71 @@ public class PropertiesListener implements ServletContextListener { "List of all MUSIC ids:" + MusicUtil.getAllIds().toString()); logger.info(EELFLoggerDelegate.applicationLogger, "List of all MUSIC public ips:" + MusicUtil.getAllPublicIps().toString()); + + scheduleCronJobForZKCleanup(); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { prop = null; } + + + private ScheduledExecutorService scheduler; + public void scheduleCronJobForZKCleanup() { + scheduler = Executors.newSingleThreadScheduledExecutor(); + scheduler.scheduleAtFixedRate(new CachingUtil(), 0, 24, TimeUnit.HOURS); + PreparedQueryObject pQuery = new PreparedQueryObject(); + String consistency = MusicUtil.EVENTUAL; + pQuery.appendQueryString("CREATE TABLE IF NOT EXISTS admin.locks ( lock_id text PRIMARY KEY, ctime text)"); + try { + ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + } catch (MusicServiceException e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),ErrorSeverity.ERROR); + } + + //Zookeeper cleanup + scheduler.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + deleteLocksFromDB(); + } + } , 0, 24, TimeUnit.HOURS); + } + + + public void deleteLocksFromDB() { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "select * from admin.locks"); + try { + ResultSet rs = MusicCore.get(pQuery); + Iterator<Row> it = rs.iterator(); + StringBuilder deleteKeys = new StringBuilder(); + Boolean expiredKeys = false; + while (it.hasNext()) { + Row row = (Row) it.next(); + String id = row.getString("lock_id"); + long ctime = Long.parseLong(row.getString("ctime")); + if(System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) { + expiredKeys = true; + String new_id = id.substring(1); + try { + MusicCore.deleteLock(new_id); + } catch (MusicLockingException e) { + logger.info(EELFLoggerDelegate.applicationLogger, + e.getMessage()); + } + deleteKeys.append("'").append(id).append("'").append(","); + } + } + if(expiredKeys) { + deleteKeys.deleteCharAt(deleteKeys.length()-1); + CachingUtil.deleteKeysFromDB(deleteKeys.toString()); + } + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),ErrorSeverity.ERROR); + } + } +*/ } diff --git a/src/main/java/org/onap/music/main/PropertiesLoader.java b/src/main/java/org/onap/music/main/PropertiesLoader.java new file mode 100644 index 00000000..ee10db42 --- /dev/null +++ b/src/main/java/org/onap/music/main/PropertiesLoader.java @@ -0,0 +1,192 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.main; + +import java.util.ArrayList; +import java.util.Arrays; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.stereotype.Component; + +@PropertySource(value = {"file:/opt/app/music/etc/music.properties", "classpath:/project.properties"}) +@Component +public class PropertiesLoader implements InitializingBean { + + @Value("${zookeeper.host}") + private String zookeeperHost; + + @Value("${cassandra.host}") + public String cassandraHost; + + @Value("${music.ip}") + public String musicIp; + + @Value("${debug}") + public String debug; + + @Value("${version}") + public String version; + + @Value("${music.rest.ip}") + public String musicRestIp; + + @Value("${music.properties}") + public String musicProperties; + + @Value("${lock.lease.period}") + public String lockLeasePeriod; + + @Value("${public.ip}") + public String publicIp; + + @Value("${my.id}") + public String myId; + + @Value("${all.ids}") + public String allIds; + + @Value("${all.public.ips}") + public String allPublicIps; + + @Value("${cassandra.user}") + public String cassandraUser; + + @Value("${cassandra.password}") + public String cassandraPassword; + + @Value("${aaf.endpoint.url}") + public String aafEndpointUrl; + + @Value("${admin.username}") + public String adminUsername; + + @Value("${admin.password}") + public String adminPassword; + + @Value("${cassandra.port}") + public String cassandraPort; + + @Value("${aaf.admin.url}") + public String aafAdminUrl; + + @Value("${music.namespace}") + public String musicNamespace; + + @Value("${admin.aaf.role}") + public String adminAafRole; + + @Value("${notify.interval}") + public String notifyInterval; + + @Value("${notify.timeout}") + public String notifyTimeout; + + @Value("${cadi}") + public String isCadi; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesLoader.class); + + @Bean + public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { + //return new PropertySourcesPlaceholderConfigurer(); + PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); + pspc.setIgnoreResourceNotFound(true); + pspc.setIgnoreUnresolvablePlaceholders(true); + return pspc; + } + + public void loadProperties () { + if(aafAdminUrl != null && !aafAdminUrl.equals("${aaf.admin.url}")) + MusicUtil.setAafAdminUrl(aafAdminUrl); + if(aafEndpointUrl != null && !aafEndpointUrl.equals("${aaf.endpoint.url}")) + MusicUtil.setAafEndpointUrl(aafEndpointUrl); + if(adminAafRole != null && !adminAafRole.equals("${admin.aaf.role}")) + MusicUtil.setAdminAafRole(adminAafRole); + //MusicUtil.setAdminId(adminId); + if(adminPassword != null && !adminPassword.equals("${admin.password}")) + MusicUtil.setAdminPass(adminPassword); + if(adminUsername != null && !adminUsername.equals("${admin.username}")) + MusicUtil.setAdminId(adminUsername); + if(allIds != null && !allIds.equals("${all.ids}")) { + String[] ids = allIds.split(":"); + MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids))); + } + if(allPublicIps != null && !allPublicIps.equals("${all.public.ips}")) { + String[] ips = allPublicIps.split(":"); + if (ips.length == 1) { + // Future use + } else if (ips.length > 1) { + MusicUtil.setAllPublicIps( + new ArrayList<String>(Arrays.asList(ips))); + } + } + if(cassandraPort != null && !cassandraPort.equals("${cassandra.port}")) + MusicUtil.setCassandraPort(Integer.parseInt(cassandraPort)); + if(cassandraUser != null && !cassandraUser.equals("${cassandra.user}")) + MusicUtil.setCassName(cassandraUser); + if(cassandraPassword != null && !cassandraPassword.equals("${cassandra.password}")) + MusicUtil.setCassPwd(cassandraPassword); + if(debug != null && !debug.equals("${debug}")) + MusicUtil.setDebug(Boolean.parseBoolean(debug)); + if(lockLeasePeriod != null && !lockLeasePeriod.equals("${lock.lease.period}")) + MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(lockLeasePeriod)); + if(musicIp != null && !musicIp.equals("${music.ip}")) + MusicUtil.setDefaultMusicIp(musicIp); + if(musicNamespace != null && !musicNamespace.equals("${music.namespace}")) + MusicUtil.setMusicNamespace(musicNamespace); + if(musicProperties != null && !musicProperties.equals("${music.properties}")) + MusicUtil.setMusicPropertiesFilePath(musicProperties); + if(musicRestIp != null && !musicRestIp.equals("${music.rest.ip}")) + MusicUtil.setMusicRestIp(musicRestIp); + if(cassandraHost != null && !cassandraHost.equals("${cassandra.host}")) + MusicUtil.setMyCassaHost(cassandraHost); + logger.info("#### Cassandra Host: " + MusicUtil.getMyCassaHost()); + if(myId != null && !myId.equals("${my.id}")) + MusicUtil.setMyId(Integer.parseInt(myId)); + if(zookeeperHost != null && !zookeeperHost.equals("${zookeeper.host}")) + MusicUtil.setMyZkHost(zookeeperHost); + if(notifyInterval != null && !notifyInterval.equals("${notify.interval}")) + MusicUtil.setNotifyInterval(Integer.parseInt(notifyInterval)); + if(notifyTimeout != null && !notifyTimeout.equals("${notify.timeout}")) + MusicUtil.setNotifyTimeOut(Integer.parseInt(notifyTimeout)); + if(allPublicIps != null && !allPublicIps.equals("${public.ip}")) + MusicUtil.setPublicIp(allPublicIps); + if(version != null && !version.equals("${version}")) + MusicUtil.setVersion(version); + if(isCadi != null && !isCadi.equals("${cadi}")) + MusicUtil.setIsCadi(Boolean.parseBoolean(isCadi)); + } + + + @Override + public void afterPropertiesSet() throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/src/main/java/org/onap/music/main/ResultType.java b/src/main/java/org/onap/music/main/ResultType.java index 61ba0295..f5ef2070 100644 --- a/src/main/java/org/onap/music/main/ResultType.java +++ b/src/main/java/org/onap/music/main/ResultType.java @@ -19,13 +19,14 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; public enum ResultType { SUCCESS("Success"), FAILURE("Failure"), - SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"), - BODYMISSING("Incomplete Request body. Please correct your input request and retry."); - + SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"), + BODYMISSING("Incomplete Request body. Please correct your input request and retry."); + private String result; ResultType(String result) { diff --git a/src/main/java/org/onap/music/main/ReturnType.java b/src/main/java/org/onap/music/main/ReturnType.java index 33f68d7d..f02dabbf 100644 --- a/src/main/java/org/onap/music/main/ReturnType.java +++ b/src/main/java/org/onap/music/main/ReturnType.java @@ -19,6 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.main; import java.util.HashMap; |