diff options
16 files changed, 251 insertions, 341 deletions
diff --git a/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java b/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java index 9ccff828..2e17670f 100755 --- a/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java +++ b/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -61,10 +61,6 @@ import com.datastax.driver.extras.codecs.enums.EnumNameCodec; * */ public class MusicDataStore { - - public static final String CONSISTENCY_LEVEL_ONE = "ONE"; - public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM"; - public static final String CONSISTENCY_LEVEL_LOCAL_QUORUM = "LOCAL_QUORUM"; private Session session; private Cluster cluster; @@ -471,15 +467,16 @@ public class MusicDataStore { try { SimpleStatement statement = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray()); - if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_ONE)) { + if (consistencyLevel.equalsIgnoreCase(MusicUtil.ONE)) { if(queryObject.getConsistency() == null) { statement.setConsistencyLevel(ConsistencyLevel.ONE); } else { statement.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency())); } - } - else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) { + } else if (consistencyLevel.equalsIgnoreCase(MusicUtil.QUORUM)) { statement.setConsistencyLevel(ConsistencyLevel.QUORUM); + } else if (consistencyLevel.equalsIgnoreCase(MusicUtil.LOCAL_QUORUM)) { + statement.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); } results = session.execute(statement); @@ -501,7 +498,7 @@ public class MusicDataStore { */ public ResultSet executeOneConsistencyGet(PreparedQueryObject queryObject) throws MusicServiceException, MusicQueryException { - return executeGet(queryObject, CONSISTENCY_LEVEL_ONE); + return executeGet(queryObject, MusicUtil.ONE); } /** @@ -512,7 +509,7 @@ public class MusicDataStore { */ public ResultSet executeLocalQuorumConsistencyGet(PreparedQueryObject queryObject) throws MusicServiceException, MusicQueryException { - return executeGet(queryObject, CONSISTENCY_LEVEL_LOCAL_QUORUM); + return executeGet(queryObject, MusicUtil.LOCAL_QUORUM); } /** @@ -523,7 +520,7 @@ public class MusicDataStore { */ public ResultSet executeQuorumConsistencyGet(PreparedQueryObject queryObject) throws MusicServiceException, MusicQueryException { - return executeGet(queryObject, CONSISTENCY_LEVEL_QUORUM); + return executeGet(queryObject, MusicUtil.QUORUM); } } diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java index 57ff245a..2f685cfe 100644 --- a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java @@ -173,11 +173,6 @@ public class JsonInsert implements Serializable { * @throws MusicQueryException */ public PreparedQueryObject genInsertPreparedQueryObj() throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genTableInsertQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genTableInsertQuery method " + this.getTableName()); - } - PreparedQueryObject queryObject = new PreparedQueryObject(); TableMetadata tableInfo = null; try { diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java index ef560144..0a277e08 100644 --- a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java @@ -144,11 +144,6 @@ public class JsonTable { } public PreparedQueryObject genCreateTableQuery() throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genCreateTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genCreateTableQuery method " + this.getTableName()); - } - String primaryKey = null; String partitionKey = this.getPartitionKey(); String clusterKey = this.getClusteringKey(); @@ -341,35 +336,11 @@ public class JsonTable { } /** - * - * @return - */ - public PreparedQueryObject genCreateShadowLockingTableQuery() { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genCreateShadowLockingTableQuery method " + this.getTableName()); - } - - String tableName = "unsyncedKeys_" + this.getTableName(); - String tabQuery = "CREATE TABLE IF NOT EXISTS " + this.getKeyspaceName() + "." + tableName - + " ( key text,PRIMARY KEY (key) );"; - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString(tabQuery); - - return queryObject; - } - - /** * genDropTableQuery * * @return PreparedQueryObject */ public PreparedQueryObject genDropTableQuery() { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genDropTableQuery method " + this.getKeyspaceName()); - logger.debug("Coming inside genDropTableQuery method " + this.getTableName()); - } - PreparedQueryObject query = new PreparedQueryObject(); query.appendQueryString("DROP TABLE " + this.getKeyspaceName() + "." + this.getTableName() + ";"); logger.info("Delete Query ::::: " + query.getQuery()); diff --git a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java index 12508de0..cd767a44 100644 --- a/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java +++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java @@ -65,7 +65,7 @@ public class JsonUpdate implements Serializable { private Map<String, String> consistencyInfo; private transient Map<String, Object> conditions; private transient Map<String, Object> rowSpecification; - private StringBuilder rowIdString; + private String rowIdString; private String primarKeyValue; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonUpdate.class); @@ -142,11 +142,11 @@ public class JsonUpdate implements Serializable { this.values = values; } - public StringBuilder getRowIdString() { + public String getRowIdString() { return rowIdString; } - public void setRowIdString(StringBuilder rowIdString) { + public void setRowIdString(String rowIdString) { this.rowIdString = rowIdString; } @@ -176,11 +176,6 @@ public class JsonUpdate implements Serializable { * @throws MusicQueryException */ public PreparedQueryObject genUpdatePreparedQueryObj(MultivaluedMap<String, String> rowParams) throws MusicQueryException { - if (logger.isDebugEnabled()) { - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getKeyspaceName()); - logger.debug("Coming inside genUpdatePreparedQueryObj method " + this.getTableName()); - } - PreparedQueryObject queryObject = new PreparedQueryObject(); if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) || @@ -205,20 +200,7 @@ public class JsonUpdate implements Serializable { Map<String, Object> valuesMap = this.getValues(); - TableMetadata tableInfo; - - try { - tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName()); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, e); - /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();*/ - throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); - }catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL, - ErrorTypes.GENERALSERVICEERROR); - throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); - } + TableMetadata tableInfo = getColumnMetadata(this.getKeyspaceName(), this.getTableName()); if (tableInfo == null) { logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+this.getTableName(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -289,7 +271,7 @@ public class JsonUpdate implements Serializable { rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject); this.setRowIdString(rowId.rowIdString); this.setPrimarKeyValue(rowId.primarKeyValue); - if(rowId == null || rowId.primarKeyValue.isEmpty()) { + if(rowId == null || rowId.getPrimaryKeyValue().isEmpty()) { /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();*/ @@ -312,7 +294,7 @@ public class JsonUpdate implements Serializable { queryObject.appendQueryString( - " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";"); + " SET " + fieldValueString + " WHERE " + rowId.getRowIdString() + ";"); @@ -324,7 +306,7 @@ public class JsonUpdate implements Serializable { // to avoid parsing repeatedly, just send the select query to obtain row PreparedQueryObject selectQuery = new PreparedQueryObject(); selectQuery.appendQueryString("SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " - + rowId.rowIdString + ";"); + + rowId.getRowIdString() + ";"); selectQuery.addValue(rowId.primarKeyValue); conditionInfo = new Condition(this.getConditions(), selectQuery); } @@ -348,20 +330,62 @@ public class JsonUpdate implements Serializable { return queryObject; } + + TableMetadata getColumnMetadata(String keyspaceName, String tableName) throws MusicQueryException { + TableMetadata tableInfo; + try { + tableInfo = returnColumnMetadata(keyspaceName, tableName); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes + .GENERALSERVICEERROR, e); + /*return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();*/ + throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR, ErrorSeverity.CRITICAL, + ErrorTypes.GENERALSERVICEERROR); + throw new MusicQueryException(e.getMessage(), Status.BAD_REQUEST.getStatusCode()); + } + return tableInfo; + } + + /** wrapper around static method for testing */ + TableMetadata returnColumnMetadata(String keyspace, String tableName) throws MusicServiceException { + return MusicDataStoreHandle.returnColumnMetadata(keyspace, tableName); + } - private class RowIdentifier { - public String primarKeyValue; - public StringBuilder rowIdString; + class RowIdentifier { + private String primarKeyValue; + private String rowIdString; @SuppressWarnings("unused") public PreparedQueryObject queryObject; // the string with all the row // identifiers separated by AND - public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, + public RowIdentifier(String primaryKeyValue, String rowIdString, PreparedQueryObject queryObject) { this.primarKeyValue = primaryKeyValue; this.rowIdString = rowIdString; this.queryObject = queryObject; } + + public String getPrimaryKeyValue() { + return this.primarKeyValue; + } + + public void setPrimaryKeyValue(String primaryKeyValue) { + this.primarKeyValue = primaryKeyValue; + } + + public String getRowIdString() { + return this.rowIdString.toString(); + } + + public void setRowIdString(String rowIdString) { + this.rowIdString = rowIdString; + } + + public PreparedQueryObject getQueryObject() { + return this.queryObject; + } } /** @@ -373,12 +397,12 @@ public class JsonUpdate implements Serializable { * @return * @throws MusicServiceException */ - private RowIdentifier getRowIdentifier(String keyspace, String tablename, + RowIdentifier getRowIdentifier(String keyspace, String tablename, MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject) throws MusicServiceException { StringBuilder rowSpec = new StringBuilder(); int counter = 0; - TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo = returnColumnMetadata(keyspace, tablename); if (tableInfo == null) { logger.error(EELFLoggerDelegate.errorLogger, "Table information not found. Please check input for table name= " @@ -410,7 +434,7 @@ public class JsonUpdate implements Serializable { } counter = counter + 1; } - return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); + return new RowIdentifier(primaryKey.toString(), rowSpec.toString(), queryObject); } } diff --git a/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java index edce3fff..cb6816e0 100644 --- a/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java +++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java @@ -129,7 +129,7 @@ public class CassaLockStore { table = table_prepend_name+table; String tabQuery = "CREATE TABLE IF NOT EXISTS "+keyspace+"."+table + " ( key text, lockReference bigint, createTime text, acquireTime text, guard bigint static, " - + "lockType text, owner text, PRIMARY KEY ((key), lockReference) ) " + + "lockType text, leasePeriodTime bigint, owner text, PRIMARY KEY ((key), lockReference) ) " + "WITH CLUSTERING ORDER BY (lockReference ASC);"; PreparedQueryObject queryObject = new PreparedQueryObject(); diff --git a/music-core/src/main/java/org/onap/music/main/MusicUtil.java b/music-core/src/main/java/org/onap/music/main/MusicUtil.java index d46e770e..db51322d 100644 --- a/music-core/src/main/java/org/onap/music/main/MusicUtil.java +++ b/music-core/src/main/java/org/onap/music/main/MusicUtil.java @@ -73,6 +73,7 @@ public class MusicUtil { public static final String EVENTUAL_NB = "eventual_nb"; public static final String ALL = "all"; public static final String QUORUM = "quorum"; + public static final String LOCAL_QUORUM = "local_quorum"; public static final String ONE = "one"; public static final String ATOMICDELETELOCK = "atomic_delete_lock"; diff --git a/music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java index 39432d07..90cd68e2 100644 --- a/music-core/src/test/java/org/onap/music/unittests/MusicUtilTest.java +++ b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java @@ -21,7 +21,7 @@ * ==================================================================== */ -package org.onap.music.unittests; +package org.onap.music.cassandra; import static org.junit.Assert.*; import java.math.BigInteger; diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java index a069b81d..0014f823 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java @@ -22,7 +22,7 @@ * ==================================================================== */ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.jsonobjects; import static org.junit.Assert.*; import java.util.ArrayList; @@ -31,7 +31,6 @@ import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonDelete; public class JsonDeleteTest { diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java index 4992af7b..ad71c9ea 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java @@ -22,17 +22,31 @@ * ==================================================================== */ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.jsonobjects; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; - +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.FieldSetter; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Session; +//import org.mockito.internal.util.reflection.Whitebox; +import com.datastax.driver.core.TableMetadata; + public class JsonInsertTest { @@ -107,5 +121,56 @@ public class JsonInsertTest { ji.setObjectMap(map); assertEquals(map, ji.getObjectMap()); } + + @Test + public void testPrimaryKey() { + ji.setPrimaryKeyVal("primKey"); + assertEquals("primKey", ji.getPrimaryKeyVal()); + } + + @Test + public void testGenInsertPreparedQueryObj() throws Exception { + ji.setKeyspaceName("keyspace"); + ji.setTableName("table"); + ji.setPrimaryKeyVal("value"); + Map<String,Object> rowSpec = new HashMap<>(); + rowSpec.put("val1","one"); + rowSpec.put("val2","two"); + ji.setRowSpecification(rowSpec); + Map<String,Object> vals = new HashMap<>(); + vals.put("val1","one"); + vals.put("val2","two"); + ji.setValues(vals); + + Map<String,String> cons = new HashMap<>(); + cons.put("type","quorum"); + ji.setConsistencyInfo(cons); + + MusicDataStore mds = Mockito.mock(MusicDataStore.class); + Session session = Mockito.mock(Session.class); + Mockito.when(mds.getSession()).thenReturn(session); + MusicDataStoreHandle mdsh = Mockito.mock(MusicDataStoreHandle.class); + FieldSetter.setField(mdsh, mdsh.getClass().getDeclaredField("mDstoreHandle"), mds); + TableMetadata tableMeta = Mockito.mock(TableMetadata.class); + Mockito.when(mds.returnColumnMetadata(Mockito.anyString(), Mockito.anyString())) + .thenReturn(tableMeta); + + ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class); + List<ColumnMetadata> listcmd = new ArrayList<>(); + listcmd.add(cmd); + Mockito.when(tableMeta.getPrimaryKey()).thenReturn(listcmd); + Mockito.when(cmd.getName()).thenReturn("val1"); + Mockito.when(tableMeta.getColumn("val1")).thenReturn(cmd); + Mockito.when(tableMeta.getColumn("val2")).thenReturn(cmd); + Mockito.when(cmd.getType()).thenReturn(DataType.text()); + + PreparedQueryObject query = ji.genInsertPreparedQueryObj(); + System.out.println(query.getQuery()); + System.out.println(query.getValues()); + + + assertEquals("INSERT INTO keyspace.table (vector_ts,val2,val1) VALUES (?,?,?);", query.getQuery()); + assertTrue(query.getValues().containsAll(vals.values())); + } } diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java index 0f4abd7c..a3fa58e4 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java @@ -20,14 +20,13 @@ * ==================================================================== */ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.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 { diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java index 37d1787a..21c022ab 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java @@ -22,7 +22,7 @@ * ==================================================================== */ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.jsonobjects; import static org.junit.Assert.assertEquals; @@ -31,7 +31,6 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonSelect; public class JsonSelectTest { diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java index 4e3b4629..3ab32d40 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java @@ -22,14 +22,14 @@ * ==================================================================== */ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.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; +import org.onap.music.exceptions.MusicQueryException; public class JsonTableTest { @@ -53,6 +53,7 @@ public class JsonTableTest { Map<String, Object> properties = new HashMap<>(); properties.put("k1", "one"); jt.setProperties(properties); + assertEquals(properties.size(), jt.getProperties().size()); } @Test @@ -83,6 +84,13 @@ public class JsonTableTest { jt.setClusteringOrder(clusteringOrder); assertEquals(clusteringOrder,jt.getClusteringOrder()); } + + @Test + public void testGetClusterKey() { + String clusterKey = "clusterKey"; + jt.setClusteringKey(clusterKey); + assertEquals(clusterKey, jt.getClusteringKey()); + } @Test public void testGetPrimaryKey() { @@ -96,5 +104,50 @@ public class JsonTableTest { jt.setFilteringKey("FilteringKey"); assertEquals("FilteringKey",jt.getFilteringKey()); } + + @Test + public void testPartitionKey() { + jt.setPartitionKey("ParitionKey"); + assertEquals("ParitionKey",jt.getPartitionKey()); + } + @Test + public void genCreateTableQuery() throws MusicQueryException { + JsonTable jt2 = new JsonTable(); + jt2.setKeyspaceName("keyspace"); + jt2.setTableName("table"); + Map<String, String> fields = new HashMap<>(); + fields.put("k1", "one"); + jt2.setFields(fields); + jt2.setPrimaryKey("k1"); + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt2.setConsistencyInfo(mapSs); + String clusteringOrder = "clusteringOrder"; + jt.setClusteringOrder(clusteringOrder); + String clusterKey = "clusterKey"; + jt.setClusteringKey(clusterKey); + + System.out.println(jt2.genCreateTableQuery().getQuery()); + assertEquals("CREATE TABLE keyspace.table (vector_ts text,k1 one, PRIMARY KEY ( (k1) ));", + jt2.genCreateTableQuery().getQuery()); + } + + @Test + public void genDropTableQuery() throws MusicQueryException { + JsonTable jt2 = new JsonTable(); + jt2.setKeyspaceName("keyspace"); + jt2.setTableName("table"); + Map<String, String> fields = new HashMap<>(); + fields.put("k1", "one"); + jt2.setFields(fields); + jt2.setPrimaryKey("k1"); + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt.setConsistencyInfo(mapSs); + + System.out.println(jt2.genDropTableQuery().getQuery()); + assertEquals("DROP TABLE keyspace.table;", + jt2.genDropTableQuery().getQuery()); + } } diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java index e00cb463..37c729f4 100644 --- a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java @@ -22,14 +22,22 @@ * ==================================================================== *******************************************************************************/ -package org.onap.music.unittests.jsonobjects; +package org.onap.music.datastore.jsonobjects; import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; +import javax.ws.rs.core.MultivaluedMap; import org.junit.Before; import org.junit.Test; -import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.mockito.Mockito; +import org.onap.music.datastore.jsonobjects.JsonUpdate.RowIdentifier; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; public class JsonUpdateTest { @@ -108,4 +116,51 @@ public class JsonUpdateTest { assertTrue(ju.serialize() instanceof byte[]); } + @Test + public void testRowIdString() { + ju.setRowIdString("testing"); + assertEquals("testing", ju.getRowIdString()); + } + + @Test + public void testPrimaryKeyValue() { + ju.setPrimarKeyValue("primeKey"); + assertEquals("primeKey", ju.getPrimarKeyValue()); + } + + @Test + public void testGenUpdatePreparedQueryObj() throws Exception { + JsonUpdate ju = Mockito.spy(JsonUpdate.class); + MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class); + + ju.setKeyspaceName("keyspace"); + ju.setTableName("table"); + ju.setPrimarKeyValue("primaryKeyValue"); + Map<String, String> consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "critical"); + ju.setConsistencyInfo(consistencyInfo); + Map<String, Object> values = new HashMap<>(); + values.put("col1", "val1"); + ju.setValues(values); + + TableMetadata tmd = Mockito.mock(TableMetadata.class); + Mockito.doReturn(tmd).when(ju).returnColumnMetadata(Mockito.anyString(), Mockito.anyString()); + ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class); + Mockito.when(tmd.getColumn("col1")).thenReturn(cmd); + List<ColumnMetadata> colList = new ArrayList<>(); + colList.add(cmd); + Mockito.when(tmd.getPrimaryKey()).thenReturn(colList); + Mockito.when(cmd.getType()).thenReturn(DataType.varchar()); + + RowIdentifier rowId = Mockito.mock(RowIdentifier.class); + Mockito.doReturn(rowId).when(ju).getRowIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any(), + Mockito.any()); + + Mockito.when(rowId.getRowIdString()).thenReturn("col1"); + Mockito.when(rowId.getPrimaryKeyValue()).thenReturn("val1"); + + + assertEquals("UPDATE keyspace.table SET vector_ts=?,col1= ? WHERE col1;", + ju.genUpdatePreparedQueryObj(rowParams).getQuery()); + } } diff --git a/music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java index 012629e0..d6ccc1f1 100644 --- a/music-core/src/test/java/org/onap/music/unittests/ResultTypeTest.java +++ b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java @@ -20,11 +20,10 @@ * ==================================================================== */ -package org.onap.music.unittests; +package org.onap.music.main; import static org.junit.Assert.*; import org.junit.Test; -import org.onap.music.main.ResultType; public class ResultTypeTest { diff --git a/music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java index 490020ac..fbb5f84d 100644 --- a/music-core/src/test/java/org/onap/music/unittests/ReturnTypeTest.java +++ b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java @@ -20,7 +20,7 @@ * ==================================================================== */ -package org.onap.music.unittests; +package org.onap.music.main; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -28,8 +28,6 @@ import static org.junit.Assert.assertTrue; import java.util.Map; import org.junit.Test; -import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; public class ReturnTypeTest { diff --git a/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java b/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java deleted file mode 100644 index 582744fb..00000000 --- a/music-core/src/test/java/org/onap/music/unittests/CassandraCQL.java +++ /dev/null @@ -1,245 +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; - -/** - * @author srupane - * - */ - -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -//import org.apache.thrift.transport.TTransportException; -import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.onap.music.datastore.MusicDataStore; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.lockingservice.cassandra.LockType; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.extras.codecs.enums.EnumNameCodec; - -public class CassandraCQL { - public static final String createAdminKeyspace = "CREATE KEYSPACE admin WITH REPLICATION = " - + "{'class' : 'SimpleStrategy' , 'replication_factor': 1} AND DURABLE_WRITES = true"; - - public static final String createAdminTable = "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text," - + " application_name text, is_api boolean," - + " password text, username text," - + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");"; - - public static final String createKeySpace = - "CREATE KEYSPACE IF NOT EXISTS testcassa WITH replication = " - +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;"; - - public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testcassa"; - - public static final String createTableEmployees = - "CREATE TABLE IF NOT EXISTS testcassa.employees " - + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map<text,text>,PRIMARY KEY (empname)) " - + "WITH comment='Financial Info of employees' " - + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} " - + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};"; - - public static final String insertIntoTablePrepared1 = - "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary) VALUES (?,?,?,?); "; - - public static final String insertIntoTablePrepared2 = - "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);"; - - public static final String selectALL = "SELECT * FROM testcassa.employees;"; - - public static final String selectSpecific = - "SELECT * FROM testcassa.employees WHERE empname= ?;"; - - public static final String updatePreparedQuery = - "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;"; - - public static final String deleteFromTable = " "; - - public static final String deleteFromTablePrepared = " "; - - // Set Values for Prepared Query - - public static List<Object> setPreparedInsertValues1() { - - List<Object> preppreparedInsertValues1 = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6"); - BigInteger empSalary = BigInteger.valueOf(23443); - String empName = "Mr Test one"; - preppreparedInsertValues1.add(vectorTs); - preppreparedInsertValues1.add(empId); - preppreparedInsertValues1.add(empName); - preppreparedInsertValues1.add(empSalary); - return preppreparedInsertValues1; - } - - public static List<Object> setPreparedInsertValues2() { - - List<Object> preparedInsertValues2 = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6"); - BigInteger empSalary = BigInteger.valueOf(45655); - String empName = "Mr Test two"; - Map<String, String> address = new HashMap<>(); - preparedInsertValues2.add(vectorTs); - preparedInsertValues2.add(empId); - preparedInsertValues2.add(empName); - preparedInsertValues2.add(empSalary); - address.put("Street", "1 some way"); - address.put("City", "Some town"); - preparedInsertValues2.add(address); - return preparedInsertValues2; - } - - public static List<Object> setPreparedUpdateValues() { - - List<Object> preparedUpdateValues = new ArrayList<>(); - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); - Map<String, String> address = new HashMap<>(); - preparedUpdateValues.add(vectorTs); - String empName = "Mr Test one"; - address.put("Street", "101 Some Way"); - address.put("City", "New York"); - preparedUpdateValues.add(address); - preparedUpdateValues.add(empName); - return preparedUpdateValues; - } - - // Generate Different Prepared Query Objects - /** - * Query Object for Get. - * - * @return - */ - public static PreparedQueryObject setPreparedGetQuery() { - - PreparedQueryObject queryObject = new PreparedQueryObject(); - String empName1 = "Mr Test one"; - queryObject.appendQueryString(selectSpecific); - queryObject.addValue(empName1); - return queryObject; - } - - /** - * Query Object 1 for Insert. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedInsertQueryObject1() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(insertIntoTablePrepared1); - List<Object> values = setPreparedInsertValues1(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - /** - * Query Object 2 for Insert. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedInsertQueryObject2() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(insertIntoTablePrepared2); - List<Object> values = setPreparedInsertValues2(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - /** - * Query Object for Update. - * - * @return {@link PreparedQueryObject} - */ - public static PreparedQueryObject setPreparedUpdateQueryObject() { - - PreparedQueryObject queryobject = new PreparedQueryObject(); - queryobject.appendQueryString(updatePreparedQuery); - List<Object> values = setPreparedUpdateValues(); - if (!values.isEmpty() || values != null) { - for (Object o : values) { - queryobject.addValue(o); - } - } - return queryobject; - - } - - private static ArrayList<String> getAllPossibleLocalIps() { - ArrayList<String> allPossibleIps = new ArrayList<String>(); - try { - Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); - while (en.hasMoreElements()) { - NetworkInterface ni = (NetworkInterface) en.nextElement(); - Enumeration<InetAddress> ee = ni.getInetAddresses(); - while (ee.hasMoreElements()) { - InetAddress ia = (InetAddress) ee.nextElement(); - allPossibleIps.add(ia.getHostAddress()); - } - } - } catch (SocketException e) { - System.out.println(e.getMessage()); - } - return allPossibleIps; - } - - public static MusicDataStore connectToEmbeddedCassandra() throws Exception { - System.setProperty("log4j.configuration", "log4j.properties"); - - String address = "localhost"; - - EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build(); - cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000); - - Session session = cluster.connect(); - - return new MusicDataStore(cluster, session); - } - -} |