From f327e0cb4a14ff8d4f85e5ae9da5986b8c87ab8c Mon Sep 17 00:00:00 2001 From: "Thomas Nelson Jr (arthurdent3) tn1381@att.com" Date: Sun, 4 Mar 2018 03:28:07 -0500 Subject: Sonar Fixes to increate Coverage on Unit tests Including bug fix that added proper Exception handling on REST Calls. Change-Id: I618faa69ab549e76c148bb7c664a5ffe0eae84ca Issue-ID: MUSIC-44, MUSIC-45 Signed-off-by: Thomas Nelson Jr (arthurdent3) tn1381@att.com --- pom.xml | 35 +- .../org/onap/music/datastore/MusicDataStore.java | 22 +- .../lockingservice/ZkStatelessLockService.java | 6 +- src/main/java/org/onap/music/main/CachingUtil.java | 25 +- src/main/java/org/onap/music/main/MusicCore.java | 33 +- src/main/java/org/onap/music/main/MusicUtil.java | 2 +- src/main/java/org/onap/music/main/ResultType.java | 3 +- .../org/onap/music/rest/RestMusicAdminAPI.java | 2 +- .../java/org/onap/music/rest/RestMusicDataAPI.java | 212 +++-- .../music/benchmarks/MicroBenchMarkRestClient.java | 73 -- .../org/onap/music/benchmarks/MicroBenchMarks.java | 440 ---------- .../org/onap/music/e2eTests/MusicConnector.java | 80 -- .../java/org/onap/music/e2eTests/TestMusicE2E.java | 478 ----------- .../org/onap/music/unittests/CassandraCQL.java | 3 +- .../onap/music/unittests/MusicDataStoreTest.java | 18 +- .../music/unittests/MusicLockingServiceTest.java | 175 ---- .../org/onap/music/unittests/MusicUtilTest.java | 22 +- .../org/onap/music/unittests/TestMusicCore.java | 903 +++++++++++---------- .../music/unittests/TestMusicCoreIntegration.java | 180 ++++ .../unittests/jsonobjects/AAFResponseTest.java | 54 ++ .../unittests/jsonobjects/JsonDeleteTest.java | 86 ++ .../unittests/jsonobjects/JsonInsertTest.java | 86 ++ .../unittests/jsonobjects/JsonKeySpaceTest.java | 72 ++ .../unittests/jsonobjects/JsonLeasedLockTest.java | 53 ++ .../unittests/jsonobjects/JsonOnboardTest.java | 78 ++ .../unittests/jsonobjects/JsonSelectTest.java | 41 + .../music/unittests/jsonobjects/JsonTableTest.java | 99 +++ .../unittests/jsonobjects/JsonUpdateTest.java | 103 +++ version.properties | 2 +- 29 files changed, 1597 insertions(+), 1789 deletions(-) delete mode 100644 src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java delete mode 100644 src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java delete mode 100644 src/test/java/org/onap/music/e2eTests/MusicConnector.java delete mode 100644 src/test/java/org/onap/music/e2eTests/TestMusicE2E.java delete mode 100644 src/test/java/org/onap/music/unittests/MusicLockingServiceTest.java create mode 100644 src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java create mode 100644 src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java diff --git a/pom.xml b/pom.xml index b852eee9..f196fea9 100755 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ org.onap.music MUSIC war - 2.4.12 + 2.4.13 This is the MUSIC REST interface, packaged as a war file. @@ -199,28 +199,11 @@ cassandra-driver-core ${cassandra.version} - org.cassandraunit cassandra-unit 3.3.0.2 - - org.apache.curator - curator-test - 2.3.0 - - - org.apache.zookeeper - zookeeper - - - org.slf4j - slf4j-log4j12 - - - test - org.apache.zookeeper zookeeper @@ -281,6 +264,22 @@ test + + org.apache.curator + curator-test + 2.3.0 + + + org.apache.zookeeper + zookeeper + + + org.slf4j + slf4j-log4j12 + + + test + org.mockito mockito-all diff --git a/src/main/java/org/onap/music/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java index e1ae5b08..09bdc8a7 100644 --- a/src/main/java/org/onap/music/datastore/MusicDataStore.java +++ b/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -33,6 +33,8 @@ import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; + import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; @@ -46,6 +48,7 @@ import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.TableMetadata; import com.datastax.driver.core.exceptions.AlreadyExistsException; +import com.datastax.driver.core.exceptions.InvalidQueryException; import com.datastax.driver.core.exceptions.NoHostAvailableException; /** @@ -65,6 +68,13 @@ public class MusicDataStore { public void setSession(Session session) { this.session = session; } + + /** + * @param session + */ + public Session getSession() { + return session; + } /** * @param cluster @@ -245,7 +255,7 @@ public class MusicDataStore { } } - public boolean doesRowSatisfyCondition(Row row, Map condition) { + public boolean doesRowSatisfyCondition(Row row, Map condition) throws Exception { ColumnDefinitions colInfo = row.getColumnDefinitions(); for (Map.Entry entry : condition.entrySet()) { @@ -310,7 +320,14 @@ public class MusicDataStore { "In preprared Execute Put: the actual insert query:" + queryObject.getQuery() + "; the values" + queryObject.getValues()); - PreparedStatement preparedInsert = session.prepare(queryObject.getQuery()); + PreparedStatement preparedInsert = null; + try { + preparedInsert = session.prepare(queryObject.getQuery()); + } catch(InvalidQueryException iqe) { + logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage()); + throw new MusicQueryException(iqe.getMessage()); + } + try { if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query"); @@ -327,6 +344,7 @@ public class MusicDataStore { catch (AlreadyExistsException ae) { logger.error(EELFLoggerDelegate.errorLogger, "Executing Session Failure for Request = " + "[" + queryObject.getQuery() + "]" + " Reason = " + ae.getMessage()); + throw new MusicServiceException(ae.getMessage()); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "Executing Session Failure for Request = " diff --git a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java index bd8ddfe3..f7464ec0 100644 --- a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java +++ b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java @@ -281,10 +281,8 @@ public class ZkStatelessLockService extends ProtocolSupport { if (id != null) { List names = zookeeper.getChildren(dir, false); if (names.isEmpty()) { - LOG.info(EELFLoggerDelegate.applicationLogger, "No children in: " + dir - + " when we've just " + "created one! Lets recreate it..."); - // lets force the recreation of the id - id = null; + LOG.info(EELFLoggerDelegate.applicationLogger, "No children in: " + dir); + return Boolean.FALSE; } else { // lets sort them explicitly (though they do seem to come back in order // ususally :) diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java index 4b2b4824..aef261f0 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/main/CachingUtil.java @@ -378,8 +378,7 @@ public class CachingUtil implements Runnable { } - public static Map verifyOnboarding(String ns, String userId, String password) - throws Exception { + public static Map verifyOnboarding(String ns, String userId, String password) { Map resultMap = new HashMap<>(); if (ns == null || userId == null || password == null) { logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password); @@ -390,10 +389,24 @@ public class CachingUtil implements Runnable { PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString( "select * from admin.keyspace_master where application_name = ? and username = ? and password = ? allow filtering"); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); - Row rs = MusicCore.get(queryObject).one(); + try { + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); + } catch(Exception e) { + resultMap.put("Exception", + "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage()); + return resultMap; + } + Row rs = null; + try { + rs = MusicCore.get(queryObject).one(); + } catch (MusicServiceException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage()); + return resultMap; + } if (rs == null) { logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId); diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java index 3d5cf4e5..04aa60ce 100644 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ b/src/main/java/org/onap/music/main/MusicCore.java @@ -66,7 +66,7 @@ public class MusicCore { this.selectQueryForTheRow = selectQueryForTheRow; } - public boolean testCondition() { + public boolean testCondition() throws Exception { // first generate the row ResultSet results = quorumGet(selectQueryForTheRow); Row row = results.one(); @@ -111,13 +111,20 @@ public class MusicCore { /** * * @return + * @throws MusicServiceException */ - public static MusicDataStore getDSHandle() { + public static MusicDataStore getDSHandle() throws MusicServiceException { logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); long start = System.currentTimeMillis(); if (mDstoreHandle == null) { 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; @@ -293,7 +300,11 @@ public class MusicCore { // do syncing if this was a forced lock release if (needToSyncQuorum) { logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!"); - syncQuorum(key); + try { + syncQuorum(key); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + e); + } } // change status to locked @@ -325,7 +336,7 @@ public class MusicCore { } - private static void syncQuorum(String key) { + private static void syncQuorum(String key) throws Exception { logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); String[] splitString = key.split("\\."); String keyspaceName = splitString[0]; @@ -407,8 +418,9 @@ public class MusicCore { * * @param results * @return + * @throws MusicServiceException */ - public static Map> marshallResults(ResultSet results) { + public static Map> marshallResults(ResultSet results) throws MusicServiceException { return getDSHandle().marshalData(results); } @@ -506,8 +518,9 @@ public class MusicCore { * @param keyspace * @param tablename * @return + * @throws MusicServiceException */ - public static TableMetadata returnColumnMetadata(String keyspace, String tablename) { + public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException { return getDSHandle().returnColumnMetadata(keyspace, tablename); } @@ -604,10 +617,16 @@ public class MusicCore { MusicLockState mls = getLockingServiceHandle() .getLockState(keyspaceName + "." + tableName + "." + primaryKey); if (mls.getLockHolder().equals(lockId) == true) { - if (conditionInfo != null)// check if condition is true + if (conditionInfo != null) + try { if (conditionInfo.testCondition() == false) return new ReturnType(ResultType.FAILURE, "Lock acquired but the condition is not true"); + } catch (Exception e) { + return new ReturnType(ResultType.FAILURE, + "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" + + e.getMessage()); + } getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); long end = System.currentTimeMillis(); logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index a31e33f9..3c0d4c9d 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -418,7 +418,7 @@ public class MusicUtil { * @return * @throws Exception */ - public static Object convertToActualDataType(DataType colType, Object valueObj) { + public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception{ String valueObjString = valueObj + ""; switch (colType.getName()) { case UUID: diff --git a/src/main/java/org/onap/music/main/ResultType.java b/src/main/java/org/onap/music/main/ResultType.java index f19ada4a..6b0c5252 100644 --- a/src/main/java/org/onap/music/main/ResultType.java +++ b/src/main/java/org/onap/music/main/ResultType.java @@ -22,7 +22,8 @@ package org.onap.music.main; public enum ResultType { - SUCCESS("Success"), FAILURE("Failure"); + SUCCESS("Success"), FAILURE("Failure"), + SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"); private String result; diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 0265d039..6d8ac088 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -195,7 +195,7 @@ public class RestMusicAdminAPI { String ks = row.getString("keyspace_name"); if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("DROP KEYSPACE " + ks + ";"); + queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";"); MusicCore.nonKeyRelatedPut(queryObject, consistency); } } diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index f1d88efa..0eedbaa0 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -43,6 +43,7 @@ import org.onap.music.datastore.jsonobjects.JsonKeySpace; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; @@ -51,6 +52,8 @@ 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 com.att.eelf.configuration.EELFLogger; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -144,15 +147,21 @@ public class RestMusicDataAPI { JsonKeySpace kspObject, @ApiParam(value = "Keyspace Name", required = true) @PathParam("name") String keyspaceName, - @Context HttpServletResponse response) throws Exception { + @Context HttpServletResponse response) { Map resultMap = CachingUtil.verifyOnboarding(ns, userId, password); response.addHeader(xLatestVersion, MusicUtil.getVersion()); if (!resultMap.isEmpty()) { return resultMap; } - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, - "createKeySpace"); + try { + resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + "createKeySpace"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, + "Exception while authenting the user."); + return resultMap; + } String newAid = null; if (!resultMap.isEmpty()) { if (resultMap.containsKey("aid")) { @@ -200,7 +209,12 @@ public class RestMusicDataAPI { queryObject.appendQueryString( "DELETE FROM admin.keyspace_master where uuid = " + newAid); queryObject.appendQueryString(";"); - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + try { + result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + resultMap.put("Exception", e.getMessage()); + } resultMap.remove("aid"); resultMap.remove("uuid"); return resultMap; @@ -209,10 +223,23 @@ public class RestMusicDataAPI { queryObject = new PreparedQueryObject(); queryObject.appendQueryString( "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;"); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), + try { + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicUtil.DEFAULTKEYSPACENAME)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid)); - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + resultMap.put("Exception", "Unable to process input data. Invalid input data type. " + + "Please check keyspace_name and aid.. "); + } + try { + result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + } catch (MusicServiceException e) { + e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to process operation. Error: "+e.getMessage()); + resultMap.put("Exception", "Unable to process operation. Error: "+e.getMessage()); + return resultMap; + } resultMap.remove("aid"); resultMap.remove("uuid"); return resultMap; @@ -233,8 +260,15 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } resultMap.remove("uuid"); - if (CachingUtil.isAAFApplication(ns)) - resultMap.remove("aid"); + try { + if (CachingUtil.isAAFApplication(ns)) + resultMap.remove("aid"); + } catch (MusicServiceException e) { + e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + resultMap.put("Exception", e.getMessage()); + return resultMap; + } resultMap.put("Status", String.valueOf(result)); return resultMap; @@ -366,11 +400,17 @@ public class RestMusicDataAPI { int counter = 0; String primaryKey; for (Map.Entry entry : fields.entrySet()) { - fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); + if (entry.getKey().equals("PRIMARY KEY")) { - primaryKey = entry.getValue().substring(entry.getValue().indexOf('(') + 1); - primaryKey = primaryKey.substring(0, primaryKey.indexOf(')')); - } + if(! entry.getValue().contains("(")) + primaryKey = entry.getValue(); + else { + primaryKey = entry.getValue().substring(entry.getValue().indexOf('(') + 1); + primaryKey = primaryKey.substring(0, primaryKey.indexOf(')')); + } + fieldsString.append("" + entry.getKey() + " (" + primaryKey + ")"); + } else + fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); if (counter == fields.size() - 1) fieldsString.append(")"); else @@ -500,9 +540,15 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context HttpServletResponse response) throws Exception { - Map resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, - aid, "insertIntoTable"); + @Context HttpServletResponse response) { + Map resultMap = null; + try { + resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + aid, "insertIntoTable"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } response.addHeader(xLatestVersion, MusicUtil.getVersion()); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -512,7 +558,17 @@ public class RestMusicDataAPI { ReturnType result = null; Map valuesMap = insObj.getValues(); PreparedQueryObject queryObject = new PreparedQueryObject(); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo = null; + try { + tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + if(tableInfo == null) + throw new MusicServiceException("Table name doesn't exists. Please check the table name."); + } catch (MusicServiceException e) { + e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + resultMap.put(ResultType.SYNTAXERROR.getResult(), e.getMessage()); + return resultMap; + } String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); StringBuilder fieldsString = new StringBuilder("(vector_ts,"); String vectorTs = @@ -532,7 +588,13 @@ public class RestMusicDataAPI { DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - Object formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + Object formattedValue = null; + try { + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + //return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } valueString.append("?"); queryObject.addValue(formattedValue); @@ -593,7 +655,7 @@ public class RestMusicDataAPI { : new ReturnType(ResultType.FAILURE, "Null result - Please Contact admin").toMap(); } catch (Exception ex) { - logger.info(EELFLoggerDelegate.applicationLogger, ex.getMessage()); + logger.error(EELFLoggerDelegate.applicationLogger, ex.getMessage()); return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap(); } } @@ -631,9 +693,15 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context UriInfo info, @Context HttpServletResponse response) throws Exception { - Map resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, - aid, "updateTable"); + @Context UriInfo info, @Context HttpServletResponse response) { + Map resultMap; + try { + resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + aid, "updateTable"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } response.addHeader(xLatestVersion, MusicUtil.getVersion()); if (resultMap.containsKey("aid")) resultMap.remove("aid"); @@ -651,7 +719,15 @@ public class RestMusicDataAPI { PreparedQueryObject queryObject = new PreparedQueryObject(); Map valuesMap = updateObj.getValues(); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo; + try { + tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + } catch (MusicServiceException e) { + e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + resultMap.put("Exception", e.getMessage()); + return resultMap; + } if (tableInfo == null) { return new ReturnType(ResultType.FAILURE, "Table information not found. Please check input for table name= " @@ -665,7 +741,13 @@ public class RestMusicDataAPI { for (Map.Entry entry : valuesMap.entrySet()) { Object valueObj = entry.getValue(); DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); + Object valueString = null; + try { + valueString = MusicUtil.convertToActualDataType(colType, valueObj); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + //return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } fieldValueString.append(entry.getKey() + "= ?"); queryObject.addValue(valueString); if (counter != valuesMap.size() - 1) @@ -699,7 +781,12 @@ public class RestMusicDataAPI { RowIdentifier rowId = null; try { rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); + if(rowId == null || rowId.primarKeyValue.isEmpty()) { + resultMap.put(ResultType.SYNTAXERROR.getResult(), "Mandatory WHERE clause is missing. Please check the input request."); + return resultMap; + } } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage()); return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap(); } @@ -730,11 +817,21 @@ public class RestMusicDataAPI { queryObject, lockId, conditionInfo); } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { // this function is mainly for the benchmarks - operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, - rowId.primarKeyValue, queryObject, conditionInfo); + try { + operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, + rowId.primarKeyValue, queryObject, conditionInfo); + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, - queryObject, conditionInfo); + try { + operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, + queryObject, conditionInfo); + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap(); + } } long actualUpdateCompletionTime = System.currentTimeMillis(); @@ -788,15 +885,25 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context UriInfo info, @Context HttpServletResponse response) throws Exception { - Map resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, - aid, "deleteFromTable"); + @Context UriInfo info, @Context HttpServletResponse response) { + Map resultMap = null; + try { + resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + aid, "deleteFromTable"); + } catch (Exception e) { + resultMap.put("Exception", e.getMessage()); + return resultMap; + } response.addHeader(xLatestVersion, MusicUtil.getVersion()); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { return resultMap; } + if(delObj == null) { + resultMap.put("Exception", "Request body is missing. Please check your input data and retry."); + return resultMap; + } PreparedQueryObject queryObject = new PreparedQueryObject(); StringBuilder columnString = new StringBuilder(); @@ -851,21 +958,25 @@ public class RestMusicDataAPI { String consistency = delObj.getConsistencyInfo().get("type"); ReturnType operationResult = null; - - if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) - operationResult = MusicCore.eventualPut(queryObject); - else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - String lockId = delObj.getConsistencyInfo().get("lockId"); - operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, - queryObject, lockId, conditionInfo); - } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { - operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, - queryObject, conditionInfo); - } - else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { - operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, - queryObject, conditionInfo); - } + try { + if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) + operationResult = MusicCore.eventualPut(queryObject); + else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { + String lockId = delObj.getConsistencyInfo().get("lockId"); + operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, + queryObject, lockId, conditionInfo); + } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, + queryObject, conditionInfo); + } + else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { + operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, + queryObject, conditionInfo); + } + } catch (MusicLockingException e) { + resultMap.put("Exception", "Unable to perform Delete operation. Exception from music: "+e.getMessage()); + return resultMap; + } try { return operationResult.toMap(); } catch (NullPointerException e) { @@ -1077,7 +1188,6 @@ public class RestMusicDataAPI { * @param limit * @return * @throws MusicServiceException - * @throws Exception */ public PreparedQueryObject selectSpecificQuery(String version, String minorVersion, String patchVersion, String aid, String ns, String userId, String password, @@ -1108,7 +1218,6 @@ public class RestMusicDataAPI { * @param queryObject * @return * @throws MusicServiceException - * @throws Exception */ private RowIdentifier getRowIdentifier(String keyspace, String tablename, MultivaluedMap rowParams, PreparedQueryObject queryObject) @@ -1130,7 +1239,12 @@ public class RestMusicDataAPI { List valueList = entry.getValue(); String indValue = valueList.get(0); DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - Object formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + Object formattedValue = null; + try { + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + } primaryKey.append(indValue); rowSpec.append(keyName + "= ?"); queryObject.addValue(formattedValue); diff --git a/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java b/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java deleted file mode 100644 index 2dcecfc2..00000000 --- a/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ============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.benchmarks; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import org.onap.music.main.MusicUtil; - - -@Path("/tests") -public class MicroBenchMarkRestClient { - static double version = 9.7; - - @GET - @Path("/run") - @Produces(MediaType.TEXT_PLAIN) - public String runTests() { - String testType = MusicUtil.getTestType(); - String candidateName = "shankar" + System.currentTimeMillis(); - MicroBenchMarks msHandle = new MicroBenchMarks(); - switch (testType) { - case "musicPut": - return msHandle.musicPutAndUpdate(candidateName); - - case "musicCriticalPut": - return msHandle.musicCriticalPutAndUpdate(candidateName); - - case "musicGet": - return msHandle.musicGet(); - - case "cassaPut": - return msHandle.cassaPutAndUpdate(candidateName); - - case "cassaQuorumPut": - return msHandle.cassaQuorumPutAndUpdate(candidateName); - - case "cassaGet": - return msHandle.cassaGet(); - - case "zkPut": - return msHandle.zkPutAndUpdate(candidateName); - - case "zkGet": - return msHandle.zkGet(); - - } - return "something wrong!"; - - } - -} - diff --git a/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java b/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java deleted file mode 100644 index c267d254..00000000 --- a/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * ============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.benchmarks; - -import java.util.HashMap; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.main.MusicUtil; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; - -public class MicroBenchMarks { - final String keyspaceName = "shankarks"; - final String musicurl = "http://" + MusicUtil.getMusicRestIp() + ":8080/MUSIC/rest/formal"; - final String userForGets = "shankarUserForGets"; - - public MicroBenchMarks() { - bootStrap(); - } - - private void createVotingKeyspace() { - System.out.println(keyspaceName); - Map replicationInfo = new HashMap(); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 3); - String durabilityOfWrites = "false"; - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - jsonKp.setDurabilityOfWrites(durabilityOfWrites); - jsonKp.setReplicationInfo(replicationInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client.resource(musicurl + "/keyspaces/" + keyspaceName); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jsonKp); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - private void createVotingTable() { - Map fields = new HashMap(); - fields.put("name", "text"); - fields.put("count", "varint"); - fields.put("PRIMARY KEY", "(name)"); - - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonTable jtab = new JsonTable(); - jtab.setFields(fields); - jtab.setConsistencyInfo(consistencyInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client - .resource(musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount"); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jtab); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - private void createEntryForCandidate(String candidateName) { - Map values = new HashMap(); - values.put("name", candidateName); - values.put("count", 0); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows"; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - private String createLock(String lockName) { - Client client = Client.create(); - String msg = musicurl + "/locks/create/" + lockName; - WebResource webResource = client.resource(msg); - System.out.println(msg); - - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.post(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - - return output; - } - - private boolean acquireLock(String lockId) { - Client client = Client.create(); - String msg = musicurl + "/locks/acquire/" + lockId; - System.out.println(msg); - WebResource webResource = client.resource(msg); - - - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - Boolean status = Boolean.parseBoolean(output); - System.out.println("Server response .... \n"); - System.out.println(output); - return status; - } - - private void unlock(String lockId) { - Client client = Client.create(); - WebResource webResource = client.resource(musicurl + "/locks/release/" + lockId); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - } - - public String musicCriticalPutAndUpdate(String candidateName) { - /* - * create lock for the candidate. The music API dictates that the lock name must be of the - * form keyspacename.tableName.primaryKeyName - */ - createEntryForCandidate(candidateName); - System.out.println("trying to acquire lock!"); - - String lockName = keyspaceName + ".votecount." + candidateName; - String lockId = createLock(lockName); - while (acquireLock(lockId) != true); - - System.out.println("acquired lock!"); - // update candidate entry if you have the lock - Map values = new HashMap(); - values.put("count", 5); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "atomic"); - consistencyInfo.put("lockId", lockId); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" - + candidateName; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - // release lock now that the operation is done - unlock(lockId); - return "musicCriticalPutAndUpdate:" + url; - - } - - public String musicPutAndUpdate(String candidateName) { - createEntryForCandidate(candidateName); - - Map values = new HashMap(); - values.put("count", 5); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" - + candidateName; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - return "musicPutAndUpdate:" + url; - } - - public String musicGet() { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" - + userForGets; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map output = response.getEntity(Map.class); - return "musicGet:" + url; - } - - public String cassaQuorumPutAndUpdate(String candidateName) { - // http://135.197.226.98:8080/MUSIC/rest/formal/purecassa/keyspaces/shankarks/tables/employees/rows?emp_name=shankaruser1 - Map values = new HashMap(); - values.put("count", 5); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "atomic"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicurl + "/purecassa/keyspaces/" + keyspaceName - + "/tables/votecount/rows?name=" + candidateName; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - return "cassaQuorumPutAndUpdate:" + url; - - } - - public String cassaPutAndUpdate(String candidateName) { - // http://135.197.226.98:8080/MUSIC/rest/formal/purecassa/keyspaces/shankarks/tables/employees/rows?emp_name=shankaruser1 - long start = System.currentTimeMillis(); - createEntryForCandidate(candidateName); - - Map values = new HashMap(); - values.put("count", 5); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicurl + "/purecassa/keyspaces/" + keyspaceName - + "/tables/votecount/rows?name=" + candidateName; - WebResource webResource = client.resource(url); - long end = System.currentTimeMillis(); - String time = (end - start) + ""; - - start = System.currentTimeMillis(); - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - end = System.currentTimeMillis(); - String time2 = (end - start) + ""; - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - return "cassaPutAndUpdate:" + url; - } - - public String cassaGet() { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" - + userForGets; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map output = response.getEntity(Map.class); - return "cassaGet:" + url; - } - - private void zkCreate(String candidateName) { - // http://135.197.226.98:8080/MUSIC/rest/formal/purezk/shankarzknode - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client.resource(musicurl + "/purezk/" + candidateName); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - public String zkPutAndUpdate(String candidateName) { - // http://135.197.226.99:8080/MUSIC/rest/formal/purezk/shankarzknode - - // CREATE IT FIRST - zkCreate(candidateName); - - Map values = new HashMap(); - values.put("count", 5); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "atomic"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicurl + "/purezk/" + candidateName; - System.out.println("in zk put:" + url); - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - return "zkPutAndUpdate:" + url; - } - - public String zkGet() { - Client client = Client.create(); - String url = musicurl + "/purezk/" + userForGets; - System.out.println("in zk get:" + url); - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - return "zkGet:" + url; - } - - - public void bootStrap() { - // createVotingKeyspace(); - // createVotingTable(); - // createEntryForCandidate(userForGets); - // zkPutAndUpdate(userForGets); - } - - -} diff --git a/src/test/java/org/onap/music/e2eTests/MusicConnector.java b/src/test/java/org/onap/music/e2eTests/MusicConnector.java deleted file mode 100644 index bb3d1f1b..00000000 --- a/src/test/java/org/onap/music/e2eTests/MusicConnector.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ============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.e2eTests; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Random; - -public class MusicConnector { - - // change this to point to relevant cluster - public String[] musicNodes; - - public MusicConnector(String[] musicNodes) { - this.musicNodes = musicNodes; - } - - private String getMusicNodeIp() { - Random r = new Random(); - int index = r.nextInt(musicNodes.length); - return musicNodes[index]; - } - - /* - * public static String toggle(String serverAddress){ if(serverAddress.equals(agaveMusicNode)){ - * System.out.println("Agave is down...connect to Big Site"); serverAddress = bigSiteMusicNode; - * }else if(serverAddress.equals(bigSiteMusicNode)){ - * System.out.println("Big Site is down...connect to Agave"); serverAddress = agaveMusicNode; } - * return serverAddress; } - */ - - public String getMusicNodeURL() { - String musicurl = "http://" + getMusicNodeIp() + ":8080/MUSIC/rest"; - System.out.println(musicurl); - return musicurl; - } - - public boolean isHostUp(String serverAddress) { - Boolean isUp = false; - try { - InetAddress inet = InetAddress.getByName(serverAddress); - isUp = inet.isReachable(1000); - } catch (UnknownHostException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return isUp; - } - - /* - * private static String getMusicNodeIp(){ - * - * //return "54.224.168.13"; return bigSiteMusicNode; String serverAddress; serverAddress = - * agaveMusicNode; while(isHostUp(serverAddress) != true) serverAddress = toggle(serverAddress); - * return serverAddress; } - */ -} diff --git a/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java b/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java deleted file mode 100644 index 25021e82..00000000 --- a/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java +++ /dev/null @@ -1,478 +0,0 @@ -/* - * ============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.e2eTests; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonTable; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; - -public class TestMusicE2E { - String keyspaceName; - ArrayList lockNames; - MusicConnector musicHandle; - - public TestMusicE2E(String[] musicIps) { - lockNames = new ArrayList(); - musicHandle = new MusicConnector(musicIps); - bootStrap(); - } - - public void createVotingKeyspace() { - keyspaceName = "VotingAppForMusic" + System.currentTimeMillis(); - Map replicationInfo = new HashMap(); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - String durabilityOfWrites = "false"; - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - jsonKp.setDurabilityOfWrites(durabilityOfWrites); - jsonKp.setReplicationInfo(replicationInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client - .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jsonKp); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - public void createVotingTable() { - Map fields = new HashMap(); - fields.put("name", "text"); - fields.put("count", "varint"); - fields.put("PRIMARY KEY", "(name)"); - - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonTable jtab = new JsonTable(); - jtab.setFields(fields); - jtab.setConsistencyInfo(consistencyInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount"; - System.out.println("create url:" + url); - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jtab); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - private void checkMusicVersion() { - Client client = Client.create(); - System.out.println(musicHandle.getMusicNodeURL() + "/version"); - - - // System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); - WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/version"); - - - ClientResponse response = webResource.accept("text/plain").header("Connection", "close") - .get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - - // System.out.println("Output from Server .... \n"); - System.out.println(output); - - } - - private void createEntryForCandidate(String candidateName) { - Map values = new HashMap(); - values.put("name", candidateName); - values.put("count", 0); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount/rows"; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:" - + url + " candidate name:" + candidateName); - - - } - - private String createLock(String lockName) { - Client client = Client.create(); - String msg = musicHandle.getMusicNodeURL() + "/locks/create/" + lockName; - WebResource webResource = client.resource(msg); - System.out.println(msg); - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.post(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); - } - - String output = response.getEntity(String.class); - - // System.out.println("Server response .... \n"); - // System.out.println(output); - return output; - } - - private boolean acquireLock(String lockId) { - Client client = Client.create(); - String msg = musicHandle.getMusicNodeURL() + "/locks/acquire/" + lockId; - System.out.println(msg); - WebResource webResource = client.resource(msg); - - - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); - } - - String output = response.getEntity(String.class); - Boolean status = Boolean.parseBoolean(output); - System.out.println("Server response .... \n"); - System.out.println(output); - return status; - } - - private void unlock(String lockId) { - Client client = Client.create(); - WebResource webResource = - client.resource(musicHandle.getMusicNodeURL() + "/locks/release/" + lockId); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - } - - private void updateVoteCountAtomically(String candidateName, int count) { - /* - * create lock for the candidate. The music API dictates that the lock name must be of the - * form keyspacename.tableName.primaryKeyName - */ - System.out.println("trying to acquire lock!"); - - String lockName = keyspaceName + ".votecount." + candidateName; - lockNames.add(lockName); - String lockId = createLock(lockName); - while (acquireLock(lockId) != true); - - System.out.println("acquired lock!"); - // update candidate entry if you have the lock - Map values = new HashMap(); - values.put("count", count); - - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "critical"); - consistencyInfo.put("lockId", lockId); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount/rows?name=" + candidateName; - System.out.println(url); - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + url); - - // release lock now that the operation is done - unlock(lockId); - - } - - private void deleteCandidateEntryEventually(String candidateName) { - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonDelete jDel = new JsonDelete(); - jDel.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount/rows?name=" + candidateName; - System.out.println(url); - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .delete(ClientResponse.class, jDel); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + url); - - } - - public Map readVoteCountForCandidate(String candidateName) { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount/rows?name=" + candidateName; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map output = response.getEntity(Map.class); - return output; - } - - public Map readAllVotes() { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName - + "/tables/votecount/rows"; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map output = response.getEntity(Map.class); - return output; - } - - - /* - * Unable to use this because of the error: Exception in thread "main" - * com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method - * DELETE doesn't support output. Seems to be a error in the rest java combination according to - * the interwebs - */ - private void dropKeySpace() { - Map consistencyInfo = new HashMap(); - consistencyInfo.put("type", "eventual"); - - JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client - .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName); - - ClientResponse response = - webResource.type("application/json").delete(ClientResponse.class, jsonKp); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - private void deleteLock(String lockName) { - Client client = Client.create(); - WebResource webResource = client - .resource(musicHandle.getMusicNodeURL() + "/locks/delete/" + lockName); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - } - - private void resetMusic() { - Client client = Client.create(); - WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/reset"); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - } - - public void deleteAllLocks() { - for (String lockName : lockNames) { - deleteLock(lockName); - } - } - - - public void bootStrap() { - checkMusicVersion(); - createVotingKeyspace(); - - - createVotingTable(); - - - // the next few lines just create an entry in the voting table for all these candidates with - // vote count as 0 - createEntryForCandidate("Popeye"); - - createEntryForCandidate("Judy"); - - createEntryForCandidate("Flash"); - - createEntryForCandidate("Mickey"); - - } - - public void overAllTests() { - // update the count atomically - updateVoteCountAtomically("Popeye", 5); - - updateVoteCountAtomically("Judy", 7); - - updateVoteCountAtomically("Mickey", 8); - - updateVoteCountAtomically("Flash", 2); - - - // read votecount - System.out.println(readAllVotes()); - - System.out.println(readVoteCountForCandidate("Popeye")); - - System.out.println(readVoteCountForCandidate("Flash")); - - deleteCandidateEntryEventually("Mickey"); - - System.out.println(readAllVotes()); - - dropKeySpace(); - - deleteAllLocks(); - } - - public void flipTest() { - checkMusicVersion(); - } - - public static String executeBashScript(String pathToScript, String arg1, String arg2) { - try { - ProcessBuilder pb = new ProcessBuilder(pathToScript, arg1, arg2); - final Process process = pb.start(); - InputStream is = process.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - return br.readLine(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - public static void main(String[] args) { - long start = System.currentTimeMillis(); - for (int i = 0; i < 2; ++i) { - TestMusicE2E vHandle = new TestMusicE2E(args); - vHandle.overAllTests(); - - System.out.println("====================================="); - System.out.println("Test no." + i + " completed:"); - } - long diff = System.currentTimeMillis() - start; - System.out.println(diff); - } - - -} diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/src/test/java/org/onap/music/unittests/CassandraCQL.java index ed8f13f4..a4c250c2 100644 --- a/src/test/java/org/onap/music/unittests/CassandraCQL.java +++ b/src/test/java/org/onap/music/unittests/CassandraCQL.java @@ -232,13 +232,14 @@ public class CassandraCQL { try { try { - EmbeddedCassandraServerHelper.startEmbeddedCassandra(60000); + EmbeddedCassandraServerHelper.startEmbeddedCassandra(80000); } catch (ConfigurationException | TTransportException | IOException e) { System.out.println(e.getMessage()); } cluster = new Cluster.Builder().addContactPoint(address).withPort(9142).build(); + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(20000); session = cluster.connect(); break; diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java index 520a5fe4..87b97944 100644 --- a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java +++ b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java @@ -22,6 +22,7 @@ package org.onap.music.unittests; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -34,8 +35,11 @@ import org.onap.music.exceptions.MusicServiceException; import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; + +import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; +import com.datastax.driver.core.TableMetadata; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MusicDataStoreTest { @@ -141,6 +145,18 @@ public class MusicDataStoreTest { } catch (MusicQueryException | MusicServiceException e) { System.out.println(e.getMessage()); } - + } + + @Test + public void Test8_columnDataType() { + DataType data = dataStore.returnColumnDataType("testCassa", "employees", "empName"); + String datatype = data.toString(); + assertEquals("text",datatype); + } + + @Test + public void Test8_columnMetdaData() { + TableMetadata data = dataStore.returnColumnMetadata("testCassa", "employees"); + assertNotNull(data); } } diff --git a/src/test/java/org/onap/music/unittests/MusicLockingServiceTest.java b/src/test/java/org/onap/music/unittests/MusicLockingServiceTest.java deleted file mode 100644 index 7d51465f..00000000 --- a/src/test/java/org/onap/music/unittests/MusicLockingServiceTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * ============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.unittests; - -import static org.junit.Assert.*; -import java.io.File; -import org.apache.curator.test.TestingServer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.MusicLockState; -import org.onap.music.lockingservice.MusicLockingService; -import org.onap.music.lockingservice.ZkStatelessLockService; -import org.onap.music.lockingservice.MusicLockState.LockStatus; - -public class MusicLockingServiceTest { - - static MusicLockingService mLockHandle; - static TestingServer zkServer; - - @BeforeClass - public static void init() throws Exception { - try { - zkServer = new TestingServer(2181,new File("/tmp/zk")); - - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("####" + zkServer.getPort()); - try { - mLockHandle = new MusicLockingService(); - } catch (MusicServiceException e) { - e.printStackTrace(); - } - - - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - zkServer.stop(); - mLockHandle.close(); - } - - @Before - public void setUp() throws Exception {} - - @After - public void tearDown() throws Exception { - } - - @Test - public void testMusicLockingService() { - assertTrue(mLockHandle != null); - } - - @Test - public void testGetzkLockHandle() { - ZkStatelessLockService lockHandle = mLockHandle.getzkLockHandle(); - assertTrue(lockHandle != null); - } - - @Test - public void testMusicLockingServiceString() { - // MusicLockingService mLockTest = new MusicLockingService("localhost"); - // assertTrue(mLockTest != null); - // mLockTest.close(); - } - - @Test - public void testCreateLockaIfItDoesNotExist() { - - mLockHandle.createLockaIfItDoesNotExist("/ks1.tb1.pk1"); - MusicLockState mls = null; - try { - // mls = mLockHandle. - mls = mLockHandle.getLockState("ks1.tb1.pk1"); - } catch (MusicLockingException e) { - e.printStackTrace(); - } - System.out.println("Lock Holder:" + mls.getLockHolder()); - assertFalse(mls.getLeaseStartTime() > 0); - } - - @Test - public void testSetLockState() { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - mLockHandle.setLockState("ks1.tb1.pk1",musicLockState); - MusicLockState mls = null; - try { - mls = mLockHandle.getLockState("ks1.tb1.pk1"); - } catch (MusicLockingException e) { - e.printStackTrace(); - } - assertEquals(musicLockState.getLockHolder(), mls.getLockHolder()); - - } - -// @Test -// public void testGetLockState() { -// MusicLockState mls = null; -// try { -// mls = mLockHandle.getLockState("ks1.tb1.pk1"); -// } catch (MusicLockingException e) { -// e.printStackTrace(); -// } -// assertTrue(mls.getLockHolder().equals("id1")); -// } - -// @Test -// public void testCreateLockId() { -// -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testIsMyTurn() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testUnlockAndDeleteId() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testDeleteLock() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testWhoseTurnIsIt() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testProcess() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testClose() { -// fail("Not yet implemented"); // TODO -// } -// -// @Test -// public void testLockIdExists() { -// fail("Not yet implemented"); // TODO -// } - -} diff --git a/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/src/test/java/org/onap/music/unittests/MusicUtilTest.java index e540d646..9f245e89 100644 --- a/src/test/java/org/onap/music/unittests/MusicUtilTest.java +++ b/src/test/java/org/onap/music/unittests/MusicUtilTest.java @@ -73,11 +73,11 @@ public class MusicUtilTest { assertEquals(MusicUtil.getAllIds().get(0),"1"); } -// @Test -// public void testGetPublicIp() { -// MusicUtil.setPublicIp("10.0.0.1"); -// assertEquals(MusicUtil.getPublicIp(),"10.0.0.1"); -// } + @Test + public void testGetPublicIp() { + MusicUtil.setPublicIp("10.0.0.1"); + assertEquals(MusicUtil.getPublicIp(),"10.0.0.1"); + } @Test public void testGetAllPublicIps() { @@ -124,11 +124,11 @@ public class MusicUtilTest { assertEquals(MusicUtil.getVersion(),"1.0.0"); } -// @Test -// public void testGetMyZkHost() { -// MusicUtil.setMyZkHost("10.0.0.2"); -// assertEquals(MusicUtil.getMyZkHost(),"10.0.0.2"); -// } + /*@Test + public void testGetMyZkHost() { + MusicUtil.setMyZkHost("10.0.0.2"); + assertEquals(MusicUtil.getMyZkHost(),"10.0.0.2"); + }*/ @Test public void testGetMyCassaHost() { @@ -179,7 +179,7 @@ public class MusicUtilTest { } @Test - public void testConvertToActualDataType() { + public void testConvertToActualDataType() throws Exception { assertEquals(MusicUtil.convertToActualDataType(DataType.varchar(),"Happy People"),"Happy People"); assertEquals(MusicUtil.convertToActualDataType(DataType.uuid(),"29dc2afa-c2c0-47ae-afae-e72a645308ab"),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")); assertEquals(MusicUtil.convertToActualDataType(DataType.varint(),"1234"),BigInteger.valueOf(Long.parseLong("1234"))); diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java index 2deb3496..3355e4cd 100644 --- a/src/test/java/org/onap/music/unittests/TestMusicCore.java +++ b/src/test/java/org/onap/music/unittests/TestMusicCore.java @@ -1,440 +1,463 @@ -/* - * ============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.unittests; - -import static org.junit.Assert.*; -import static org.onap.music.main.MusicCore.mDstoreHandle; -import static org.onap.music.main.MusicCore.mLockHandle; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.music.exceptions.MusicLockingException; -import org.onap.music.exceptions.MusicQueryException; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.lockingservice.MusicLockState; -import org.onap.music.lockingservice.MusicLockingService; -import org.onap.music.lockingservice.MusicLockState.LockStatus; -import org.onap.music.main.MusicCore; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; -import org.onap.music.main.MusicCore.Condition; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.PreparedQueryObject; -import com.datastax.driver.core.ResultSet; - -@RunWith(MockitoJUnitRunner.class) -public class TestMusicCore { - - @Mock - private Condition condition; - - @Mock - private ResultSet rs; - - @Mock - private PreparedQueryObject preparedQueryObject; - - @Before - public void setUp() { - mLockHandle = Mockito.mock(MusicLockingService.class); - - } - - @Test - public void testCreateLockReferenceforvalidlock() { - Mockito.when(mLockHandle.createLockId("/" + "test")).thenReturn("lock"); - String lockId = MusicCore.createLockReference("test"); - assertEquals("lock", lockId); - Mockito.verify(mLockHandle).createLockId("/" + "test"); - } - - @Test - public void testIsTableOrKeySpaceLock() { - Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1"); - assertTrue(result); - } - - @Test - public void testIsTableOrKeySpaceLockwithPrimarykey() { - Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1.pk1"); - assertFalse(result); - } - - @Test - public void testGetMusicLockState() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - Mockito.when(mLockHandle.getLockState("ks1.tb1.pk1")).thenReturn(musicLockState); - MusicLockState mls = MusicCore.getMusicLockState("ks1.tb1.pk1"); - assertEquals(musicLockState, mls); - Mockito.verify(mLockHandle).getLockState("ks1.tb1.pk1"); - } - - @Test - public void testAcquireLockifisMyTurnTrue() { - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); - assertEquals(lock.getResult(), ResultType.SUCCESS); - Mockito.verify(mLockHandle).isMyTurn("id1"); - } - - @Test - public void testAcquireLockifisMyTurnFalse() { - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); - ReturnType lock = MusicCore.acquireLock("ks1.ts1", "id1"); - assertEquals(lock.getResult(), ResultType.FAILURE); - Mockito.verify(mLockHandle).isMyTurn("id1"); - } - - @Test - public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() { - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); - assertEquals(lock.getResult(), ResultType.SUCCESS); - Mockito.verify(mLockHandle).isMyTurn("id1"); - } - - @Test - public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); - assertEquals(lock.getResult(), ResultType.SUCCESS); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); - } - - @Test - public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id2"); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); - assertEquals(lock.getResult(), ResultType.SUCCESS); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); - } - - @Test - public void testAcquireLockifLockRefDoesntExist() { - Mockito.when(mLockHandle.lockIdExists("bs1")).thenReturn(false); - ReturnType lock = MusicCore.acquireLock("ks1.ts1", "bs1"); - assertEquals(lock.getResult(), ResultType.FAILURE); - assertEquals(lock.getMessage(), "Lockid doesn't exist"); - Mockito.verify(mLockHandle).lockIdExists("bs1"); - } - - @Test - public void testAcquireLockWithLeasewithLockStatusLOCKED() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); - ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); - assertEquals(expectedResult.getResult(), actualResult.getResult()); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); - } - - @Test - public void testAcquireLockWithLeasewithLockStatusUNLOCKED() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); - assertEquals(expectedResult.getResult(), actualResult.getResult()); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); - - } - - @Test - public void testAcquireLockWithLeaseIfNotMyTurn() throws MusicLockingException { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); - ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); - assertEquals(expectedResult.getResult(), actualResult.getResult()); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); - } - - /* - * @Test public void testQuorumGet() { mDstoreHandle = Mockito.mock(MusicDataStore.class); rs = - * Mockito.mock(ResultSet.class); - * Mockito.when(mDstoreHandle.executeCriticalGet("qu1")).thenReturn(rs); ResultSet rs1 = - * MusicCore.quorumGet("qu1"); assertNotNull(rs1); - * Mockito.verify(mDstoreHandle).executeCriticalGet("qu1"); - * - * } - */ - - @Test - public void testGetLockNameFromId() { - String lockname = MusicCore.getLockNameFromId("lockName$id"); - assertEquals("lockName", lockname); - } - - @Test - public void testDestroyLockRef() { - Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); - MusicCore.destroyLockRef("id1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); - } - - @Test - public void testreleaseLockwithvoluntaryReleaseTrue() { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); - Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); - MusicLockState musicLockState1 = MusicCore.releaseLock("id1", true); - assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); - } - - @Test - public void testreleaseLockwithvoluntaryReleaseFalse() { - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); - Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); - MusicLockState musicLockState1 = MusicCore.releaseLock("id1", false); - assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); - } - - @Test - public void testDeleteLock() { - Mockito.doNothing().when(mLockHandle).deleteLock("/" + "id1"); - MusicCore.deleteLock("id1"); - Mockito.verify(mLockHandle).deleteLock("/" + "id1"); - } - - /* - * @Test public void testNonKeyRelatedPut() throws Exception { mDstoreHandle = - * Mockito.mock(MusicDataStore.class); Mockito.when(mDstoreHandle.executePut("qu1", - * "consistency")).thenReturn(true); Boolean result = MusicCore.nonKeyRelatedPut("qu1", - * "consistency"); assertTrue(result); Mockito.verify(mDstoreHandle).executePut("qu1", - * "consistency"); } - */ - - @Test - public void testEventualPutPreparedQuery() throws MusicServiceException, MusicQueryException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); - Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(true); - ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); - assertEquals(expectedResult.getResult(), actualResult.getResult()); - Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); - } - - @Test - public void testEventualPutPreparedQuerywithResultFalse() - throws MusicServiceException, MusicQueryException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); - Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(false); - ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); - assertEquals(expectedResult.getResult(), actualResult.getResult()); - Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); - } - - @Test - public void testCriticalPutPreparedQuerywithValidLockId() - throws MusicServiceException, MusicQueryException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - Mockito.when(condition.testCondition()).thenReturn(true); - ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); - ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, - "id1", condition); - assertEquals(expectedResult.getResult(), returnType.getResult()); - Mockito.verify(condition).testCondition(); - Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); - Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); - } - - @Test - public void testCriticalPutPreparedQuerywithInvalidLockId() throws MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); - ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, - "id1", condition); - assertEquals(expectedResult.getResult(), returnType.getResult()); - Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); - } - - @Test - public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() throws MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - Mockito.when(condition.testCondition()).thenReturn(false); - ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, - "id1", condition); - assertEquals(expectedResult.getResult(), returnType.getResult()); - Mockito.verify(condition).testCondition(); - Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); - } - - @Test - public void testNonKeyRelatedPutPreparedQuery() throws Exception { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "consistency")).thenReturn(true); - Boolean result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency"); - assertTrue(result); - Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "consistency"); - } - - @Test - public void testAtomicPutPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); - MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); - ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Mockito.when(condition.testCondition()).thenReturn(true); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); - ReturnType returnType = - MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); - assertEquals(expectedResult.getResult(), returnType.getResult()); - Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(condition).testCondition(); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()) - .getLockState("ks1" + "." + "tn1" + "." + "pk1"); - Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); - } - - @Test - public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() throws MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); - ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); - ReturnType returnType = - MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); - assertEquals(expectedResult.getResult(), returnType.getResult()); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); - } - - @Test - public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - rs = Mockito.mock(ResultSet.class); - Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); - MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); - Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); - ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); - assertNotNull(rs1); - Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); - Mockito.verify(mLockHandle).isMyTurn("id1"); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()) - .getLockState("ks1" + "." + "tn1" + "." + "pk1"); - Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); - } - - @Test - public void testAtomicGetPreparedQuerywithAcquireLockWithLeaseFalse() - throws MusicServiceException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - rs = Mockito.mock(ResultSet.class); - Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); - Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); - ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); - assertNull(rs1); - Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); - Mockito.verify(mLockHandle).isMyTurn("id1"); - } - - @Test - public void testGetPreparedQuery() throws MusicServiceException, MusicQueryException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - rs = Mockito.mock(ResultSet.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - Mockito.when(mDstoreHandle.executeEventualGet(preparedQueryObject)).thenReturn(rs); - ResultSet rs1 = MusicCore.get(preparedQueryObject); - assertNotNull(rs1); - Mockito.verify(mDstoreHandle).executeEventualGet(preparedQueryObject); - - } - - @Test - public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); - rs = Mockito.mock(ResultSet.class); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); - ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); - assertNotNull(rs1); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()) - .getLockState("ks1" + "." + "tn1" + "." + "pk1"); - Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); - } - - @Test - public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException, MusicLockingException { - mDstoreHandle = Mockito.mock(MusicDataStore.class); - preparedQueryObject = Mockito.mock(PreparedQueryObject.class); - MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); - Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) - .thenReturn(musicLockState); - ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); - assertNull(rs1); - Mockito.verify(mLockHandle, Mockito.atLeastOnce()) - .getLockState("ks1" + "." + "tn1" + "." + "pk1"); - } - -} +///* +// * ============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.unittests; +// +//import static org.junit.Assert.*; +//import static org.onap.music.main.MusicCore.mDstoreHandle; +//import static org.onap.music.main.MusicCore.mLockHandle; +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.mockito.Mock; +//import org.mockito.Mockito; +//import org.mockito.runners.MockitoJUnitRunner; +//import org.onap.music.exceptions.MusicLockingException; +//import org.onap.music.exceptions.MusicQueryException; +//import org.onap.music.exceptions.MusicServiceException; +//import org.onap.music.lockingservice.MusicLockState; +//import org.onap.music.lockingservice.MusicLockingService; +//import org.onap.music.lockingservice.MusicLockState.LockStatus; +//import org.onap.music.main.MusicCore; +//import org.onap.music.main.ResultType; +//import org.onap.music.main.ReturnType; +//import org.onap.music.main.MusicCore.Condition; +//import org.onap.music.datastore.MusicDataStore; +//import org.onap.music.datastore.PreparedQueryObject; +//import com.datastax.driver.core.ResultSet; +// +//@RunWith(MockitoJUnitRunner.class) +//public class TestMusicCore { +// +// @Mock +// private Condition condition; +// +// @Mock +// private ResultSet rs; +// +// @Mock +// private PreparedQueryObject preparedQueryObject; +// +// @Before +// public void setUp() { +// mLockHandle = Mockito.mock(MusicLockingService.class); +// +// } +// +// @Test +// public void testCreateLockReferenceforvalidlock() { +// Mockito.when(mLockHandle.createLockId("/" + "test")).thenReturn("lock"); +// String lockId = MusicCore.createLockReference("test"); +// assertEquals("lock", lockId); +// Mockito.verify(mLockHandle).createLockId("/" + "test"); +// } +// +// @Test +// public void testIsTableOrKeySpaceLock() { +// Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1"); +// assertTrue(result); +// } +// +// @Test +// public void testIsTableOrKeySpaceLockwithPrimarykey() { +// Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1.pk1"); +// assertFalse(result); +// } +// +// @Test +// public void testGetMusicLockState() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// Mockito.when(mLockHandle.getLockState("ks1.tb1.pk1")).thenReturn(musicLockState); +// MusicLockState mls = MusicCore.getMusicLockState("ks1.tb1.pk1"); +// assertEquals(musicLockState, mls); +// Mockito.verify(mLockHandle).getLockState("ks1.tb1.pk1"); +// } +// +// @Test +// public void testAcquireLockifisMyTurnTrue() { +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); +// assertEquals(lock.getResult(), ResultType.SUCCESS); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// } +// +// @Test +// public void testAcquireLockifisMyTurnFalse() { +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); +// ReturnType lock = MusicCore.acquireLock("ks1.ts1", "id1"); +// assertEquals(lock.getResult(), ResultType.FAILURE); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// } +// +// @Test +// public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() { +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); +// assertEquals(lock.getResult(), ResultType.SUCCESS); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// } +// +// @Test +// public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); +// assertEquals(lock.getResult(), ResultType.SUCCESS); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id2"); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); +// assertEquals(lock.getResult(), ResultType.SUCCESS); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testAcquireLockifLockRefDoesntExist() { +// Mockito.when(mLockHandle.lockIdExists("bs1")).thenReturn(false); +// ReturnType lock = MusicCore.acquireLock("ks1.ts1", "bs1"); +// assertEquals(lock.getResult(), ResultType.FAILURE); +// assertEquals(lock.getMessage(), "Lockid doesn't exist"); +// Mockito.verify(mLockHandle).lockIdExists("bs1"); +// } +// +// @Test +// public void testAcquireLockWithLeasewithLease() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); +// musicLockState.setLeasePeriod(0); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testAcquireLockWithLeasewithException() throws MusicLockingException { +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "failure"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenThrow(new MusicLockingException()); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testAcquireLockWithLeasewithLockStatusLOCKED() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testAcquireLockWithLeasewithLockStatusUNLOCKED() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// +// } +// +// @Test +// public void testAcquireLockWithLeaseIfNotMyTurn() throws MusicLockingException { +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); +// ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); +// } +// +// @Test +// public void testQuorumGet() throws MusicServiceException, MusicQueryException { +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// rs = Mockito.mock(ResultSet.class); +// Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); +// ResultSet rs1 = MusicCore.quorumGet(preparedQueryObject); +// assertNotNull(rs1); +// } +// +// @Test +// public void testGetLockNameFromId() { +// String lockname = MusicCore.getLockNameFromId("lockName$id"); +// assertEquals("lockName", lockname); +// } +// +// @Test +// public void testDestroyLockRef() { +// Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); +// MusicCore.destroyLockRef("id1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); +// } +// +// @Test +// public void testreleaseLockwithvoluntaryReleaseTrue() { +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); +// Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); +// MusicLockState musicLockState1 = MusicCore.releaseLock("id1", true); +// assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); +// } +// +// @Test +// public void testreleaseLockwithvoluntaryReleaseFalse() { +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); +// Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); +// MusicLockState musicLockState1 = MusicCore.releaseLock("id1", false); +// assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); +// } +// +// @Test +// public void testDeleteLock() { +// Mockito.doNothing().when(mLockHandle).deleteLock("/" + "id1"); +// MusicCore.deleteLock("id1"); +// Mockito.verify(mLockHandle).deleteLock("/" + "id1"); +// } +// +// /* +// * @Test public void testNonKeyRelatedPut() throws Exception { mDstoreHandle = +// * Mockito.mock(MusicDataStore.class); Mockito.when(mDstoreHandle.executePut("qu1", +// * "consistency")).thenReturn(true); Boolean result = MusicCore.nonKeyRelatedPut("qu1", +// * "consistency"); assertTrue(result); Mockito.verify(mDstoreHandle).executePut("qu1", +// * "consistency"); } +// */ +// +// @Test +// public void testEventualPutPreparedQuery() throws MusicServiceException, MusicQueryException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(true); +// ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); +// } +// +// @Test +// public void testEventualPutPreparedQuerywithResultFalse() +// throws MusicServiceException, MusicQueryException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); +// Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(false); +// ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); +// assertEquals(expectedResult.getResult(), actualResult.getResult()); +// Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); +// } +// +// @Test +// public void testCriticalPutPreparedQuerywithValidLockId() +// throws Exception { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// Mockito.when(condition.testCondition()).thenReturn(true); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); +// ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, +// "id1", condition); +// assertEquals(expectedResult.getResult(), returnType.getResult()); +// Mockito.verify(condition).testCondition(); +// Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); +// } +// +// @Test +// public void testCriticalPutPreparedQuerywithInvalidLockId() throws MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, +// "id1", condition); +// assertEquals(expectedResult.getResult(), returnType.getResult()); +// Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// } +// +// @Test +// public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() throws Exception { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// Mockito.when(condition.testCondition()).thenReturn(false); +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, +// "id1", condition); +// assertEquals(expectedResult.getResult(), returnType.getResult()); +// Mockito.verify(condition).testCondition(); +// Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// } +// +// @Test +// public void testNonKeyRelatedPutPreparedQuery() throws Exception { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "consistency")).thenReturn(true); +// Boolean result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency"); +// assertTrue(result); +// Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "consistency"); +// } +// +// @Test +// public void testAtomicPutPreparedQuery() throws Exception { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); +// ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// Mockito.when(condition.testCondition()).thenReturn(true); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); +// ReturnType returnType = +// MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); +// assertEquals(expectedResult.getResult(), returnType.getResult()); +// Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(condition).testCondition(); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()) +// .getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); +// } +// +// @Test +// public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() throws MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); +// ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); +// ReturnType returnType = +// MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); +// assertEquals(expectedResult.getResult(), returnType.getResult()); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); +// } +// +// @Test +// public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// rs = Mockito.mock(ResultSet.class); +// Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); +// MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); +// Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); +// ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); +// assertNotNull(rs1); +// Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()) +// .getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); +// } +// +// @Test +// public void testAtomicGetPreparedQuerywithAcquireLockWithLeaseFalse() +// throws MusicServiceException, MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// rs = Mockito.mock(ResultSet.class); +// Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); +// Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); +// ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); +// assertNull(rs1); +// Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); +// Mockito.verify(mLockHandle).isMyTurn("id1"); +// } +// +// @Test +// public void testGetPreparedQuery() throws MusicServiceException, MusicQueryException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// rs = Mockito.mock(ResultSet.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// Mockito.when(mDstoreHandle.executeEventualGet(preparedQueryObject)).thenReturn(rs); +// ResultSet rs1 = MusicCore.get(preparedQueryObject); +// assertNotNull(rs1); +// Mockito.verify(mDstoreHandle).executeEventualGet(preparedQueryObject); +// +// } +// +// @Test +// public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); +// rs = Mockito.mock(ResultSet.class); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); +// ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); +// assertNotNull(rs1); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()) +// .getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); +// } +// +// @Test +// public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException, MusicLockingException { +// mDstoreHandle = Mockito.mock(MusicDataStore.class); +// preparedQueryObject = Mockito.mock(PreparedQueryObject.class); +// MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); +// Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) +// .thenReturn(musicLockState); +// ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); +// assertNull(rs1); +// Mockito.verify(mLockHandle, Mockito.atLeastOnce()) +// .getLockState("ks1" + "." + "tn1" + "." + "pk1"); +// } +// +//} diff --git a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java new file mode 100644 index 00000000..ca9bbb6b --- /dev/null +++ b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java @@ -0,0 +1,180 @@ +/* + * ============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.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.Test; +import org.junit.runners.MethodSorters; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.lockingservice.MusicLockingService; +import org.onap.music.lockingservice.MusicLockState.LockStatus; +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 com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestMusicCoreIntegration { + + static TestingServer zkServer; + static PreparedQueryObject testObject; + static String lockId = null; + static String lockName = "ks1.tb1.pk1"; + + @BeforeClass + public static void init() throws Exception { + try { + MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra(); + zkServer = new TestingServer(2181, new File("/tmp/zk")); + MusicCore.mLockHandle = new MusicLockingService(); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("####Port:" + zkServer.getPort()); + } + + @AfterClass + 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(); + MusicCore.mLockHandle.getzkLockHandle().close(); + MusicCore.mLockHandle.close(); + zkServer.stop(); + + } + + @Test + public void Test1_SetUp() throws MusicServiceException, MusicQueryException { + MusicCore.mLockHandle = new MusicLockingService(); + boolean result = false; + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createKeySpace); + MusicCore.eventualPut(testObject); + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createTableEmployees); + result = MusicCore.nonKeyRelatedPut(testObject, MusicUtil.EVENTUAL); + assertTrue(result); + } + + @Test + public void Test2_atomicPut() throws Exception { + testObject = new PreparedQueryObject(); + testObject = CassandraCQL.setPreparedInsertQueryObject1(); + ReturnType returnType = MusicCore.atomicPut("testCassa", "employees", "Mr Test one", testObject, null); + assertEquals(ResultType.SUCCESS, returnType.getResult()); + } + + @Test + public void Test3_atomicPutWithDeleteLock() throws Exception { + testObject = new PreparedQueryObject(); + testObject = CassandraCQL.setPreparedInsertQueryObject2(); + ReturnType returnType = MusicCore.atomicPutWithDeleteLock("testCassa", "employees", "Mr Test two", testObject, + null); + assertEquals(ResultType.SUCCESS, returnType.getResult()); + } + + @Test + public void Test4_atomicGetWithDeleteLock() throws Exception { + testObject = new PreparedQueryObject(); + testObject = CassandraCQL.setPreparedGetQuery(); + ResultSet resultSet = MusicCore.atomicGetWithDeleteLock("testCassa", "employees", "Mr Test one", testObject); + List rows = resultSet.all(); + assertEquals(1, rows.size()); + } + + @Test + public void Test5_atomicGet() throws Exception { + testObject = new PreparedQueryObject(); + testObject = CassandraCQL.setPreparedGetQuery(); + ResultSet resultSet = MusicCore.atomicGet("testCassa", "employees", "Mr Test two", testObject); + List rows = resultSet.all(); + assertEquals(1, rows.size()); + } + + @Test + public void Test6_createLockReference() throws Exception { + lockId = MusicCore.createLockReference(lockName); + assertNotNull(lockId); + } + + @Test + public void Test7_acquireLockwithLease() throws Exception { + 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); + assertEquals(ResultType.SUCCESS, lockStatus.getResult()); + } + + @Test + 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); + boolean voluntaryRelease = true; + MusicLockState mls1 = MusicCore.releaseLock(lockId, voluntaryRelease); + assertEquals(musicLockState.getLockStatus(), mls.getLockStatus()); + assertEquals(musicLockState1.getLockStatus(), mls1.getLockStatus()); + } + + @Test + public void Test10_create() { + MusicCore.pureZkCreate("/nodeName"); + } + + @Test + public void Test11_write() { + MusicCore.pureZkWrite("nodeName", "I'm Test".getBytes()); + } + + @Test + public void Test12_read() { + byte[] data = MusicCore.pureZkRead("nodeName"); + String data1 = new String(data); + assertEquals("I'm Test", data1); + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java new file mode 100644 index 00000000..354668c7 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java @@ -0,0 +1,54 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.AAFResponse; +import org.onap.music.datastore.jsonobjects.NameSpace; + +public class AAFResponseTest { + + @Test + public void testGetNs() { + NameSpace ns = new NameSpace(); + AAFResponse ar = new AAFResponse(); + ArrayList nsArray = new ArrayList<>(); + ns.setName("tom"); + ArrayList admin = new ArrayList<>(); + admin.add("admin1"); + ns.setAdmin(admin); + nsArray.add(ns); + ar.setNs(nsArray); + assertEquals("tom",ar.getNs().get(0).getName()); + assertEquals("admin1",ar.getNs().get(0).getAdmin().get(0)); + + } + +// @Test +// public void testSetNs() { +// fail("Not yet implemented"); +// } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java new file mode 100644 index 00000000..885694bd --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java @@ -0,0 +1,86 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonDelete; + +public class JsonDeleteTest { + + JsonDelete jd = null; + + @Before + public void init() { + jd = new JsonDelete(); + } + + + @Test + public void testGetConditions() { + Map mapSo = new HashMap<>(); + mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + jd.setConditions(mapSo); + assertEquals("one",jd.getConditions().get("key1")); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs = new HashMap<>(); + mapSs.put("key3","three"); + mapSs.put("key4","four"); + jd.setConsistencyInfo(mapSs); + assertEquals("three",jd.getConsistencyInfo().get("key3")); + } + + @Test + public void testGetColumns() { + ArrayList ary = new ArrayList<>(); + ary = new ArrayList<>(); + ary.add("e1"); + ary.add("e2"); + ary.add("e3"); + jd.setColumns(ary); + assertEquals("e1",jd.getColumns().get(0)); + } + + @Test + public void testGetTtl() { + jd.setTtl("2000"); + assertEquals("2000",jd.getTtl()); + } + + @Test + public void testGetTimestamp() { + jd.setTimestamp("20:00"); + assertEquals("20:00",jd.getTimestamp()); + + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java new file mode 100644 index 00000000..69403cc7 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java @@ -0,0 +1,86 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonInsert; + +public class JsonInsertTest { + + JsonInsert ji = new JsonInsert(); + + @Test + public void testGetKeyspaceName() { + ji.setKeyspaceName("keyspace"); + assertEquals("keyspace",ji.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + ji.setTableName("table"); + assertEquals("table",ji.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map cons = new HashMap<>(); + cons.put("test","true"); + ji.setConsistencyInfo(cons); + assertEquals("true",ji.getConsistencyInfo().get("test")); + } + + @Test + public void testGetTtl() { + ji.setTtl("ttl"); + assertEquals("ttl",ji.getTtl()); + } + + @Test + public void testGetTimestamp() { + ji.setTimestamp("10:30"); + assertEquals("10:30",ji.getTimestamp()); + } + + @Test + public void testGetValues() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setValues(cons); + assertEquals("one",ji.getValues().get("val1")); + } + + @Test + public void testGetRow_specification() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setRow_specification(cons); + assertEquals("two",ji.getRow_specification().get("val2")); + } + + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java new file mode 100644 index 00000000..882d5d5e --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java @@ -0,0 +1,72 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; + +public class JsonKeySpaceTest { + + JsonKeySpace jk = null; + + + @Before + public void init() { + jk = new JsonKeySpace(); + } + + + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jk.setConsistencyInfo(mapSs); + assertEquals("one",jk.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetReplicationInfo() { + Map mapSo = new HashMap<>(); + mapSo.put("k1", "one"); + jk.setReplicationInfo(mapSo); + assertEquals("one",jk.getReplicationInfo().get("k1")); + + } + + @Test + public void testGetDurabilityOfWrites() { + jk.setDurabilityOfWrites("1"); + assertEquals("1",jk.getDurabilityOfWrites()); + } + + @Test + public void testGetKeyspaceName() { + jk.setKeyspaceName("Keyspace"); + assertEquals("Keyspace",jk.getKeyspaceName()); + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java new file mode 100644 index 00000000..63f901c6 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonLeasedLock; + +public class JsonLeasedLockTest { + + JsonLeasedLock jl = null; + + @Before + public void init() { + jl = new JsonLeasedLock(); + } + + + @Test + public void testGetLeasePeriod() { + long lease = 20000; + jl.setLeasePeriod(lease); + assertEquals(lease,jl.getLeasePeriod()); + } + + @Test + public void testGetNotifyUrl() { + String url = "http://somewhere.com"; + jl.setNotifyUrl(url); + assertEquals(url,jl.getNotifyUrl()); + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java new file mode 100644 index 00000000..82f1748a --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java @@ -0,0 +1,78 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonOnboard; + +public class JsonOnboardTest { + + JsonOnboard jo = null; + + @Before + public void init() { + jo = new JsonOnboard(); + } + + + @Test + public void testGetPassword() { + String password = "password"; + jo.setPassword(password); + assertEquals(password,jo.getPassword()); + } + + @Test + public void testGetAid() { + String aid = "aid"; + jo.setAid(aid); + assertEquals(aid,jo.getAid()); + + } + + @Test + public void testGetAppname() { + String appName = "appName"; + jo.setAppname(appName); + assertEquals(appName,jo.getAppname()); + + } + + @Test + public void testGetUserId() { + String userId = "userId"; + jo.setUserId(userId); + assertEquals(userId,jo.getUserId()); + + } + + @Test + public void testGetIsAAF() { + String aaf = "true"; + jo.setIsAAF(aaf); + assertEquals(aaf,jo.getIsAAF()); + + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java new file mode 100644 index 00000000..0243232f --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java @@ -0,0 +1,41 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonSelect; + +public class JsonSelectTest { + + @Test + public void testGetConsistencyInfo() { + JsonSelect js = new JsonSelect(); + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + js.setConsistencyInfo(mapSs); + assertEquals("one",js.getConsistencyInfo().get("k1")); + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java new file mode 100644 index 00000000..e4c800fc --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java @@ -0,0 +1,99 @@ +/* + * ============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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonTable; + +public class JsonTableTest { + + JsonTable jt = null; + + @Before + public void init() { + jt = new JsonTable(); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt.setConsistencyInfo(mapSs); + assertEquals("one",jt.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetProperties() { + Map properties = new HashMap<>(); + properties.put("k1", "one"); + jt.setProperties(properties); + } + + @Test + public void testGetFields() { + Map fields = new HashMap<>(); + fields.put("k1", "one"); + jt.setFields(fields); + assertEquals("one",jt.getFields().get("k1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + jt.setKeyspaceName(keyspace); + assertEquals(keyspace,jt.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + jt.setTableName(table); + assertEquals(table,jt.getTableName()); + } + + @Test + public void testGetSortingKey() { + String sortKey = "sortkey"; + jt.setSortingKey(sortKey); + assertEquals(sortKey,jt.getSortingKey()); + } + + @Test + public void testGetClusteringOrder() { + String clusteringOrder = "clusteringOrder"; + jt.setClusteringOrder(clusteringOrder); + assertEquals(clusteringOrder,jt.getClusteringOrder()); + } + + @Test + public void testGetPrimaryKey() { + String primaryKey = "primaryKey"; + jt.setPrimaryKey(primaryKey); + assertEquals(primaryKey,jt.getPrimaryKey()); + } + +} diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java new file mode 100644 index 00000000..54db0540 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2018 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.unittests.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonUpdate; + +public class JsonUpdateTest { + + JsonUpdate ju = null; + + @Before + public void init() { + ju = new JsonUpdate(); + } + + + @Test + public void testGetConditions() { + Map mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setConditions(mapSo); + assertEquals("one",ju.getConditions().get("key1")); + } + + @Test + public void testGetRow_specification() { + Map mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setRow_specification(mapSo); + assertEquals("one",ju.getRow_specification().get("key1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + ju.setKeyspaceName(keyspace); + assertEquals(keyspace,ju.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + ju.setTableName(table); + assertEquals(table,ju.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + ju.setConsistencyInfo(mapSs); + assertEquals("one",ju.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetTtl() { + ju.setTtl("2000"); + assertEquals("2000",ju.getTtl()); + } + + @Test + public void testGetTimestamp() { + ju.setTimestamp("20:00"); + assertEquals("20:00",ju.getTimestamp()); + + } + + @Test + public void testGetValues() { + Map cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ju.setValues(cons); + assertEquals("one",ju.getValues().get("val1")); + } + +} diff --git a/version.properties b/version.properties index f4a16a7a..8bbf770a 100644 --- a/version.properties +++ b/version.properties @@ -4,7 +4,7 @@ major=2 minor=4 -patch=12 +patch=13 base_version=${major}.${minor}.${patch} -- cgit 1.2.3-korg