diff options
author | srupane kondreddy <srupane.kondreddy@att.com> | 2018-11-13 15:27:24 -0500 |
---|---|---|
committer | srupane kondreddy <sk5300@research.att.com> | 2018-11-13 15:48:52 -0500 |
commit | 7addd52dc73e6571028ca7f6a018e75ec1c9b0ca (patch) | |
tree | 85250211fb6e3d67a849edffd40535992ec1b78c | |
parent | ac3cfd1cd5f18d72948b70db39cc7db32a392133 (diff) |
music core implemented as a service
Change-Id: I4075d0efb03bf2a153976354947be1329660c1f1
Issue-ID: MUSIC-148
Signed-off-by: srupane kondreddy <sk5300@research.att.com>
28 files changed, 740 insertions, 454 deletions
diff --git a/src/main/java/org/onap/music/authentication/MusicAuthentication.java b/src/main/java/org/onap/music/authentication/MusicAuthentication.java new file mode 100644 index 00000000..4967e845 --- /dev/null +++ b/src/main/java/org/onap/music/authentication/MusicAuthentication.java @@ -0,0 +1,138 @@ +/* + * ============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.authentication; + +import java.util.HashMap; +import java.util.Map; + +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 org.onap.music.main.CachingUtil; +import org.onap.music.main.MusicUtil; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Row; + +public class MusicAuthentication { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthentication.class); + + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); + + /** + * authenticate user logic + * + * @param nameSpace + * @param userId + * @param password + * @param keyspace + * @param aid + * @param operation + * @return + * @throws Exception + */ + public static Map<String, Object> authenticate(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); + } + + return resultMap; + } + +} diff --git a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java b/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java index 8aadcba3..281c6ca0 100644 --- a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java +++ b/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java @@ -27,16 +27,18 @@ import java.util.HashMap; import java.util.Map; import org.codehaus.jettison.json.JSONObject; +import org.onap.music.datastore.MusicDataStoreHandle; 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.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.rest.RestMusicDataAPI; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.DataType; @@ -46,6 +48,7 @@ import com.datastax.driver.core.TableMetadata; public class MusicConditional { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName, Map<String, Object> casscadeColumnData, String primaryKey, Map<String, Object> valuesMap, @@ -53,7 +56,7 @@ public class MusicConditional { Map<String, PreparedQueryObject> queryBank = new HashMap<>(); TableMetadata tableInfo = null; - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); String primaryId = tableInfo.getPrimaryKey().get(0).getName(); DataType casscadeColumnType = tableInfo.getColumn(casscadeColumnName).getType(); @@ -84,15 +87,15 @@ public class MusicConditional { String key = keyspace + "." + tablename + "." + primaryKey; - String lockId = MusicCore.createLockReference(key); + String lockId = musicCore.createLockReference(key); long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); + ReturnType lockAcqResult = musicCore.acquireLockWithLease(key, lockId, leasePeriod); try { if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { ReturnType criticalPutResult = conditionalInsertAtomic(lockId, keyspace, tablename, primaryKey, queryBank); - MusicCore.destroyLockRef(key,lockId); + musicCore.destroyLockRef(key,lockId); if (criticalPutResult.getMessage().contains("insert")) criticalPutResult .setMessage("Insert values: "); @@ -102,11 +105,11 @@ public class MusicConditional { return criticalPutResult; } else { - MusicCore.destroyLockRef(key,lockId); + musicCore.destroyLockRef(key,lockId); return lockAcqResult; } } catch (Exception e) { - MusicCore.destroyLockRef(key,lockId); + musicCore.destroyLockRef(key,lockId); return new ReturnType(ResultType.FAILURE, e.getMessage()); } @@ -119,18 +122,18 @@ public class MusicConditional { try { String fullyQualifiedKey = keyspace + "." + tableName + "." + primaryKey; - ReturnType lockAcqResult = MusicCore.acquireLock(fullyQualifiedKey, lockId); + ReturnType lockAcqResult = musicCore.acquireLock(fullyQualifiedKey, lockId); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { try { - results = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)); + results = MusicDataStoreHandle.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)); } catch (Exception e) { return new ReturnType(ResultType.FAILURE, e.getMessage()); } if (results.all().isEmpty()) { - MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical"); + MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical"); return new ReturnType(ResultType.SUCCESS, "insert"); } else { - MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical"); + MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical"); return new ReturnType(ResultType.SUCCESS, "update"); } } else { @@ -152,20 +155,20 @@ public class MusicConditional { public static ReturnType update(Map<String,PreparedQueryObject> queryBank, String keyspace, String tableName, String primaryKey,String primaryKeyValue,String planId,String cascadeColumnName,Map<String,String> cascadeColumnValues) { String key = keyspace + "." + tableName + "." + primaryKeyValue; - String lockId = MusicCore.createLockReference(key); + String lockId = musicCore.createLockReference(key); long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); try { - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); + ReturnType lockAcqResult = musicCore.acquireLockWithLease(key, lockId, leasePeriod); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { return updateAtomic(lockId, keyspace, tableName, primaryKey,primaryKeyValue, queryBank,planId,cascadeColumnValues,cascadeColumnName); } else { - MusicCore.destroyLockRef(key,lockId); + musicCore.destroyLockRef(key,lockId); return lockAcqResult; } } catch (Exception e) { - MusicCore.destroyLockRef(key,lockId); + musicCore.destroyLockRef(key,lockId); return new ReturnType(ResultType.FAILURE, e.getMessage()); } @@ -176,9 +179,9 @@ public class MusicConditional { String key = keyspace + "." + tableName + "." + primaryKeyValue; long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); try { - ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod); + ReturnType lockAcqResult = musicCore.acquireLockWithLease(key, lockId, leasePeriod); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - Row row = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)).one(); + Row row = MusicDataStoreHandle.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)).one(); if(row != null) { Map<String, String> updatedValues = cascadeColumnUpdateSpecific(row, cascadeColumnValues, casscadeColumnName, planId); @@ -191,14 +194,14 @@ public class MusicConditional { update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts)); update.addValue(MusicUtil.convertToActualDataType(DataType.text(), primaryKeyValue)); try { - MusicCore.getDSHandle().executePut(update, "critical"); + MusicDataStoreHandle.getDSHandle().executePut(update, "critical"); } catch (Exception ex) { return new ReturnType(ResultType.FAILURE, ex.getMessage()); } }else { return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+primaryKey); } - MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.UPSERT), "critical"); + MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPSERT), "critical"); return new ReturnType(ResultType.SUCCESS, "update success"); } else { diff --git a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java index 4292749c..63c104f7 100644 --- a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java +++ b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java @@ -38,17 +38,19 @@ import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.codehaus.jettison.json.JSONObject; +import org.onap.music.datastore.MusicDataStoreHandle; 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.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; import org.onap.music.rest.RestMusicAdminAPI; +import org.onap.music.service.impl.MusicCassaCore; +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.conductor.*; @@ -103,7 +105,7 @@ public class RestMusicConditionalAPI { Map<String, Object> authMap = null; try { - authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "insertIntoTable"); + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "insertIntoTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -174,7 +176,7 @@ public class RestMusicConditionalAPI { Map<String, Object> authMap = null; try { - authMap = MusicCore.authenticate(ns, userId, password, keyspace, aid, "updateTable"); + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "updateTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -194,7 +196,7 @@ public class RestMusicConditionalAPI { String planId = casscadeColumnData.get("key").toString(); Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value"); TableMetadata tableInfo = null; - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); String primaryId = tableInfo.getPrimaryKey().get(0).getName(); diff --git a/src/main/java/org/onap/music/datastore/Condition.java b/src/main/java/org/onap/music/datastore/Condition.java new file mode 100644 index 00000000..f08a8754 --- /dev/null +++ b/src/main/java/org/onap/music/datastore/Condition.java @@ -0,0 +1,53 @@ +/* + * ============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.datastore; + +import java.util.Map; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + + + + public class Condition { + Map<String, Object> conditions; + PreparedQueryObject selectQueryForTheRow; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Condition.class); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); + + 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 = musicCore.quorumGet(selectQueryForTheRow); + Row row = results.one(); + return MusicDataStoreHandle.getDSHandle().doesRowSatisfyCondition(row, conditions); + } + } + diff --git a/src/main/java/org/onap/music/datastore/CassaDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java index 14934f6e..725cefe6 100644 --- a/src/main/java/org/onap/music/datastore/CassaDataStore.java +++ b/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -89,7 +89,7 @@ import com.sun.jersey.core.util.Base64; * @author bharathb * */ -public class CassaDataStore { +public class MusicDataStore { private Session session; private Cluster cluster; @@ -119,12 +119,12 @@ public class CassaDataStore { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CassaDataStore.class); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class); /** * */ - public CassaDataStore() { + public MusicDataStore() { connectToCassaCluster(); } @@ -133,7 +133,7 @@ public class CassaDataStore { * @param cluster * @param session */ - public CassaDataStore(Cluster cluster, Session session) { + public MusicDataStore(Cluster cluster, Session session) { this.session = session; this.cluster = cluster; } @@ -143,7 +143,7 @@ public class CassaDataStore { * @param remoteIp * @throws MusicServiceException */ - public CassaDataStore(String remoteIp) { + public MusicDataStore(String remoteIp) { try { connectToCassaCluster(remoteIp); } catch (MusicServiceException e) { diff --git a/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java b/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java new file mode 100644 index 00000000..a2d9386b --- /dev/null +++ b/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java @@ -0,0 +1,115 @@ +/* + * ============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.datastore; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import org.onap.music.service.impl.MusicCassaCore; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.TableMetadata; + +public class MusicDataStoreHandle { + + public static MusicDataStore mDstoreHandle = null; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStoreHandle.class); + + /** + * + * @param remoteIp + * @return + */ + public static MusicDataStore getDSHandle(String remoteIp) { + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); + long start = System.currentTimeMillis(); + if (mDstoreHandle == null) { + try { + MusicUtil.loadProperties(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default."); + } + 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) { + try { + MusicUtil.loadProperties(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default."); + } + // Quick Fix - Best to put this into every call to getDSHandle? + if (! MusicUtil.getMyCassaHost().equals("localhost") ) { + 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; + } + + /** + * + * @param keyspace + * @param tablename + * @return + * @throws MusicServiceException + */ + public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { + return MusicDataStoreHandle.getDSHandle().returnColumnMetadata(keyspace, tablename); + } + + /** + * + * @param results + * @return + * @throws MusicServiceException + */ + public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException { + return MusicDataStoreHandle.getDSHandle().marshalData(results); + } + +} diff --git a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java index 5f6329a1..65e19501 100644 --- a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java +++ b/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java @@ -26,9 +26,10 @@ import java.util.UUID; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ConsistencyLevel; @@ -39,6 +40,7 @@ import com.datastax.driver.core.ConsistencyLevel; public class MusicHealthCheck { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); private String cassandrHost; private String zookeeperHost; @@ -78,7 +80,7 @@ public class MusicHealthCheck { PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)"); pQuery.addValue(UUID.randomUUID()); - ResultType rs = MusicCore.nonKeyRelatedPut(pQuery, consistency); + ResultType rs = musicCore.nonKeyRelatedPut(pQuery, consistency); System.out.println(rs); if (rs != null) { return Boolean.TRUE; @@ -94,7 +96,7 @@ public class MusicHealthCheck { pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)"); ResultType rs = null ; try { - rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString()); + rs = musicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString()); } catch (MusicServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/main/java/org/onap/music/datastore/CassaLockStore.java b/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java index e03a1c07..f753aab7 100644 --- a/src/main/java/org/onap/music/datastore/CassaLockStore.java +++ b/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java @@ -1,7 +1,9 @@ -package org.onap.music.datastore; +package org.onap.music.lockingservice.cassandra; import java.util.UUID; +import org.onap.music.datastore.MusicDataStore; +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; @@ -30,12 +32,12 @@ public class CassaLockStore { } } - CassaDataStore dsHandle; + MusicDataStore dsHandle; public CassaLockStore() { - dsHandle = new CassaDataStore(); + dsHandle = new MusicDataStore(); } - public CassaLockStore(CassaDataStore dsHandle) { + public CassaLockStore(MusicDataStore dsHandle) { this.dsHandle=dsHandle; } diff --git a/src/main/java/org/onap/music/datastore/MusicLockState.java b/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java index 60a15b13..f5070a1d 100644 --- a/src/main/java/org/onap/music/datastore/MusicLockState.java +++ b/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java @@ -1,4 +1,4 @@ -package org.onap.music.datastore; +package org.onap.music.lockingservice.cassandra; public class MusicLockState { public enum LockStatus { UNLOCKED, BEING_LOCKED, LOCKED diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java index d3654118..5c253f5e 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/main/CachingUtil.java @@ -41,6 +41,8 @@ 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.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.att.eelf.configuration.EELFLogger; import com.datastax.driver.core.DataType; @@ -67,6 +69,7 @@ public class CachingUtil implements Runnable { private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache"); private static Map<String, Number> userAttempts = new HashMap<>(); private static Map<String, Calendar> lastFailedTime = new HashMap<>(); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); public boolean isCacheRefreshNeeded() { if (aafCache.get("initBlankMap") == null) @@ -91,7 +94,7 @@ public class CachingUtil implements Runnable { logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); e1.printStackTrace(); } - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); Iterator<Row> it = rs.iterator(); Map<String, String> map = null; while (it.hasNext()) { @@ -245,7 +248,7 @@ public class CachingUtil implements Runnable { + namespace + "' allow filtering"); Row rs = null; try { - rs = MusicCore.get(pQuery).one(); + 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."); @@ -269,7 +272,7 @@ public class CachingUtil implements Runnable { pQuery.appendQueryString( "SELECT uuid from admin.keyspace_master where keyspace_name = '" + keyspace + "' allow filtering"); - Row rs = MusicCore.get(pQuery).one(); + Row rs = musicCore.get(pQuery).one(); try { uuid = rs.getUUID("uuid").toString(); } catch (Exception e) { @@ -286,7 +289,7 @@ public class CachingUtil implements Runnable { pQuery.appendQueryString( "SELECT application_name from admin.keyspace_master where keyspace_name = '" + keyspace + "' allow filtering"); - Row rs = MusicCore.get(pQuery).one(); + Row rs = musicCore.get(pQuery).one(); try { appName = rs.getString("application_name"); } catch (Exception e) { @@ -335,7 +338,7 @@ public class CachingUtil implements Runnable { } Row rs = null; try { - rs = MusicCore.get(queryObject).one(); + rs = musicCore.get(queryObject).one(); } catch (MusicServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -386,7 +389,7 @@ public class CachingUtil implements Runnable { } Row rs = null; try { - rs = MusicCore.get(queryObject).one(); + rs = musicCore.get(queryObject).one(); } catch (MusicServiceException e) { e.printStackTrace(); resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage()); diff --git a/src/main/java/org/onap/music/main/CronJobManager.java b/src/main/java/org/onap/music/main/CronJobManager.java index 5b7a8de4..2ed1a97e 100644 --- a/src/main/java/org/onap/music/main/CronJobManager.java +++ b/src/main/java/org/onap/music/main/CronJobManager.java @@ -34,6 +34,8 @@ import javax.servlet.annotation.WebListener; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -42,6 +44,7 @@ import com.datastax.driver.core.Row; public class CronJobManager implements ServletContextListener { private ScheduledExecutorService scheduler; + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); @Override public void contextInitialized(ServletContextEvent event) { @@ -51,7 +54,7 @@ public class CronJobManager implements ServletContextListener { 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); + ResultType result = musicCore.nonKeyRelatedPut(pQuery, consistency); } catch (MusicServiceException e1) { e1.printStackTrace(); } @@ -60,7 +63,7 @@ public class CronJobManager implements ServletContextListener { pQuery.appendQueryString( "select * from admin.locks"); try { - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); Iterator<Row> it = rs.iterator(); StringBuilder deleteKeys = new StringBuilder(); Boolean expiredKeys = false; @@ -71,7 +74,7 @@ public class CronJobManager implements ServletContextListener { if(System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) { expiredKeys = true; String new_id = id.substring(1); - MusicCore.deleteLock(new_id); + musicCore.deleteLock(new_id); deleteKeys.append(id).append(","); } else { @@ -103,7 +106,7 @@ public class CronJobManager implements ServletContextListener { expiredKeys = true; String id = pair.getKey(); deleteKeys.append("'").append(id).append("'").append(","); - MusicCore.deleteLock(id.substring(1)); + musicCore.deleteLock(id.substring(1)); MusicUtil.zkNodeMap.remove(id); } catch (MusicLockingException e) { @@ -129,7 +132,7 @@ public class CronJobManager implements ServletContextListener { pQuery.appendQueryString( "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")"); try { - MusicCore.nonKeyRelatedPut(pQuery, "eventual"); + musicCore.nonKeyRelatedPut(pQuery, "eventual"); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/org/onap/music/main/VotingAppJar.java b/src/main/java/org/onap/music/main/VotingAppJar.java index 1c475639..68c6923c 100644 --- a/src/main/java/org/onap/music/main/VotingAppJar.java +++ b/src/main/java/org/onap/music/main/VotingAppJar.java @@ -7,7 +7,8 @@ import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -19,6 +20,7 @@ public class VotingAppJar { String keyspaceName; String tableName; + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); public VotingAppJar() throws MusicServiceException { keyspaceName = "VotingAppForMusic"; @@ -47,7 +49,7 @@ public class VotingAppJar "CREATE KEYSPACE " + keyspaceName + " WITH REPLICATION = " + replicationInfo.toString().replaceAll("=", ":")); try { - MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + musicCore.nonKeyRelatedPut(queryObject, "eventual"); } catch (MusicServiceException e) { if (e.getMessage().equals("Keyspace votingappformusic already exists")) { // ignore @@ -63,7 +65,7 @@ public class VotingAppJar "CREATE TABLE " + keyspaceName + "." + tableName + " (name text PRIMARY KEY, count varint);"); try { - MusicCore.createTable(keyspaceName, tableName, queryObject, "eventual"); + musicCore.createTable(keyspaceName, tableName, queryObject, "eventual"); } catch (MusicServiceException e) { if (e.getMessage().equals("Table votingappformusic.votevount already exists")) { //ignore @@ -79,7 +81,7 @@ public class VotingAppJar "INSERT INTO " + keyspaceName + "." + tableName + " (name, count) " + "VALUES ('"+candidateName+"', 0);"); - MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + musicCore.nonKeyRelatedPut(queryObject, "eventual"); } public void vote() throws MusicLockingException, MusicQueryException, MusicServiceException { @@ -94,13 +96,13 @@ public class VotingAppJar queryObject.appendQueryString( "INSERT INTO " + keyspaceName + "." + tableName + " (name, count) " + "VALUES ('"+candidateName+"', "+numVotes+");"); - MusicCore.atomicPut(keyspaceName, tableName, candidateName, queryObject, null); + musicCore.atomicPut(keyspaceName, tableName, candidateName, queryObject, null); } private void readAllVotes() throws MusicServiceException { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("SELECT * FROM " + keyspaceName + "." + tableName); - ResultSet rs = MusicCore.get(queryObject); + ResultSet rs = musicCore.get(queryObject); for(Row candidate : rs.all()) { System.out.println(candidate.getString("name") + " - " + candidate.getVarint("count")); } diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java index 6a843607..958ef6ea 100644 --- a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java +++ b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java @@ -24,7 +24,7 @@ package org.onap.music.response.jsonobjects; import java.util.HashMap; import java.util.Map; -import org.onap.music.datastore.MusicLockState.LockStatus; +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; import org.onap.music.main.ResultType; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 90436499..9ae7bc32 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -47,9 +47,11 @@ 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.main.CachingUtil; -import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; + import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -63,6 +65,7 @@ import io.swagger.annotations.ApiOperation; public class RestMusicAdminAPI { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); /* * API to onboard an application with MUSIC. This is the mandatory first step. @@ -93,7 +96,7 @@ public class RestMusicAdminAPI { pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); if (!rs.all().isEmpty()) { resultMap.put("Exception", "Application " + appName + " has already been onboarded. Please contact admin."); @@ -114,7 +117,7 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - String returnStr = MusicCore.eventualPut(pQuery).toString(); + String returnStr = musicCore.eventualPut(pQuery).toString(); if (returnStr.contains("Failure")) { resultMap.put("Exception", "Oops. Something wrong with onboarding process. Please retry later or contact admin."); @@ -170,7 +173,7 @@ public class RestMusicAdminAPI { if (isAAF != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), Boolean.parseBoolean(isAAF))); - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); Iterator<Row> it = rs.iterator(); while (it.hasNext()) { Row row = (Row) it.next(); @@ -215,20 +218,20 @@ public class RestMusicAdminAPI { "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - Row row = MusicCore.get(pQuery).one(); + Row row = musicCore.get(pQuery).one(); if (row != null) { String ks = row.getString("keyspace_name"); if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); + musicCore.nonKeyRelatedPut(queryObject, consistency); } } pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + ResultType result = musicCore.nonKeyRelatedPut(pQuery, consistency); if (result == ResultType.SUCCESS) { resultMap.put("Success", "Your application has been deleted successfully"); } else { @@ -245,7 +248,7 @@ public class RestMusicAdminAPI { pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); List<Row> rows = rs.all(); String uuid = null; if (rows.size() == 0) { @@ -261,19 +264,19 @@ public class RestMusicAdminAPI { "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(uuid))); - Row row = MusicCore.get(pQuery).one(); + Row row = musicCore.get(pQuery).one(); String ks = row.getString("keyspace_name"); if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("DROP KEYSPACE " + ks + ";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); + musicCore.nonKeyRelatedPut(queryObject, consistency); } pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(uuid))); - MusicCore.eventualPut(pQuery); + musicCore.eventualPut(pQuery); resultMap.put("Success", "Your application " + appName + " has been deleted."); return Response.status(Status.OK).entity(resultMap).build(); } else { @@ -323,7 +326,7 @@ public class RestMusicAdminAPI { pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - ResultSet rs = MusicCore.get(pQuery); + ResultSet rs = musicCore.get(pQuery); if (!rs.all().isEmpty()) { resultMap.put("Exception", "Application " + appName + " has already been onboarded. Please contact admin."); @@ -356,7 +359,7 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + ResultType result = musicCore.nonKeyRelatedPut(pQuery, consistency); if (result == ResultType.SUCCESS) { resultMap.put("Success", "Your application has been updated successfully"); diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index 99c60b30..986d25ec 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -48,6 +48,7 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -62,12 +63,14 @@ 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.main.CachingUtil; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicCore.Condition; +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; @@ -111,6 +114,7 @@ public class RestMusicDataAPI { private static final String XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final String VERSION = "v2"; + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); private class RowIdentifier { public String primarKeyValue; @@ -170,7 +174,7 @@ public class RestMusicDataAPI { try { - authMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "createKeySpace"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); @@ -215,7 +219,7 @@ public class RestMusicDataAPI { ResultType result = ResultType.FAILURE; try { - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + result = musicCore.nonKeyRelatedPut(queryObject, consistency); logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); } catch ( MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); @@ -226,12 +230,12 @@ public class RestMusicDataAPI { queryObject = new PreparedQueryObject(); queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); + musicCore.nonKeyRelatedPut(queryObject, consistency); queryObject = new PreparedQueryObject(); queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName + " to '" + userId + "'"); queryObject.appendQueryString(";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); + musicCore.nonKeyRelatedPut(queryObject, consistency); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); } @@ -252,7 +256,7 @@ public class RestMusicDataAPI { queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); CachingUtil.updateMusicCache(keyspaceName, ns); CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); - MusicCore.eventualPut(queryObject); + musicCore.eventualPut(queryObject); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); @@ -286,7 +290,7 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password,keyspaceName, aid, "dropKeySpace"); + Map<String, Object> authMap = MusicAuthentication.authenticate(ns, userId, password,keyspaceName, aid, "dropKeySpace"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -302,7 +306,7 @@ public class RestMusicDataAPI { pQuery.appendQueryString( "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - Row row = MusicCore.get(pQuery).one(); + Row row = musicCore.get(pQuery).one(); long count = row.getLong(0); if (count == 0) { @@ -316,17 +320,17 @@ public class RestMusicDataAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicUtil.DEFAULTKEYSPACENAME)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - MusicCore.nonKeyRelatedPut(pQuery, consistency); + musicCore.nonKeyRelatedPut(pQuery, consistency); } else { pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - MusicCore.nonKeyRelatedPut(pQuery, consistency); + musicCore.nonKeyRelatedPut(pQuery, consistency); } PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";"); - ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + ResultType result = musicCore.nonKeyRelatedPut(queryObject, consistency); if ( result.equals(ResultType.FAILURE) ) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build(); } @@ -363,7 +367,7 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace, + Map<String, Object> authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "createTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); @@ -549,7 +553,7 @@ public class RestMusicDataAPI { ResultType result = ResultType.FAILURE; try { //logger.info("cjc query="+queryObject.getQuery()); - result = MusicCore.createTable(keyspace, tablename, queryObject, consistency); + result = musicCore.createTable(keyspace, tablename, queryObject, consistency); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); response.status(Status.BAD_REQUEST); @@ -589,7 +593,7 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace,aid, "createIndex"); + Map<String, Object> authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace,aid, "createIndex"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -607,7 +611,7 @@ public class RestMusicDataAPI { ResultType result = ResultType.FAILURE; try { - result = MusicCore.nonKeyRelatedPut(query, "eventual"); + result = musicCore.nonKeyRelatedPut(query, "eventual"); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); response.status(Status.BAD_REQUEST); @@ -653,7 +657,7 @@ public class RestMusicDataAPI { Map<String, Object> authMap = null; try { - authMap = MusicCore.authenticate(ns, userId, password, keyspace, + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "insertIntoTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -670,7 +674,7 @@ public class RestMusicDataAPI { PreparedQueryObject queryObject = new PreparedQueryObject(); TableMetadata tableInfo = null; try { - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); if(tableInfo == null) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build(); } @@ -795,7 +799,7 @@ public class RestMusicDataAPI { String consistency = insObj.getConsistencyInfo().get("type"); try { if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { - result = MusicCore.eventualPut(queryObject); + result = musicCore.eventualPut(queryObject); } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { String lockId = insObj.getConsistencyInfo().get("lockId"); if(lockId == null) { @@ -804,9 +808,9 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); } - result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null); + result = musicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null); + result = musicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null); } } catch (Exception ex) { @@ -859,7 +863,7 @@ public class RestMusicDataAPI { String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap; try { - authMap = MusicCore.authenticate(ns, userId, password, keyspace, + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "updateTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -884,7 +888,7 @@ public class RestMusicDataAPI { TableMetadata tableInfo; try { - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); } catch (MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); @@ -970,14 +974,14 @@ public class RestMusicDataAPI { selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new MusicCore.Condition(updateObj.getConditions(), selectQuery); + conditionInfo = new Condition(updateObj.getConditions(), selectQuery); } ReturnType operationResult = null; long jsonParseCompletionTime = System.currentTimeMillis(); if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) - operationResult = MusicCore.eventualPut(queryObject); + operationResult = musicCore.eventualPut(queryObject); else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { String lockId = updateObj.getConsistencyInfo().get("lockId"); if(lockId == null) { @@ -986,11 +990,11 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); } - operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, + operationResult = musicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, queryObject, lockId, conditionInfo); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { try { - operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, + operationResult = musicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); } catch (MusicLockingException | MusicQueryException | MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); @@ -1063,7 +1067,7 @@ public class RestMusicDataAPI { String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = null; try { - authMap = MusicCore.authenticate(ns, userId, password, keyspace, + authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "deleteFromTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -1127,7 +1131,7 @@ public class RestMusicDataAPI { selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new MusicCore.Condition(delObj.getConditions(), selectQuery); + conditionInfo = new Condition(delObj.getConditions(), selectQuery); } String consistency = delObj.getConsistencyInfo().get("type"); @@ -1135,7 +1139,7 @@ public class RestMusicDataAPI { ReturnType operationResult = null; try { if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) - operationResult = MusicCore.eventualPut(queryObject); + operationResult = musicCore.eventualPut(queryObject); else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { String lockId = delObj.getConsistencyInfo().get("lockId"); if(lockId == null) { @@ -1144,10 +1148,10 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); } - operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, + operationResult = musicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, queryObject, lockId, conditionInfo); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, + operationResult = musicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); } } catch (MusicLockingException | MusicQueryException | MusicServiceException e) { @@ -1199,7 +1203,7 @@ public class RestMusicDataAPI { String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = - MusicCore.authenticate(ns, userId, password, keyspace, aid, "dropTable"); + MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "dropTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -1211,7 +1215,7 @@ public class RestMusicDataAPI { PreparedQueryObject query = new PreparedQueryObject(); query.appendQueryString("DROP TABLE " + keyspace + "." + tablename + ";"); try { - return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(musicCore.nonKeyRelatedPut(query, consistency)).toMap()).build(); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); @@ -1254,7 +1258,7 @@ public class RestMusicDataAPI { Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> authMap = MusicCore.authenticate(ns, userId, password, keyspace,aid, "selectCritical"); + Map<String, Object> authMap = MusicAuthentication.authenticate(ns, userId, password, keyspace,aid, "selectCritical"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -1286,13 +1290,13 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); } - results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject, + results = musicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject, lockId); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject); + results = musicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject); } if(results!=null && results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); @@ -1333,7 +1337,7 @@ public class RestMusicDataAPI { String userId = userCredentials.get(MusicUtil.USERID); String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = - MusicCore.authenticate(ns, userId, password, keyspace, aid, "select"); + MusicAuthentication.authenticate(ns, userId, password, keyspace, aid, "select"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { @@ -1356,9 +1360,9 @@ public class RestMusicDataAPI { } try { - ResultSet results = MusicCore.get(queryObject); + ResultSet results = musicCore.get(queryObject); if(results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); } catch (MusicServiceException ex) { @@ -1412,7 +1416,7 @@ public class RestMusicDataAPI { throws MusicServiceException { StringBuilder rowSpec = new StringBuilder(); int counter = 0; - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); if (tableInfo == null) { logger.error(EELFLoggerDelegate.errorLogger, "Table information not found. Please check input for table name= " diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 835dda14..92dd625e 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -40,12 +40,14 @@ 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.datastore.MusicLockState; -import org.onap.music.main.MusicCore; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -60,6 +62,7 @@ public class RestMusicLocksAPI { private static final String XMINORVERSION = "X-minorVersion"; private static final String XPATCHVERSION = "X-patchVersion"; private static final String VERSION = "v2"; + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); /** * Puts the requesting process in the q for this lock. The corresponding @@ -86,7 +89,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockName); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -96,7 +99,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "createLockReference"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -105,7 +108,7 @@ public class RestMusicLocksAPI { return response.status(Status.UNAUTHORIZED).entity(resultMap).build(); } ResultType status = ResultType.SUCCESS; - String lockId = MusicCore.createLockReference(lockName); + String lockId = musicCore.createLockReference(lockName); if (lockId == null) { status = ResultType.FAILURE; @@ -138,7 +141,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockId); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -148,7 +151,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "accquireLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -158,7 +161,7 @@ public class RestMusicLocksAPI { } try { String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId); + ReturnType lockStatus = musicCore.acquireLock(lockName,lockId); if ( lockStatus.getResult().equals(ResultType.SUCCESS)) { response.status(Status.OK); } else { @@ -188,7 +191,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockId); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -198,7 +201,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "accquireLockWithLease"); if (resultMap.containsKey("aid")) @@ -208,7 +211,7 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); + ReturnType lockLeaseStatus = musicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); if ( lockLeaseStatus.getResult().equals(ResultType.SUCCESS)) { response.status(Status.OK); } else { @@ -235,7 +238,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockName); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -245,7 +248,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "currentLockHolder"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -253,7 +256,7 @@ public class RestMusicLocksAPI { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - String who = MusicCore.whoseTurnIsIt(lockName); + String who = musicCore.whoseTurnIsIt(lockName); ResultType status = ResultType.SUCCESS; String error = ""; if ( who == null ) { @@ -284,14 +287,14 @@ public class RestMusicLocksAPI { @ApiParam(value = "Password", required = true) @HeaderParam("password") String password) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockName); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "currentLockState"); if (resultMap.containsKey("aid")) @@ -301,7 +304,7 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - org.onap.music.datastore.MusicLockState mls = MusicCore.getMusicLockState(lockName); + org.onap.music.lockingservice.cassandra.MusicLockState mls = MusicCassaCore.getMusicLockState(lockName); Map<String,Object> returnMap = null; JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName); if(mls == null) { @@ -338,7 +341,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockId); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -348,7 +351,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "unLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -357,7 +360,7 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } String fullyQualifiedKey = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - MusicLockState mls = MusicCore.voluntaryReleaseLock(fullyQualifiedKey, lockId); + MusicLockState mls = musicCore.voluntaryReleaseLock(fullyQualifiedKey, lockId); if(mls.getErrorMessage() != null) { resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage()); @@ -396,7 +399,7 @@ public class RestMusicLocksAPI { @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - Map<String, Object> resultMap = MusicCore.validateLock(lockName); + Map<String, Object> resultMap = MusicCassaCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); @@ -406,7 +409,7 @@ public class RestMusicLocksAPI { String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); - resultMap = MusicCore.authenticate(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.authenticate(ns, userId, password, keyspaceName, aid, "deleteLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -415,7 +418,7 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } try{ - MusicCore.deleteLock(lockName); + musicCore.deleteLock(lockName); }catch (Exception e) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index 8af334c7..9248ee1a 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -45,14 +45,17 @@ 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.apache.commons.lang3.StringUtils; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.ResultSet; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; // cjc import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -64,6 +67,7 @@ import io.swagger.annotations.ApiParam; public class RestMusicQAPI { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); + private static MusicCoreService musicCore = MusicCassaCore.getInstance(); // private static String xLatestVersion = "X-latestVersion"; /* * private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); @@ -412,9 +416,9 @@ public class RestMusicQAPI { } try { - ResultSet results = MusicCore.get(queryObject); + ResultSet results = musicCore.get(queryObject); return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) - .setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + .setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); diff --git a/src/main/java/org/onap/music/service/MusicCoreService.java b/src/main/java/org/onap/music/service/MusicCoreService.java new file mode 100644 index 00000000..6b7cc65c --- /dev/null +++ b/src/main/java/org/onap/music/service/MusicCoreService.java @@ -0,0 +1,94 @@ +/* + * ============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.service; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.lockingservice.cassandra.*; + +import com.datastax.driver.core.ResultSet; + + + +/** + * @author srupane + * + */ +public interface MusicCoreService { + + // Core Music Database Methods + + + public ReturnType eventualPut(PreparedQueryObject queryObject); + + public ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, String lockId, Condition conditionInfo); + + public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) + throws MusicServiceException; + + public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException; + + public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException; + + public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException; + + public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) + throws MusicLockingException, MusicQueryException, MusicServiceException; + + public ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, String lockId) throws MusicServiceException; + + // Core Music Locking Service Methods + + public String createLockReference(String fullyQualifiedKey); // lock name + + public ReturnType acquireLockWithLease(String key, String lockReference, long leasePeriod) + throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id,time + + public ReturnType acquireLock(String key, String lockReference) + throws MusicLockingException, MusicQueryException, MusicServiceException; // key,lock id + + public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, + String consistency) throws MusicServiceException; + + public ResultSet quorumGet(PreparedQueryObject query); + + public String whoseTurnIsIt(String fullyQualifiedKey);// lock name + + public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference); // lock name, lock id + + public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) + throws MusicLockingException;// lock name,lock id + + public void deleteLock(String lockName) throws MusicLockingException; + +} diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/service/impl/MusicCassaCore.java index d7c5bcec..b145081a 100644 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ b/src/main/java/org/onap/music/service/impl/MusicCassaCore.java @@ -19,7 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ -package org.onap.music.main; +package org.onap.music.service.impl; import java.io.StringWriter; @@ -28,10 +28,9 @@ import java.util.Map; import java.util.StringTokenizer; import java.util.UUID; -import org.onap.music.datastore.CassaDataStore; -import org.onap.music.datastore.CassaLockStore; -import org.onap.music.datastore.CassaLockStore.LockObject; -import org.onap.music.datastore.MusicLockState; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.Condition; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; @@ -40,6 +39,13 @@ 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.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.service.MusicCoreService; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; @@ -54,38 +60,31 @@ import com.datastax.driver.core.TableMetadata; * * */ -public class MusicCore { +public class MusicCassaCore implements MusicCoreService { - public static CassaLockStore mLockHandle = null; - public static CassaDataStore mDstoreHandle = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); + public static CassaLockStore mLockHandle = null;; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class); private static boolean unitTestRun=true; + private static MusicCassaCore musicCassaCoreInstance = null; - 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 = results.one(); - return getDSHandle().doesRowSatisfyCondition(row, conditions); - } + private MusicCassaCore() { + } - - + public static MusicCassaCore getInstance() { + + if(musicCassaCoreInstance == null) { + musicCassaCoreInstance = new MusicCassaCore(); + } + return musicCassaCoreInstance; + } + public static CassaLockStore getLockingServiceHandle() throws MusicLockingException { logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); long start = System.currentTimeMillis(); if (mLockHandle == null) { try { - mLockHandle = new CassaLockStore(getDSHandle()); + mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle()); } 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); @@ -96,61 +95,9 @@ public class MusicCore { return mLockHandle; } - /** - * - * @param remoteIp - * @return - */ - public static CassaDataStore getDSHandle(String remoteIp) { - logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); - long start = System.currentTimeMillis(); - if (mDstoreHandle == null) { - try { - MusicUtil.loadProperties(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default."); - } - mDstoreHandle = new CassaDataStore(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 CassaDataStore getDSHandle() throws MusicServiceException { - - logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); - long start = System.currentTimeMillis(); - if (mDstoreHandle == null) { - try { - MusicUtil.loadProperties(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default."); - } - // Quick Fix - Best to put this into every call to getDSHandle? - if (! MusicUtil.getMyCassaHost().equals("localhost") ) { - mDstoreHandle = new CassaDataStore(MusicUtil.getMyCassaHost()); - } else { - mDstoreHandle = new CassaDataStore(); - } - } - 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 fullyQualifiedKey) { + public String createLockReference(String fullyQualifiedKey) { String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; String table = splitString[1]; @@ -170,12 +117,12 @@ public class MusicCore { } - public static ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException { + public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException { evictExpiredLockHolder(fullyQualifiedKey,leasePeriod); return acquireLock(fullyQualifiedKey, lockReference); } - private static void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException { + private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod) throws MusicLockingException, MusicQueryException, MusicServiceException { String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; @@ -215,7 +162,7 @@ public class MusicCore { return new ReturnType(ResultType.SUCCESS, lockReference+" is top of lock store"); } - public static ReturnType acquireLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException, MusicQueryException, MusicServiceException { + public ReturnType acquireLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException, MusicQueryException, MusicServiceException { String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; String table = splitString[1]; @@ -231,7 +178,7 @@ public class MusicCore { String query = "select * from "+syncTable+" where key='"+fullyQualifiedKey+"';"; PreparedQueryObject readQueryObject = new PreparedQueryObject(); readQueryObject.appendQueryString(query); - ResultSet results = getDSHandle().executeCriticalGet(readQueryObject); + ResultSet results = MusicDataStoreHandle.getDSHandle().executeCriticalGet(readQueryObject); if (results.all().size() != 0) { logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!"); try { @@ -245,7 +192,7 @@ public class MusicCore { String cleanQuery = "delete * from music_internal.unsynced_keys where key='"+fullyQualifiedKey+"';"; PreparedQueryObject deleteQueryObject = new PreparedQueryObject(); deleteQueryObject.appendQueryString(cleanQuery); - getDSHandle().executePut(deleteQueryObject, "critical"); + MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical"); } getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockReference); @@ -264,7 +211,7 @@ public class MusicCore { * * */ - public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, String consistency) throws MusicServiceException { + public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject, String consistency) throws MusicServiceException { boolean result = false; try { @@ -285,11 +232,11 @@ public class MusicCore { queryObject.appendQueryString(tabQuery); result = false; - result = getDSHandle().executePut(queryObject, "eventual"); + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual"); //create actual table - result = getDSHandle().executePut(tableQueryObject, consistency); + result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency); } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); throw new MusicServiceException(ex.getMessage()); @@ -303,7 +250,7 @@ public class MusicCore { PreparedQueryObject updateQuery = new PreparedQueryObject(); // get the primary key d - TableMetadata tableInfo = returnColumnMetadata(keyspace, table); + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table); String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();// we only support single // primary key DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); @@ -316,7 +263,7 @@ public class MusicCore { selectQuery.addValue(cqlFormattedPrimaryKeyValue); ResultSet results = null; try { - results = getDSHandle().executeCriticalGet(selectQuery); + results = MusicDataStoreHandle.getDSHandle().executeCriticalGet(selectQuery); // write it back to a quorum Row row = results.one(); ColumnDefinitions colInfo = row.getColumnDefinitions(); @@ -328,7 +275,7 @@ public class MusicCore { if (colName.equals(primaryKeyName)) continue; DataType colType = definition.getType(); - Object valueObj = getDSHandle().getColValue(row, colName, colType); + Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType); Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); fieldValueString.append(colName + " = ?"); updateQuery.addValue(valueString); @@ -340,7 +287,7 @@ public class MusicCore { + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";"); updateQuery.addValue(cqlFormattedPrimaryKeyValue); - getDSHandle().executePut(updateQuery, "critical"); + MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical"); } catch (MusicServiceException | MusicQueryException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR); } @@ -354,10 +301,10 @@ public class MusicCore { * @param query * @return ResultSet */ - public static ResultSet quorumGet(PreparedQueryObject query) { + public ResultSet quorumGet(PreparedQueryObject query) { ResultSet results = null; try { - results = getDSHandle().executeCriticalGet(query); + results = MusicDataStoreHandle.getDSHandle().executeCriticalGet(query); } catch (MusicServiceException | MusicQueryException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR); @@ -366,22 +313,14 @@ public class MusicCore { } - /** - * - * @param results - * @return - * @throws MusicServiceException - */ - public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException { - return getDSHandle().marshalData(results); - } + /** * * @param fullyQualifiedKey lockName * @return */ - public static String whoseTurnIsIt(String fullyQualifiedKey) { + public String whoseTurnIsIt(String fullyQualifiedKey) { String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; String table = splitString[1]; @@ -404,7 +343,7 @@ public class MusicCore { return st.nextToken("$"); } - public static MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) { + public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) { long start = System.currentTimeMillis(); String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; @@ -420,11 +359,11 @@ public class MusicCore { return getMusicLockState(fullyQualifiedKey); } - public static MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException{ + public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException{ return destroyLockRef(fullyQualifiedKey, lockReference); } - public static MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException, MusicServiceException, MusicQueryException{ + public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException, MusicServiceException, MusicQueryException{ String[] splitString = fullyQualifiedKey.split("\\."); String keyspace = splitString[0]; String table = splitString[1]; @@ -436,7 +375,7 @@ public class MusicCore { queryObject.addValue(fullyQualifiedKey); String insQuery = "insert into "+syncTable+" (key) values "+values+"';"; queryObject.appendQueryString(insQuery); - getDSHandle().executePut(queryObject, "critical"); + MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical"); //now release the lock return destroyLockRef(fullyQualifiedKey, lockReference); @@ -447,26 +386,10 @@ public class MusicCore { * @param lockName * @throws MusicLockingException */ - public static void deleteLock(String lockName) throws MusicLockingException { + public void deleteLock(String lockName) throws MusicLockingException { //deprecated } - - - /** - * - * @param keyspace - * @param tablename - * @return - * @throws MusicServiceException - */ - public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { - return getDSHandle().returnColumnMetadata(keyspace, tablename); - } - - - - // Prepared Query Additions. /** @@ -475,10 +398,10 @@ public class MusicCore { * @return ReturnType * @throws MusicServiceException */ - public static ReturnType eventualPut(PreparedQueryObject queryObject) { + public ReturnType eventualPut(PreparedQueryObject queryObject) { boolean result = false; try { - result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); + result = MusicDataStoreHandle.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); @@ -500,7 +423,7 @@ public class MusicCore { * @param lockReference * @return */ - public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, + public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue, PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) { long start = System.currentTimeMillis(); try { @@ -522,7 +445,7 @@ public class MusicCore { String query = queryObject.getQuery(); query = query.replaceFirst("SET", "using TIMESTAMP "+ v2sTimeStampInMicroseconds(lockReference, System.currentTimeMillis())+ " SET"); queryObject.replaceQueryString(query); - getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); + MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); long end = System.currentTimeMillis(); logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); }catch (MusicQueryException | MusicServiceException | MusicLockingException e) { @@ -544,12 +467,12 @@ public class MusicCore { * * */ - public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException { + public 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); + result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency); } catch (MusicQueryException | MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); @@ -565,10 +488,10 @@ public class MusicCore { * @return ResultSet * @throws MusicServiceException */ - public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { + public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { ResultSet results = null; try { - results = getDSHandle().executeEventualGet(queryObject); + results = MusicDataStoreHandle.getDSHandle().executeEventualGet(queryObject); } catch (MusicQueryException | MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); throw new MusicServiceException(e.getMessage()); @@ -587,7 +510,7 @@ public class MusicCore { * @param lockReference lock ID to check if the resource is free to perform the operation. * @return ResultSet */ - public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, + public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue, PreparedQueryObject queryObject, String lockReference) throws MusicServiceException { ResultSet results = null; @@ -595,7 +518,7 @@ public class MusicCore { ReturnType result = isTopOfLockStore(keyspace, table, primaryKeyValue, lockReference); if(result.getResult().equals(ResultType.FAILURE)) return null;//not top of the lock store q - results = getDSHandle().executeCriticalGet(queryObject); + results = MusicDataStoreHandle.getDSHandle().executeCriticalGet(queryObject); } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); } @@ -614,7 +537,7 @@ public class MusicCore { * @throws MusicServiceException * @throws MusicQueryException */ - public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, + public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException, MusicQueryException, MusicServiceException { long start = System.currentTimeMillis(); String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; @@ -657,7 +580,7 @@ public class MusicCore { * @throws MusicLockingException * @throws MusicQueryException */ - public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, + public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey, PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException { String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey; String lockReference = createLockReference(fullyQualifiedKey); @@ -681,96 +604,7 @@ public class MusicCore { 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> authenticate(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); - } - - return resultMap; - } + /** * @param lockName @@ -823,4 +657,13 @@ public class MusicCore { x = x.replaceFirst("top", "sword"); System.out.print(x); //returns sword pickaxe } + + + + @Override + public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey, + PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException { + //Deprecated + return null; + } } diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/src/test/java/org/onap/music/unittests/CassandraCQLQueries.java index a9cbe109..41c518e9 100644 --- a/src/test/java/org/onap/music/unittests/CassandraCQL.java +++ b/src/test/java/org/onap/music/unittests/CassandraCQLQueries.java @@ -45,10 +45,10 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.thrift.transport.TTransportException; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.onap.music.datastore.CassaDataStore; +import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; -public class CassandraCQL { +public class CassandraCQLQueries { public static final String createKeySpace = "CREATE KEYSPACE IF NOT EXISTS testCassa WITH replication = " @@ -222,7 +222,7 @@ public class CassandraCQL { return allPossibleIps; } - public static CassaDataStore connectToEmbeddedCassandra() { + public static MusicDataStore connectToEmbeddedCassandra() { Iterator<String> it = getAllPossibleLocalIps().iterator(); String address = "localhost"; @@ -249,7 +249,7 @@ public class CassandraCQL { } } - return new CassaDataStore(cluster, session); + return new MusicDataStore(cluster, session); } diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java index 3f7fd3b7..62275bb3 100644 --- a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java +++ b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java @@ -33,7 +33,7 @@ import org.mockito.Mock; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.datastore.CassaDataStore; +import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.DataType; @@ -44,12 +44,12 @@ import com.datastax.driver.core.TableMetadata; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MusicDataStoreTest { - static CassaDataStore dataStore; + static MusicDataStore dataStore; static PreparedQueryObject testObject; @BeforeClass public static void init() { - dataStore = CassandraCQL.connectToEmbeddedCassandra(); + dataStore = CassandraCQLQueries.connectToEmbeddedCassandra(); } @@ -57,7 +57,7 @@ public class MusicDataStoreTest { public static void close() throws MusicServiceException, MusicQueryException { testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.dropKeyspace); + testObject.appendQueryString(CassandraCQLQueries.dropKeyspace); dataStore.executePut(testObject, "eventual"); dataStore.close(); @@ -67,10 +67,10 @@ public class MusicDataStoreTest { public void Test1_SetUp() throws MusicServiceException, MusicQueryException { boolean result = false; testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createKeySpace); + testObject.appendQueryString(CassandraCQLQueries.createKeySpace); result = dataStore.executePut(testObject, "eventual");; testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createTableEmployees); + testObject.appendQueryString(CassandraCQLQueries.createTableEmployees); result = dataStore.executePut(testObject, "eventual"); assertEquals(true, result); @@ -78,21 +78,21 @@ public class MusicDataStoreTest { @Test public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedInsertQueryObject1(); + testObject = CassandraCQLQueries.setPreparedInsertQueryObject1(); boolean result = dataStore.executePut(testObject, "eventual"); assertEquals(true, result); } @Test public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedInsertQueryObject2(); + testObject = CassandraCQLQueries.setPreparedInsertQueryObject2(); boolean result = dataStore.executePut(testObject, "Critical"); assertEquals(true, result); } @Test public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedUpdateQueryObject(); + testObject = CassandraCQLQueries.setPreparedUpdateQueryObject(); boolean result = false; result = dataStore.executePut(testObject, "eventual"); assertEquals(true, result); @@ -101,7 +101,7 @@ public class MusicDataStoreTest { @Test public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException { testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.selectALL); + testObject.appendQueryString(CassandraCQLQueries.selectALL); boolean result = false; int count = 0; ResultSet output = null; @@ -120,7 +120,7 @@ public class MusicDataStoreTest { @Test public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedGetQuery(); + testObject = CassandraCQLQueries.setPreparedGetQuery(); boolean result = false; int count = 0; ResultSet output = null; diff --git a/src/test/java/org/onap/music/unittests/MusicLockStoreTest.java b/src/test/java/org/onap/music/unittests/MusicLockStoreTest.java index 86774538..45ce9296 100644 --- a/src/test/java/org/onap/music/unittests/MusicLockStoreTest.java +++ b/src/test/java/org/onap/music/unittests/MusicLockStoreTest.java @@ -32,9 +32,8 @@ import org.junit.runners.MethodSorters; import org.mockito.Mock; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; - -import org.onap.music.datastore.CassaDataStore; -import org.onap.music.datastore.CassaLockStore; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.DataType; @@ -45,13 +44,13 @@ import com.datastax.driver.core.TableMetadata; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MusicLockStoreTest { - static CassaDataStore dataStore; + static MusicDataStore dataStore; static CassaLockStore lockStore; static PreparedQueryObject testObject; @BeforeClass public static void init() { - dataStore = CassandraCQL.connectToEmbeddedCassandra(); + dataStore = CassandraCQLQueries.connectToEmbeddedCassandra(); lockStore = new CassaLockStore(dataStore); } @@ -59,7 +58,7 @@ public class MusicLockStoreTest { @AfterClass public static void close() throws MusicServiceException, MusicQueryException { testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.dropKeyspace); + testObject.appendQueryString(CassandraCQLQueries.dropKeyspace); dataStore.executePut(testObject, "eventual"); dataStore.close(); @@ -69,10 +68,10 @@ public class MusicLockStoreTest { public void Test1_SetUp() throws MusicServiceException, MusicQueryException { boolean result = false; testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createKeySpace); + testObject.appendQueryString(CassandraCQLQueries.createKeySpace); result = dataStore.executePut(testObject, "eventual");; testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createTableEmployees); + testObject.appendQueryString(CassandraCQLQueries.createTableEmployees); result = dataStore.executePut(testObject, "eventual"); assertEquals(true, result); @@ -93,14 +92,14 @@ public class MusicLockStoreTest { @Test public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedInsertQueryObject2(); + testObject = CassandraCQLQueries.setPreparedInsertQueryObject2(); boolean result = dataStore.executePut(testObject, "Critical"); assertEquals(true, result); } @Test public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedUpdateQueryObject(); + testObject = CassandraCQLQueries.setPreparedUpdateQueryObject(); boolean result = false; result = dataStore.executePut(testObject, "eventual"); assertEquals(true, result); @@ -109,7 +108,7 @@ public class MusicLockStoreTest { @Test public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException { testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.selectALL); + testObject.appendQueryString(CassandraCQLQueries.selectALL); boolean result = false; int count = 0; ResultSet output = null; @@ -128,7 +127,7 @@ public class MusicLockStoreTest { @Test public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException { - testObject = CassandraCQL.setPreparedGetQuery(); + testObject = CassandraCQLQueries.setPreparedGetQuery(); boolean result = false; int count = 0; ResultSet output = null; diff --git a/src/test/java/org/onap/music/unittests/TestCassaLockStore.java b/src/test/java/org/onap/music/unittests/TestCassaLockStore.java index bf058121..2f3750a2 100644 --- a/src/test/java/org/onap/music/unittests/TestCassaLockStore.java +++ b/src/test/java/org/onap/music/unittests/TestCassaLockStore.java @@ -2,16 +2,18 @@ package org.onap.music.unittests; import java.util.HashMap; import java.util.Map; -import java.util.UUID; -import org.onap.music.datastore.CassaLockStore; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; public class TestCassaLockStore { + static MusicCoreService musicCore = MusicCassaCore.getInstance(); + public static void main(String[] args) { @@ -27,12 +29,12 @@ public class TestCassaLockStore { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("CREATE KEYSPACE " + keyspace + " WITH REPLICATION = " + replicationInfo.toString().replaceAll("=", ":")); - MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + musicCore.nonKeyRelatedPut(queryObject, "eventual"); queryObject = new PreparedQueryObject(); queryObject.appendQueryString("CREATE TABLE " + keyspace + "." + table + " (name text PRIMARY KEY, count varint);"); - MusicCore.createTable(keyspace, table, queryObject, "eventual"); + musicCore.createTable(keyspace, table, queryObject, "eventual"); lockStore.createLockQueue(keyspace, table); diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java index 01d2ffb6..6f0a93a0 100644 --- a/src/test/java/org/onap/music/unittests/TestMusicCore.java +++ b/src/test/java/org/onap/music/unittests/TestMusicCore.java @@ -1,10 +1,6 @@ package org.onap.music.unittests; -import static org.junit.Assert.assertEquals; - import java.util.HashMap; -import java.util.Iterator; -import java.util.List; import java.util.Map; import org.junit.AfterClass; @@ -13,12 +9,14 @@ import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.onap.music.datastore.CassaDataStore; -import org.onap.music.datastore.CassaLockStore; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ResultSet; @@ -27,16 +25,17 @@ import com.datastax.driver.core.ResultSet; public class TestMusicCore { static PreparedQueryObject testObject; - static CassaDataStore dataStore; + static MusicDataStore dataStore; String keyspace = "MusicCoreUnitTestKp"; String table = "SampleTable"; + static MusicCoreService musicCore = MusicCassaCore.getInstance(); @BeforeClass public static void init() { System.out.println("TestMusicCore Init"); try { - MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); - MusicCore.mLockHandle = new CassaLockStore(MusicCore.mDstoreHandle); + MusicDataStoreHandle.mDstoreHandle = CassandraCQLQueries.connectToEmbeddedCassandra(); + CassaLockStore mLockHandle = new CassaLockStore(MusicDataStoreHandle.mDstoreHandle); } catch (Exception e) { e.printStackTrace(); } @@ -46,9 +45,9 @@ public class TestMusicCore { public static void close() throws MusicServiceException, MusicQueryException { System.out.println("After class TestMusicCore"); testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.dropKeyspace); - MusicCore.eventualPut(testObject); - MusicCore.mDstoreHandle.close(); + testObject.appendQueryString(CassandraCQLQueries.dropKeyspace); + musicCore.eventualPut(testObject); + MusicDataStoreHandle.mDstoreHandle.close(); } @Test @@ -61,7 +60,7 @@ public class TestMusicCore { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString( "CREATE KEYSPACE " + keyspace + " WITH REPLICATION = " + replicationInfo.toString().replaceAll("=", ":")); - MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + musicCore.nonKeyRelatedPut(queryObject, "eventual"); //check with the system table in cassandra @@ -77,7 +76,7 @@ public class TestMusicCore { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString( "CREATE TABLE " + keyspace + "." + table + " (name text PRIMARY KEY, count varint);"); - MusicCore.createTable(keyspace, table, queryObject, "eventual"); + musicCore.createTable(keyspace, table, queryObject, "eventual"); //check with the system table in cassandra diff --git a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java index 9b4fc229..53b6d8bc 100644 --- a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java +++ b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java @@ -19,26 +19,29 @@ package org.onap.music.unittests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import java.io.File; + import java.util.List; -import org.apache.curator.test.TestingServer; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.datastore.CassaLockStore; -import org.onap.music.datastore.MusicLockState; -import org.onap.music.datastore.MusicLockState.LockStatus; -import org.onap.music.main.MusicCore; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; +import org.onap.music.service.MusicCoreService; +import org.onap.music.service.impl.*; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; +import org.onap.music.service.impl.MusicCassaCore; + import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -49,12 +52,13 @@ public class TestMusicCoreIntegration { static PreparedQueryObject testObject; static String lockId = null; static String lockName = "ks1.tb1.pk1"; + static MusicCassaCore musicCore = MusicCassaCore.getInstance(); @BeforeClass public static void init() throws Exception { try { - MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); - MusicCore.mLockHandle = new CassaLockStore(MusicCore.mDstoreHandle); + MusicDataStoreHandle.mDstoreHandle = CassandraCQLQueries.connectToEmbeddedCassandra(); + MusicCassaCore.mLockHandle = new CassaLockStore(MusicDataStoreHandle.mDstoreHandle); } catch (Exception e) { e.printStackTrace(); } @@ -64,31 +68,31 @@ public class TestMusicCoreIntegration { public static void tearDownAfterClass() throws Exception { System.out.println("After class"); testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.dropKeyspace); - MusicCore.eventualPut(testObject); - MusicCore.deleteLock(lockName); - MusicCore.mDstoreHandle.close(); + testObject.appendQueryString(CassandraCQLQueries.dropKeyspace); + musicCore.eventualPut(testObject); + musicCore.deleteLock(lockName); + MusicDataStoreHandle.mDstoreHandle.close(); } @Test public void Test1_SetUp() throws MusicServiceException, MusicQueryException { - MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); - MusicCore.mLockHandle = new CassaLockStore(MusicCore.mDstoreHandle); + MusicDataStoreHandle.mDstoreHandle = CassandraCQLQueries.connectToEmbeddedCassandra(); + MusicCassaCore.mLockHandle = new CassaLockStore(MusicDataStoreHandle.mDstoreHandle); ResultType result = ResultType.FAILURE; testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createKeySpace); - MusicCore.eventualPut(testObject); + testObject.appendQueryString(CassandraCQLQueries.createKeySpace); + musicCore.eventualPut(testObject); testObject = new PreparedQueryObject(); - testObject.appendQueryString(CassandraCQL.createTableEmployees); - result = MusicCore.nonKeyRelatedPut(testObject, MusicUtil.EVENTUAL); + testObject.appendQueryString(CassandraCQLQueries.createTableEmployees); + result = musicCore.nonKeyRelatedPut(testObject, MusicUtil.EVENTUAL); assertEquals(ResultType.SUCCESS, result); } @Test public void Test2_atomicPut() throws Exception { testObject = new PreparedQueryObject(); - testObject = CassandraCQL.setPreparedInsertQueryObject1(); - ReturnType returnType = MusicCore.atomicPut("testCassa", "employees", "Mr Test one", + testObject = CassandraCQLQueries.setPreparedInsertQueryObject1(); + ReturnType returnType = musicCore.atomicPut("testCassa", "employees", "Mr Test one", testObject, null); assertEquals(ResultType.SUCCESS, returnType.getResult()); } @@ -97,28 +101,28 @@ public class TestMusicCoreIntegration { @Test public void Test5_atomicGet() throws Exception { testObject = new PreparedQueryObject(); - testObject = CassandraCQL.setPreparedGetQuery(); + testObject = CassandraCQLQueries.setPreparedGetQuery(); ResultSet resultSet = - MusicCore.atomicGet("testCassa", "employees", "Mr Test two", testObject); + musicCore.atomicGet("testCassa", "employees", "Mr Test two", testObject); List<Row> rows = resultSet.all(); assertEquals(1, rows.size()); } @Test public void Test6_createLockReference() throws Exception { - lockId = MusicCore.createLockReference(lockName); + lockId = musicCore.createLockReference(lockName); assertNotNull(lockId); } @Test public void Test7_acquireLockwithLease() throws Exception { - ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, 1000); + ReturnType lockLeaseStatus = musicCore.acquireLockWithLease(lockName, lockId, 1000); assertEquals(ResultType.SUCCESS, lockLeaseStatus.getResult()); } @Test public void Test8_acquireLock() throws Exception { - ReturnType lockStatus = MusicCore.acquireLock(lockName, lockId); + ReturnType lockStatus = musicCore.acquireLock(lockName, lockId); assertEquals(ResultType.SUCCESS, lockStatus.getResult()); } @@ -126,9 +130,9 @@ public class TestMusicCoreIntegration { public void Test9_release() throws Exception { MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); MusicLockState musicLockState1 = new MusicLockState(LockStatus.UNLOCKED, "id1"); - MusicCore.whoseTurnIsIt(lockName); - MusicLockState mls = MusicCore.getMusicLockState(lockName); - MusicLockState mls1 = MusicCore.voluntaryReleaseLock(lockName,lockId); + musicCore.whoseTurnIsIt(lockName); + MusicLockState mls = musicCore.getMusicLockState(lockName); + MusicLockState mls1 = musicCore.voluntaryReleaseLock(lockName,lockId); assertEquals(musicLockState.getLockStatus(), mls.getLockStatus()); assertEquals(musicLockState1.getLockStatus(), mls1.getLockStatus()); } diff --git a/src/test/java/org/onap/music/unittests/TestRestMusicData.java b/src/test/java/org/onap/music/unittests/TestRestMusicData.java index f0c52a3b..01ae861b 100644 --- a/src/test/java/org/onap/music/unittests/TestRestMusicData.java +++ b/src/test/java/org/onap/music/unittests/TestRestMusicData.java @@ -21,15 +21,17 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import java.io.File; + import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; + import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; + import org.apache.curator.test.TestingServer; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -44,7 +46,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; -import org.onap.music.datastore.CassaLockStore; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -53,13 +55,16 @@ import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.datastore.jsonobjects.JsonSelect; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.lockingservice.cassandra.CassaLockStore; import org.onap.music.main.CachingUtil; -import org.onap.music.main.MusicCore; +import org.onap.music.service.impl.*; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.rest.RestMusicAdminAPI; import org.onap.music.rest.RestMusicDataAPI; import org.onap.music.rest.RestMusicLocksAPI; +import org.onap.music.service.impl.MusicCassaCore; + import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -87,7 +92,7 @@ public class TestRestMusicData { CachingUtil cachUtilMock; @InjectMocks - private MusicCore mCore; + private static MusicCassaCore MusicCore =MusicCassaCore.getInstance(); //*/ static String appName = "TestApp"; @@ -109,8 +114,8 @@ public class TestRestMusicData { @BeforeClass public static void init() throws Exception { try { - MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); - MusicCore.mLockHandle = new CassaLockStore(MusicCore.mDstoreHandle); + MusicDataStoreHandle.mDstoreHandle = CassandraCQLQueries.connectToEmbeddedCassandra(); + MusicCore.mLockHandle = new CassaLockStore(MusicDataStoreHandle.mDstoreHandle); } catch (Exception e) { e.printStackTrace(); } @@ -124,8 +129,8 @@ public class TestRestMusicData { testObject = new PreparedQueryObject(); testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); MusicCore.eventualPut(testObject); - if(MusicCore.mDstoreHandle!=null) - MusicCore.mDstoreHandle.close(); + if(MusicDataStoreHandle.mDstoreHandle!=null) + MusicDataStoreHandle.mDstoreHandle.close(); if(zkServer!=null) zkServer.stop(); } diff --git a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java b/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java index a3d3d709..93591bfd 100644 --- a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java +++ b/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java @@ -47,7 +47,8 @@ import org.mindrot.jbcrypt.BCrypt; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import org.onap.music.datastore.CassaLockStore; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -57,12 +58,12 @@ import org.onap.music.datastore.jsonobjects.JsonKeySpace; import org.onap.music.datastore.jsonobjects.JsonSelect; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; -import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; //import org.onap.music.main.ResultType; import org.onap.music.rest.RestMusicAdminAPI; import org.onap.music.rest.RestMusicDataAPI; import org.onap.music.rest.RestMusicQAPI; +import org.onap.music.service.impl.MusicCassaCore; import org.onap.music.rest.RestMusicLocksAPI; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; @@ -119,12 +120,13 @@ public class TestRestMusicQAPI { static JsonKeySpace kspObject=null; static RestMusicDataAPI data = new RestMusicDataAPI(); static Response resp; + static MusicCassaCore MusicCore = MusicCassaCore.getInstance(); @BeforeClass public static void init() throws Exception { try { - MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); - MusicCore.mLockHandle = new CassaLockStore(MusicCore.mDstoreHandle); + MusicDataStoreHandle.mDstoreHandle = CassandraCQLQueries.connectToEmbeddedCassandra(); + MusicCassaCore.mLockHandle = new CassaLockStore(MusicDataStoreHandle.mDstoreHandle); // System.out.println("before class keysp"); //resp=data.createKeySpace(majorV,minorV,patchV,aid,appName,userId,password,kspObject,keyspaceName); @@ -211,8 +213,8 @@ public class TestRestMusicQAPI { testObject = new PreparedQueryObject(); testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin"); MusicCore.eventualPut(testObject); - if (MusicCore.mDstoreHandle!=null) - MusicCore.mDstoreHandle.close(); + if (MusicDataStoreHandle.mDstoreHandle!=null) + MusicDataStoreHandle.mDstoreHandle.close(); if (zkServer!=null) zkServer.stop(); } diff --git a/src/test/java/org/onap/music/unittests/TestVotingApp.java b/src/test/java/org/onap/music/unittests/TestVotingApp.java index e7a1e252..8ac71802 100644 --- a/src/test/java/org/onap/music/unittests/TestVotingApp.java +++ b/src/test/java/org/onap/music/unittests/TestVotingApp.java @@ -2,12 +2,12 @@ package org.onap.music.unittests; import java.util.HashMap; import java.util.Map; - + import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; +import org.onap.music.service.impl.MusicCassaCore; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -19,6 +19,7 @@ public class TestVotingApp { String keyspaceName; String tableName; + static MusicCassaCore MusicCore = MusicCassaCore.getInstance(); public TestVotingApp() throws MusicServiceException { keyspaceName = "VotingAppForMusic"+System.currentTimeMillis(); |