aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/main
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/org/onap/music/main')
-rwxr-xr-xsrc/main/java/org/onap/music/main/CachingUtil.java485
-rw-r--r--src/main/java/org/onap/music/main/CronJobManager.java103
-rwxr-xr-xsrc/main/java/org/onap/music/main/MusicUtil.java39
-rwxr-xr-xsrc/main/java/org/onap/music/main/PropertiesListener.java257
-rw-r--r--src/main/java/org/onap/music/main/PropertiesLoader.java5
5 files changed, 11 insertions, 878 deletions
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java
deleted file mode 100755
index db74aceb..00000000
--- a/src/main/java/org/onap/music/main/CachingUtil.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2018 IBM
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.Calendar;
-import java.util.HashMap;
-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.mindrot.jbcrypt.BCrypt;
-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.MusicServiceException;
-
-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;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-
-/**
- * All Caching related logic is handled by this class and a schedule cron runs to update cache.
- *
- * @author Vikram
- *
- */
-public class CachingUtil implements Runnable {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
-
- private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
- private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
- private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
- private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
- 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 updateCallbackNotifyList(List<String> notifyList) {
- logger.info("callbackNotifyList: updating cache.....");
- callbackNotifyList.put("callbackNotify", notifyList);
- }
-
- public static List<String> getCallbackNotifyList() {
- return callbackNotifyList.get("callbackNotify");
- }
-
- public void initializeMusicCache() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
- musicCache.put("isInitialized", "true");
- }
-
- public void initializeAafCache() throws MusicServiceException {
- logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
-
- String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(query);
- try {
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
- } catch (Exception e1) {
- logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- }
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- Map<String, String> map = null;
- while (it.hasNext()) {
- Row row = it.next();
- String nameSpace = row.getString("keyspace_name");
- String userId = row.getString(USERNAME);
- String password = row.getString(PASSWORD);
- String keySpace = row.getString("application_name");
- try {
- userAttempts.put(nameSpace, 0);
- boolean responseObj = triggerAAF(nameSpace, userId, password);
- if (responseObj) {
- map = new HashMap<>();
- map.put(userId, password);
- aafCache.put(nameSpace, map);
- musicCache.put(keySpace, nameSpace);
- logger.debug("Cronjob: Cache Updated with AAF response for namespace "
- + nameSpace);
- }
- } 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. ");
- }
- }
-
- }
-
- @Override
- public void run() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
- try {
- initializeAafCache();
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- }
- }
-
- public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
- String keySpace) throws Exception {
-
- if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
- if (keySpace != null && !musicCache.get(keySpace).equals(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..");
- // reset invalid attempts to 0
- userAttempts.put(nameSpace, 0);
- return true;
- } else {
- // call AAF update cache with new password
- if (userAttempts.get(nameSpace) == null)
- userAttempts.put(nameSpace, 0);
- if ((Integer) userAttempts.get(nameSpace) >= 3) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
- logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
- Calendar calendar = Calendar.getInstance();
- long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
- logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
- if( delayTime > 120000) {
- 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.");
- throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
- }
- }
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
- }
- }
-
- 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) {
- 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);
- musicCache.put(keySpace, nameSpace);
- return true;
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
- return false;
- }
-
- 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,"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();
- // WebResource webResource =
- // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
- WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
- String plainCreds = userId + ":" + password;
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- 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);
- if ((Integer) userAttempts.get(nameSpace) >= 2) {
- lastFailedTime.put(nameSpace, Calendar.getInstance());
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
- }
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Unable to authenticate. Please check the AAF credentials against namespace.");
- // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
- // for specific time.
- }
- /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
- Arrays.asList(MediaType.APPLICATION_JSON));
- // AAFResponse output = response.getEntity(AAFResponse.class);
- response.bufferEntity();
- String x = response.getEntity(String.class);
- AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
-
- return true;
- }
-
- public static void updateMusicCache(String keyspace, String nameSpace) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
- 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<>();
- map.put(userId, password);
- musicValidateCache.put(nameSpace, map);
- }
-
- public static void updateisAAFCache(String namespace, String isAAF) {
- appNameCache.put(namespace, isAAF);
- }
-
- public static String isAAFApplication(String namespace) throws MusicServiceException {
- String isAAF = appNameCache.get(namespace);
- if (isAAF == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT is_aaf from admin.keyspace_master where application_name = '"
- + namespace + "' allow filtering");
- Row rs = null;
- try {
- rs = MusicCore.get(pQuery).one();
- } catch(InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
- throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
- }
- try {
- isAAF = String.valueOf(rs.getBool("is_aaf"));
- if(isAAF != null)
- appNameCache.put(namespace, isAAF);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- }
- return isAAF;
- }
-
- public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
- String uuid = null;
- if (uuid == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT uuid from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- uuid = rs.getUUID("uuid").toString();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage());
- }
- }
- return uuid;
- }
-
- public static String getAppName(String keyspace) throws MusicServiceException {
- String appName = null;
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT application_name from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- appName = rs.getString("application_name");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- return appName;
- }
-
- public static String generateUUID() {
- String uuid = UUID.randomUUID().toString();
- logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
- return uuid;
- }
-
- public static Map<String, Object> validateRequest(String nameSpace, String userId,
- String password, String keyspace, String aid, String operation) {
- Map<String, Object> resultMap = new HashMap<>();
- if (!"createKeySpace".equals(operation)) {
- if (nameSpace == null) {
- resultMap.put("Exception", "Application namespace is mandatory.");
- }
- }
- return resultMap;
-
- }
-
- 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);
- resultMap.put("Exception",
- "One or more required headers appName(ns), userId, password is missing. Please check.");
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where application_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
- } catch(Exception e) {
- resultMap.put("Exception",
- "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
- return resultMap;
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- String errorMsg = "Unable to process operation. Error is "+e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger, errorMsg);
- resultMap.put("Exception", errorMsg);
- 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.");
- return resultMap;
- }
- if (rs == null) {
- 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)))) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- return resultMap;
- }
- }
- return resultMap;
- }
-
- public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
- String keyspace) {
- Map<String, Object> resultMap = new HashMap<>();
- String pwd = null;
- if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
- && (musicValidateCache.get(nameSpace).containsKey(userId))) {
- if(!musicCache.get(keyspace).equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
- resultMap.put("Exception", "Namespace, userId and password doesn't match");
- return resultMap;
- }
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage());
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- String errMsg = "Unable to process operation. Error is "+e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger, errMsg);
- resultMap.put("Exception", errMsg);
- return resultMap;
- }
- if(rs == null) {
- resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
- return resultMap;
- }
- else {
- String user = rs.getString(USERNAME);
- pwd = rs.getString(PASSWORD);
- String ns = rs.getString("application_name");
- if(!ns.equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!user.equals(userId)) {
- resultMap.put("Exception", "Invalid userId :"+userId);
- return resultMap;
- }
- if(!BCrypt.checkpw(password, pwd)) {
- resultMap.put("Exception", "Invalid password");
- return resultMap;
- }
- }
- CachingUtil.updateMusicCache(keyspace, nameSpace);
- CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
- return resultMap;
- }
-
- public static void deleteKeysFromDB(String deleteKeys) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
- try {
- MusicCore.nonKeyRelatedPut(pQuery, "eventual");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), "Deleting keys from "
- + "DB failed.");
- }
- }
-}
diff --git a/src/main/java/org/onap/music/main/CronJobManager.java b/src/main/java/org/onap/music/main/CronJobManager.java
deleted file mode 100644
index ea2fa685..00000000
--- a/src/main/java/org/onap/music/main/CronJobManager.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- * 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.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Iterator;
-
-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;
-
-@Component
-public class CronJobManager {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronJobManager.class);
-
- 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,AppMessages.QUERYERROR,ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- }
-
- 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 = 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,AppMessages.CACHEERROR,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- }
- }
-}
diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java
index dd089683..b737377d 100755
--- a/src/main/java/org/onap/music/main/MusicUtil.java
+++ b/src/main/java/org/onap/music/main/MusicUtil.java
@@ -48,7 +48,6 @@ import java.util.concurrent.ConcurrentMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
-
import org.onap.music.datastore.MusicDataStoreHandle;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
@@ -59,7 +58,6 @@ 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;
@@ -95,7 +93,6 @@ public class MusicUtil {
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";
@@ -121,7 +118,7 @@ public class MusicUtil {
private static String musicRestIp = LOCALHOST;
private static String musicPropertiesFilePath = PROPERTIES_FILE;
private static long defaultLockLeasePeriod = 6000;
- private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
+ private static final String[] propKeys = new String[] { "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","admin.username","admin.password","aaf.admin.url",
"music.namespace","admin.aaf.role","cassandra.port","lock.using"};
@@ -431,25 +428,6 @@ public class MusicUtil {
}
/**
- * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
- * value - zookeeper.host
- *
- * @return
- */
- public static String getMyZkHost() {
- return myZkHost;
- }
-
- /**
- * Set MyZkHost - Zookeeper Hostname
- *
- * @param myZkHost
- */
- public static void setMyZkHost(String myZkHost) {
- MusicUtil.myZkHost = myZkHost;
- }
-
- /**
* Get MyCassHost - Cassandra Hostname - Default = localhost property file
* value - cassandra.host
*
@@ -737,8 +715,6 @@ public class MusicUtil {
}
// 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")));
@@ -789,8 +765,6 @@ public class MusicUtil {
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();
}
@@ -815,7 +789,6 @@ public class MusicUtil {
public static void setIsCadi(boolean isCadi) {
- // TODO Auto-generated method stub
MusicUtil.isCadi = isCadi;
}
@@ -859,5 +832,15 @@ public class MusicUtil {
return MusicUtil.isCadi;
}
+
+ /**
+ * @return a random uuid
+ */
+ public static String generateUUID() {
+ String uuid = UUID.randomUUID().toString();
+ logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
+ return uuid;
+ }
+
}
diff --git a/src/main/java/org/onap/music/main/PropertiesListener.java b/src/main/java/org/onap/music/main/PropertiesListener.java
deleted file mode 100755
index c5e8c37c..00000000
--- a/src/main/java/org/onap/music/main/PropertiesListener.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * Modifications Copyright (C) 2018 IBM.
- * ===================================================================
- * 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.FileInputStream;
-import java.io.IOException;
-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;
-
-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
- public void contextInitialized(ServletContextEvent servletContextEvent) {
- prop = new Properties();
- Properties projectProp = new Properties();
- URL resource = getClass().getResource("/");
- String musicPropertiesFilePath = resource.getPath().replace("WEB-INF/classes/","WEB-INF/classes/project.properties");
-
- // Open the file
- try {
- InputStream musicProps = null;
- projectProp.load(new FileInputStream(musicPropertiesFilePath));
- if (projectProp.containsKey(MUSIC_PROPERTIES)) {
- musicProps = new FileInputStream(projectProp.getProperty(MUSIC_PROPERTIES));
- } else {
- musicProps = new FileInputStream(MusicUtil.getMusicPropertiesFilePath());
- }
- prop.load(musicProps);
- musicProps.close();
- prop.putAll(projectProp);
- String[] propKeys = MusicUtil.getPropkeys();
- for (int k = 0; k < propKeys.length; k++) {
- String key = propKeys[k];
- if (prop.containsKey(key) && prop.get(key) != null) {
- logger.info(key + " : " + prop.getProperty(key));
- switch (key) {
- case "zookeeper.host":
- MusicUtil.setMyZkHost(prop.getProperty(key));
- break;
- case "cassandra.host":
- MusicUtil.setMyCassaHost(prop.getProperty(key));
- break;
- case "music.ip":
- MusicUtil.setDefaultMusicIp(prop.getProperty(key));
- break;
- case "debug":
- MusicUtil.setDebug(Boolean
- .getBoolean(prop.getProperty(key).toLowerCase()));
- break;
- case "version":
- MusicUtil.setVersion(prop.getProperty(key));
- break;
- case "music.rest.ip":
- MusicUtil.setMusicRestIp(prop.getProperty(key));
- break;
- case MUSIC_PROPERTIES:
- MusicUtil.setMusicPropertiesFilePath(prop.getProperty(key));
- break;
- case "lock.lease.period":
- MusicUtil.setDefaultLockLeasePeriod(
- Long.parseLong(prop.getProperty(key)));
- break;
- case "my.id":
- MusicUtil.setMyId(Integer.parseInt(prop.getProperty(key)));
- break;
- case "all.ids":
- String[] ids = prop.getProperty(key).split(":");
- MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids)));
- break;
- case "public.ip":
- MusicUtil.setPublicIp(prop.getProperty(key));
- break;
- case "all.public.ips":
- String[] ips = prop.getProperty(key).split(":");
- if (ips.length == 1) {
- // Future use
- } else if (ips.length > 1) {
- MusicUtil.setAllPublicIps(
- new ArrayList<String>(Arrays.asList(ips)));
- }
- break;
- case "cassandra.user":
- MusicUtil.setCassName(prop.getProperty(key));
- break;
- case "cassandra.password":
- MusicUtil.setCassPwd(prop.getProperty(key));
- break;
- 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;
- case "notify.timeout":
- 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);
- }
- }
- }
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Starting MUSIC " + MusicUtil.getVersion() + " on node with id "
- + MusicUtil.getMyId() + " and public ip "
- + MusicUtil.getPublicIp() + "...");
- logger.info(EELFLoggerDelegate.applicationLogger,
- "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
index ee10db42..db04ff4b 100644
--- a/src/main/java/org/onap/music/main/PropertiesLoader.java
+++ b/src/main/java/org/onap/music/main/PropertiesLoader.java
@@ -37,9 +37,6 @@ import org.springframework.stereotype.Component;
@Component
public class PropertiesLoader implements InitializingBean {
- @Value("${zookeeper.host}")
- private String zookeeperHost;
-
@Value("${cassandra.host}")
public String cassandraHost;
@@ -168,8 +165,6 @@ public class PropertiesLoader implements InitializingBean {
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}"))