aboutsummaryrefslogtreecommitdiffstats
path: root/mdbc-server/src/test/java/org/onap
diff options
context:
space:
mode:
authorRob Daugherty <rd472p@att.com>2018-11-05 10:23:04 -0500
committerRob Daugherty <rd472p@att.com>2018-11-05 10:33:13 -0500
commit95d22d7491ea365fdc4525e44d484c73c33e16a1 (patch)
treea5fdb7de3f14b345db760463cec8cee130b5b116 /mdbc-server/src/test/java/org/onap
parent8dca3aebe55502ab35402da6ec7123bd3de7694d (diff)
Modularized mdbc build
The mdbc pom should inherit from oparent. The top-level pom should not build the jar directly. It should be a parent pom for mdbc submodules. The first submodule will be called mdbc-server. Note: the "mdbc" jar will now be called "mdbc-server". Change-Id: I4456e659b7494641e5b3cefd540eb62a149b79a4 Issue-ID: MUSIC-175 Signed-off-by: Rob Daugherty <rd472p@att.com>
Diffstat (limited to 'mdbc-server/src/test/java/org/onap')
-rw-r--r--mdbc-server/src/test/java/org/onap/music/mdbc/DatabaseOperationsTest.java499
-rw-r--r--mdbc-server/src/test/java/org/onap/music/mdbc/MDBCUtilsTest.java91
-rw-r--r--mdbc-server/src/test/java/org/onap/music/mdbc/TestUtils.java102
-rwxr-xr-xmdbc-server/src/test/java/org/onap/music/mdbc/test/ALLTESTS.java33
-rwxr-xr-xmdbc-server/src/test/java/org/onap/music/mdbc/test/BasicTest.java96
-rwxr-xr-xmdbc-server/src/test/java/org/onap/music/mdbc/test/CrossSiteTest.java466
-rwxr-xr-xmdbc-server/src/test/java/org/onap/music/mdbc/test/TestCommon.java44
-rwxr-xr-xmdbc-server/src/test/java/org/onap/music/mdbc/test/TransactionTest.java183
8 files changed, 1514 insertions, 0 deletions
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/DatabaseOperationsTest.java b/mdbc-server/src/test/java/org/onap/music/mdbc/DatabaseOperationsTest.java
new file mode 100644
index 0000000..b9a929c
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/DatabaseOperationsTest.java
@@ -0,0 +1,499 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc;
+
+import com.datastax.driver.core.*;
+import com.datastax.driver.core.exceptions.QueryExecutionException;
+import com.datastax.driver.core.exceptions.SyntaxError;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.zookeeper.ZooKeeper;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.music.datastore.CassaDataStore;
+import org.onap.music.exceptions.MDBCServiceException;
+import org.onap.music.exceptions.MusicLockingException;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.logging.EELFLoggerDelegate;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.MusicUtil;
+import org.onap.music.main.ResultType;
+import org.onap.music.main.ReturnType;
+import org.onap.music.mdbc.tables.*;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import static org.junit.Assert.*;
+
+public class DatabaseOperationsTest {
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DatabaseOperationsTest.class);
+
+ final private String keyspace="metricmusictest";
+ final private String mriTableName = "musicrangeinformation";
+ final private String mtdTableName = "musictxdigest";
+
+
+ // Lock and cojndition variable used to test connection to zookeeper
+ final private Lock lock = new ReentrantLock();
+ final private Condition ready = lock.newCondition();
+ //Flag used to detect connection failures before running any tests in metric
+ private boolean first=true;
+ //Properties used to connect to music
+ private Properties prop= new Properties();
+ private Cluster cluster;
+ private Session session;
+ @Before
+ public void setUp() throws Exception {
+ // System.out.println("TEST 1: Getting ready for testing connection to Cassandra");
+//
+ if(first) {
+ //Read properties file to access cassandra and zookeeper
+ readPropertiesFile();
+ //Test cassandra is correctly running
+ String cassaHost = prop.getProperty("cassandra.host",MusicUtil.getMyCassaHost());
+ String cassaUser = prop.getProperty("cassandra.user",MusicUtil.getCassName());
+ String cassaPwd = prop.getProperty("cassandra.password",MusicUtil.getCassPwd());
+ cluster = Cluster.builder().addContactPoints(cassaHost)
+ .withCredentials(cassaUser,cassaPwd).build();
+ assertNotNull("Invalid configuration for cassandra", cluster);
+ session = cluster.connect();
+ assertNotNull("Invalid configuration for cassandra", session);
+ TestUtils.populateMusicUtilsWithProperties(prop);
+ //Test zookeeper is correctly running
+ String zookeeperHost = MusicUtil.getMyZkHost();
+ assertTrue(!zookeeperHost.isEmpty());
+ ZooKeeper zk = new ZooKeeper(zookeeperHost+":2181",3000,
+ we -> {
+ lock.lock();
+ ready.signalAll();
+ lock.unlock();
+ });
+ lock.lock();
+ ready.await(10, TimeUnit.SECONDS);
+ assertEquals(zk.getState(), ZooKeeper.States.CONNECTED);
+ assertNotNull("Invalid configuration for zookeper", zk);
+ long sessionId = zk.getSessionId();
+ assertNotEquals(sessionId,0);
+ zk.close();
+ CassaDataStore store = MusicCore.getDSHandle();
+ assertNotNull("Invalid configuration for music", store);
+ first = false;
+ }
+ //Create keyspace
+ createKeyspace();
+ useKeyspace();
+ }
+
+ private void createKeyspace() {
+ String queryOp = "CREATE KEYSPACE " +
+ keyspace +
+ " WITH REPLICATION " +
+ "= {'class':'SimpleStrategy', 'replication_factor':1}; ";
+ ResultSet res=null;
+ try {
+ res = session.execute(queryOp);
+ }
+ catch(QueryExecutionException e){
+ fail("Failure executing creation of keyspace with error: " + e.getMessage());
+ } catch(SyntaxError e){
+ fail("Failure executing creation of keyspace with syntax error: " + e.getMessage());
+ }
+ assertTrue("Keyspace "+keyspace+" is already being used, please change it to avoid loosing data",res.wasApplied());
+ }
+
+ private void useKeyspace(){
+ String queryBuilder = "USE " +
+ keyspace +
+ "; ";
+ ResultSet res = session.execute(queryBuilder);
+ assertTrue("Keyspace "+keyspace+" is already being used, please change it to avoid loosing data",res.wasApplied());
+ }
+
+ private void deleteKeyspace(){
+ String queryBuilder = "DROP KEYSPACE " +
+ keyspace +
+ ";";
+ ResultSet res = session.execute(queryBuilder);
+ assertTrue("Keyspace "+keyspace+" doesn't exist and it should",res.wasApplied());
+ }
+
+ private void readPropertiesFile() {
+ try {
+ String fileLocation = MusicUtil.getMusicPropertiesFilePath();
+ InputStream fstream = new FileInputStream(fileLocation);
+ prop.load(fstream);
+ fstream.close();
+ } catch (FileNotFoundException e) {
+ logger.error("Configuration file not found");
+
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ logger.error("Exception when reading file: "+e.toString());
+ }
+ }
+
+ @After
+ public void tearDown() {
+ deleteKeyspace();
+ }
+
+ private void CreateMTD(){
+ try {
+ DatabaseOperations.createMusicTxDigest(keyspace, mtdTableName);
+ } catch (MDBCServiceException e) {
+ fail("Execution of creating music tx digest failed");
+ }
+ }
+
+ @Test
+ public void createMusicTxDigest() {
+ HashSet<String> expectedColumns = new HashSet<>(
+ Arrays.asList("txid","transactiondigest")
+ );
+ HashMap<String,DataType> expectedTypes = new HashMap<>();
+ expectedTypes.put("txid",DataType.uuid());
+ expectedTypes.put("transactiondigest",DataType.text());
+ CreateMTD();
+ //check structure of table
+ CassaDataStore ds=null;
+ try {
+ ds = MusicCore.getDSHandle();
+ } catch (MusicServiceException e) {
+ fail("Getting DS handle fail with error " + e.getErrorMessage());
+ }
+ TableMetadata table = ds.returnColumnMetadata(keyspace,mtdTableName);
+ assertNotNull("Error obtaining metadata of table, there may be an error with its creation", table);
+ List<ColumnMetadata> columnsMeta = table.getColumns();
+ checkDataTypeForTable(columnsMeta,expectedColumns,expectedTypes);
+ }
+
+ @Test
+ public void createMusicRangeInformationTable() {
+ HashSet<String> expectedColumns = new HashSet<>(
+ Arrays.asList("rangeid","keys","txredolog","ownerid","metricprocessid")
+ );
+ HashMap<String,DataType> expectedTypes = new HashMap<>();
+ expectedTypes.put("rangeid",DataType.uuid());
+ expectedTypes.put("keys",DataType.set(DataType.text()));
+ ProtocolVersion currentVer = cluster.getConfiguration().getProtocolOptions().getProtocolVersion();
+ assertNotNull("Protocol version for cluster is invalid", currentVer);
+ CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
+ assertNotNull("Codec registry for cluster is invalid", registry);
+ expectedTypes.put("txredolog",DataType.list(TupleType.of(currentVer,registry,DataType.text(),DataType.uuid())));
+ expectedTypes.put("ownerid",DataType.text());
+ expectedTypes.put("metricprocessid",DataType.text());
+ try {
+ DatabaseOperations.createMusicRangeInformationTable(keyspace,mriTableName);
+ } catch (MDBCServiceException e) {
+ fail("Execution of creating music tx digest failed");
+ }
+ //check structure of table
+ CassaDataStore ds=null;
+ try {
+ ds = MusicCore.getDSHandle();
+ } catch (MusicServiceException e) {
+ fail("Getting DS handle fail with error " + e.getErrorMessage());
+ }
+ TableMetadata table = ds.returnColumnMetadata(keyspace,mriTableName);
+ assertNotNull("Error obtaining metadata of table, there may be an error with its creation", table);
+ List<ColumnMetadata> columnsMeta = table.getColumns();
+ checkDataTypeForTable(columnsMeta,expectedColumns,expectedTypes);
+ }
+
+ private void checkDataTypeForTable(List<ColumnMetadata> columnsMeta, HashSet<String> expectedColumns,
+ HashMap<String,DataType> expectedTypes){
+ for(ColumnMetadata cMeta : columnsMeta){
+ String columnName = cMeta.getName();
+ DataType type = cMeta.getType();
+ assertTrue("Invalid column name: "+columnName,expectedColumns.contains(columnName));
+ assertTrue("Fix the contents of expectedtypes for column: "+columnName,
+ expectedTypes.containsKey(columnName));
+ assertEquals("Invalid type for column: "+columnName,
+ expectedTypes.get(columnName),type);
+ }
+ }
+
+ private void createMRI(){
+ try {
+ DatabaseOperations.createMusicRangeInformationTable(keyspace,mriTableName);
+ } catch (MDBCServiceException e) {
+ fail("Execution of creating music tx digest failed");
+ }
+ }
+
+ @Test
+ public void createEmptyMriRow() {
+ //Assume mri creation is working
+ createMRI();
+ List<Range> ranges = new ArrayList<>();
+ ranges.add(new Range("table1"));
+ ranges.add(new Range("table2"));
+ final String lockId = null;
+ String processId = "tcp://test:1234";
+ UUID newRowId=null;
+ try {
+ newRowId = DatabaseOperations.createEmptyMriRow(keyspace,mriTableName,processId,
+ lockId, ranges);
+ } catch (MDBCServiceException e) {
+ fail("Adding a new empty mri row failed");
+ }
+ getRowFromMriAndCompare(newRowId,ranges,lockId,processId);
+ }
+
+ private String getLock(String table, MriReference mriIndex){
+ String fullyQualifiedMriKey = keyspace+"."+ mriIndex.table+"."+mriIndex.index.toString();
+ String lockId;
+ lockId = MusicCore.createLockReference(fullyQualifiedMriKey);
+ //\TODO Handle better failures to acquire locks
+ ReturnType lockReturn=null;
+ try {
+ lockReturn = MusicCore.acquireLock(fullyQualifiedMriKey,lockId);
+ } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
+ fail(e.getMessage());
+ }
+ assertEquals(lockReturn.getResult(),ResultType.SUCCESS);
+ return lockId;
+ }
+
+ private void releaseLock(MriReference mriIndex, String lock){
+ String fullyQualifiedMriKey = keyspace+"."+ mriIndex.table+"."+mriIndex.index.toString();
+ try {
+ MusicCore.voluntaryReleaseLock(fullyQualifiedMriKey,lock);
+ } catch (MusicLockingException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ private List<Range> getTestRanges(){
+ List<Range> ranges = new ArrayList<>();
+ ranges.add(new Range("table1"));
+ ranges.add(new Range("table2"));
+ return ranges;
+ }
+
+ private String getTestProcessId(){
+ return "tcp://test:1234";
+ }
+
+ private UUID CreateRowWithLockAndCheck(UUID newId, String lockId){
+
+ List<Range> ranges = getTestRanges();
+ String processId = getTestProcessId();
+ UUID newRowId=null;
+ try {
+ newRowId = DatabaseOperations.createEmptyMriRow(keyspace,mriTableName,newId, processId, lockId, ranges);
+ } catch (MDBCServiceException e) {
+ fail("Adding a new empty mri row failed");
+ }
+ getRowFromMriAndCompare(newRowId,ranges,lockId,processId);
+ return newRowId;
+ }
+
+ @Test
+ public void createEmptyMriRowWithLock() {
+ createMRI();
+ //Assume mri creation is working
+ UUID newId = DatabaseOperations.generateUniqueKey();
+ MriReference mriIndex = new MriReference(mriTableName,newId);
+ String lockId = getLock(mriTableName,mriIndex);
+ assertTrue("Error obtaining lock",!lockId.isEmpty());
+ UUID newRowId = CreateRowWithLockAndCheck(newId,lockId);
+ assertEquals(newRowId,newId);
+ releaseLock(mriIndex,lockId);
+ }
+
+ private void getRowFromMriAndCompare(UUID newRowId, List<Range> ranges, String lockId, String processId){
+ lockId=(lockId==null)?"":lockId;
+ ResultSet res=null;
+ String queryOp = "SELECT * FROM " +
+ keyspace + "." + mriTableName +
+ " WHERE rangeid = " +
+ newRowId +
+ ";";
+ try {
+ res = session.execute(queryOp);
+ }
+ catch(QueryExecutionException e){
+ fail("Failure executing retrieval of row in MRU error: " + e.getMessage());
+ } catch(SyntaxError e){
+ fail("Failure executing retrieval of row with syntax error: " + e.getMessage());
+ }
+ assertFalse(res.isExhausted());
+ Row response = res.one();
+ UUID id = response.get("rangeid",UUID.class);
+ assertEquals(id,newRowId);
+ Set<String> keys = response.getSet("keys",String.class);
+ for(Range r : ranges){
+ assertTrue("Table was not found in retrieved keys",keys.contains(r.table));
+ }
+ List<TupleValue> redo = response.getList("txredolog",TupleValue.class);
+ assertTrue(redo.isEmpty());
+ String ownerId = response.getString("ownerid");
+ assertEquals(ownerId,lockId);
+ String mpid= response.getString("metricprocessid");
+ assertEquals(mpid,processId);
+ }
+
+ @Test
+ public void getMriRow() {
+ createMRI();
+ //Assume mri creation is working
+ UUID newId = DatabaseOperations.generateUniqueKey();
+ MriReference mriIndex = new MriReference(mriTableName,newId);
+ String lockId = getLock(mriTableName,mriIndex);
+ assertTrue("Error obtaining lock",!lockId.isEmpty());
+ UUID newRowId = CreateRowWithLockAndCheck(newId,lockId);
+ MusicRangeInformationRow mriRow=null;
+ try {
+ mriRow = DatabaseOperations.getMriRow(keyspace, mriTableName, newRowId, lockId);
+ } catch (MDBCServiceException e) {
+ fail(e.getErrorMessage());
+ }
+ final List<Range> ranges = getTestRanges();
+ String processId = getTestProcessId();
+ assertEquals("invalid process id", mriRow.metricProcessId,processId);
+ assertEquals("invalid index", mriRow.index,newRowId);
+ assertEquals("invalid lock id",mriRow.ownerId,lockId);
+ assertTrue("redo log is not empty", mriRow.redoLog.isEmpty());
+ List<Range> readRange = mriRow.partition.ranges;
+ List<Range> range = ranges;
+ for(Range r: range){
+ boolean found = false;
+ for(Range rr : readRange) {
+ if(r.equals(rr)) {
+ found = true;
+ }
+
+ }
+ assertTrue("ranges are incorrect", found);
+ }
+ }
+
+ @Test
+ public void getTransactionDigest() {
+ CreateMTD();
+ Range inputRange = new Range("table1");
+ StagingTable inputStaging = new StagingTable();
+ inputStaging.addOperation("key1", OperationType.INSERT,"1");
+ HashMap<Range, StagingTable> input= new HashMap<>();
+ input.put(inputRange, inputStaging);
+ MusicTxDigestId newId = new MusicTxDigestId(DatabaseOperations.generateUniqueKey());
+ try {
+ DatabaseOperations.createTxDigestRow(keyspace,mtdTableName,newId,MDBCUtils.toString(input));
+ } catch (MDBCServiceException e) {
+ fail("Adding a new mtd row failed");
+ } catch (IOException e) {
+ fail("Fail compressing input staging tables");
+ }
+ HashMap<Range, StagingTable> results=null;
+ try {
+ results = DatabaseOperations.getTransactionDigest(keyspace,mtdTableName,newId);
+ } catch (MDBCServiceException e) {
+ fail("Adding a new mtd row failed with error: "+e.getErrorMessage());
+ }
+ assertTrue(results.containsKey(inputRange));
+ StagingTable newStaging = results.get(inputRange);
+ Deque<Pair<String,Operation>> opers=null;
+ Deque<Pair<String,Operation>> initialOpers=null;
+ try {
+ opers=newStaging.getIterableSnapshot();
+ initialOpers=inputStaging.getIterableSnapshot();
+ } catch (NoSuchFieldException e) {
+ fail(e.getMessage());
+ }
+ assertEquals("Operations are not equal",opers.size(),initialOpers.size());
+ while(!opers.isEmpty()){
+ Pair<String,Operation> recvOper = opers.getFirst();
+ Pair<String,Operation> originalOper = initialOpers.getFirst();
+ assertEquals(recvOper.getKey(),originalOper.getKey());
+ assertEquals(recvOper.getValue(),originalOper.getValue());
+ opers.removeFirst();
+ initialOpers.removeFirst();
+ }
+ }
+
+ @Test
+ public void createNamespace() {
+ deleteKeyspace();
+ try {
+ DatabaseOperations.createNamespace(keyspace,1);
+ } catch (MDBCServiceException e) {
+ fail(e.getErrorMessage());
+ }
+ String describeOp = "USE "+keyspace+";";
+ ResultSet res=null;
+ try {
+ res = session.execute(describeOp);
+ }
+ catch(QueryExecutionException e){
+ fail("Failure executing retrieval of row in MRU error: " + e.getMessage());
+ } catch(SyntaxError e){
+ fail("Failure executing retrieval of row with syntax error: " + e.getMessage());
+ }
+ assertTrue("Error with keyspace: "+keyspace, res.wasApplied());
+ }
+
+ private void getRowFromMtdAndCompare(MusicTxDigestId newId, String transactionDigest){
+ ResultSet res=null;
+ String queryOp = "SELECT * FROM " +
+ keyspace + "." + mtdTableName+
+ " WHERE txid = " +
+ newId.tablePrimaryKey +
+ ";";
+ try {
+ res = session.execute(queryOp);
+ }
+ catch(QueryExecutionException e){
+ fail("Failure executing retrieval of row in MTD error: " + e.getMessage());
+ } catch(SyntaxError e){
+ fail("Failure executing retrieval of row in MTD with syntax error: " + e.getMessage());
+ }
+ assertFalse(res.isExhausted());
+ Row response = res.one();
+ UUID id = response.getUUID("txId");
+ assertEquals(id,newId.tablePrimaryKey);
+ String digest = response.getString("transactiondigest");
+ assertEquals(digest,transactionDigest);
+ }
+
+ @Test
+ public void createTxDigestRow(){
+ CreateMTD();
+ MusicTxDigestId newId = new MusicTxDigestId(DatabaseOperations.generateUniqueKey());
+ String transactionDigest = "newdigest";
+ try {
+ DatabaseOperations.createTxDigestRow(keyspace,mtdTableName,newId,transactionDigest);
+ } catch (MDBCServiceException e) {
+ fail("Adding a new empty mtd row failed");
+ }
+ getRowFromMtdAndCompare(newId,transactionDigest);
+
+ }
+
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/MDBCUtilsTest.java b/mdbc-server/src/test/java/org/onap/music/mdbc/MDBCUtilsTest.java
new file mode 100644
index 0000000..2c26aed
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/MDBCUtilsTest.java
@@ -0,0 +1,91 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc;
+
+import org.onap.music.mdbc.tables.OperationType;
+import org.onap.music.mdbc.tables.StagingTable;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+
+import static org.junit.Assert.*;
+
+public class MDBCUtilsTest {
+
+ @Test
+ public void toStringTest1() {
+ StagingTable table = new StagingTable();
+ table.addOperation("test",OperationType.INSERT,(new JSONObject(new String[]{"test3", "Test4"})).toString());
+ String output=null;
+ try {
+ output = MDBCUtils.toString(table);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertTrue(output!=null);
+ assertTrue(!output.isEmpty());
+ }
+
+ @Test
+ public void toStringTest2() {
+ HashMap<String,StagingTable> mapToSerialize = new HashMap<>();
+ StagingTable table = new StagingTable();
+ table.addOperation("test",OperationType.INSERT,(new JSONObject(new String[]{"test3", "Test4"})).toString());
+ mapToSerialize.put("table",table);
+ String output=null;
+ try {
+ output = MDBCUtils.toString(mapToSerialize);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertTrue(output!=null);
+ assertTrue(!output.isEmpty());
+ }
+
+ @Test
+ public void toStringTest3() {
+ String testStr = "test";
+ OperationType typeTest = OperationType.INSERT;
+ String output=null;
+ try {
+ output = MDBCUtils.toString(testStr);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertTrue(output!=null);
+ assertTrue(!output.isEmpty());
+ output=null;
+ try {
+ output = MDBCUtils.toString(typeTest);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertTrue(output!=null);
+ assertTrue(!output.isEmpty());
+ }
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/TestUtils.java b/mdbc-server/src/test/java/org/onap/music/mdbc/TestUtils.java
new file mode 100644
index 0000000..111b65c
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/TestUtils.java
@@ -0,0 +1,102 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc;
+
+import org.onap.music.logging.EELFLoggerDelegate;
+import org.onap.music.main.MusicUtil;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Properties;
+
+public class TestUtils {
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TestUtils.class);
+
+ public static void populateMusicUtilsWithProperties(Properties prop){
+ //TODO: Learn how to do this properly within music
+ String[] propKeys = MusicUtil.getPropkeys();
+ for (int k = 0; k < propKeys.length; k++) {
+ String key = propKeys[k];
+ if (prop.containsKey(key) && prop.get(key) != null) {
+ switch (key) {
+ case "zookeeper.host":
+ MusicUtil.setMyZkHost(prop.getProperty(key));
+ break;
+ case "cassandra.host":
+ MusicUtil.setMyCassaHost(prop.getProperty(key));
+ break;
+ case "music.ip":
+ MusicUtil.setDefaultMusicIp(prop.getProperty(key));
+ break;
+ case "debug":
+ MusicUtil.setDebug(Boolean
+ .getBoolean(prop.getProperty(key).toLowerCase()));
+ break;
+ case "version":
+ MusicUtil.setVersion(prop.getProperty(key));
+ break;
+ case "music.rest.ip":
+ MusicUtil.setMusicRestIp(prop.getProperty(key));
+ break;
+ case "music.properties":
+ MusicUtil.setMusicPropertiesFilePath(prop.getProperty(key));
+ break;
+ case "lock.lease.period":
+ MusicUtil.setDefaultLockLeasePeriod(
+ Long.parseLong(prop.getProperty(key)));
+ break;
+ case "my.id":
+ MusicUtil.setMyId(Integer.parseInt(prop.getProperty(key)));
+ break;
+ case "all.ids":
+ String[] ids = prop.getProperty(key).split(":");
+ MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids)));
+ break;
+ case "public.ip":
+ MusicUtil.setPublicIp(prop.getProperty(key));
+ break;
+ case "all.public.ips":
+ String[] ips = prop.getProperty(key).split(":");
+ if (ips.length == 1) {
+ // Future use
+ } else if (ips.length > 1) {
+ MusicUtil.setAllPublicIps(
+ new ArrayList<String>(Arrays.asList(ips)));
+ }
+ break;
+ case "cassandra.user":
+ MusicUtil.setCassName(prop.getProperty(key));
+ break;
+ case "cassandra.password":
+ MusicUtil.setCassPwd(prop.getProperty(key));
+ break;
+ case "aaf.endpoint.url":
+ MusicUtil.setAafEndpointUrl(prop.getProperty(key));
+ break;
+ default:
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "No case found for " + key);
+ }
+ }
+ }
+
+
+ }
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/test/ALLTESTS.java b/mdbc-server/src/test/java/org/onap/music/mdbc/test/ALLTESTS.java
new file mode 100755
index 0000000..8a7a72b
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/test/ALLTESTS.java
@@ -0,0 +1,33 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc.test;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ //BasicTest.class,
+ //CrossSiteTest.class,
+ //TransactionTest.class
+})
+
+public class ALLTESTS {
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/test/BasicTest.java b/mdbc-server/src/test/java/org/onap/music/mdbc/test/BasicTest.java
new file mode 100755
index 0000000..0901534
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/test/BasicTest.java
@@ -0,0 +1,96 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc.test;
+
+import static org.junit.Assert.*;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+
+/**
+ * This is a basic test which creates some tables, does a few selects, adn runs some joins.
+ * It is mainly intended to make sure that no exceptions are thrown in basic operation.
+ */
+public class BasicTest extends TestCommon {
+ private static final String DB_CONNECTION = "avatica://" + "mem:db1";
+ private static final String KEYSPACE = "Basic_Test";
+
+ //@Test
+ public void test() {
+ try {
+ Connection connection = getDBConnection(DB_CONNECTION, KEYSPACE, "0");
+ assertNotNull(connection);
+ System.out.println("GOT conn");
+ Statement stmt = connection.createStatement();
+ assertNotNull(stmt);
+ System.out.println("GOT stmt");
+
+ try {
+ connection.setAutoCommit(false);
+ stmt.execute("CREATE TABLE IF NOT EXISTS PERSON(ID_ varchar(255), NAME varchar(255), SSN varchar(255), primary key (ID_))");
+ stmt.execute("INSERT INTO PERSON(ID_, NAME, SSN) VALUES('1', 'Anju', '111-22-3333')");
+ stmt.execute("INSERT INTO PERSON(ID_, NAME, SSN) VALUES('2', 'Sonia', '111-22-4444')");
+ stmt.execute("INSERT INTO PERSON(ID_, NAME, SSN) VALUES('3', 'Asha', '111-55-6666')");
+ dumptable(connection);
+
+ stmt.execute("DELETE FROM PERSON WHERE ID_ = '1'");
+ dumptable(connection);
+
+ stmt.execute("UPDATE PERSON SET NAME = 'foobar' WHERE ID_ = '2'");
+ dumptable(connection);
+
+ stmt.execute("CREATE TABLE IF NOT EXISTS SONG(ID_ varchar(255), PREF int, ARIA varchar(255), primary key (ID_, PREF))");
+ stmt.execute("INSERT INTO SONG(ID_, PREF, ARIA) VALUES('1', 1, 'Nessun Dorma')");
+ stmt.execute("INSERT INTO SONG(ID_, PREF, ARIA) VALUES('2', 5, 'O mio Bambino Caro')");
+ stmt.execute("INSERT INTO SONG(ID_, PREF, ARIA) VALUES('2', 2, 'Sweet Georgia Brown')");
+ stmt.execute("INSERT INTO SONG(ID_, PREF, ARIA) VALUES('3', 77, 'Mud Flats Blues')");
+ stmt.execute("INSERT INTO SONG(ID_, PREF, ARIA) VALUES('3', 69, 'Me & Mr Jones')");
+ ResultSet rs = stmt.executeQuery("SELECT * FROM PERSON AS P, SONG AS S WHERE P.ID_ = S.ID_");
+ while (rs.next()) {
+ System.out.println("ID_ " + rs.getInt("ID_") + " Name: " + rs.getString("NAME") + " Aria: " + rs.getString("ARIA"));
+ }
+ rs.close();
+ stmt.close();
+ connection.commit();
+ } catch (Exception e) {
+ fail(e.toString());
+ } finally {
+ connection.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail(e.toString());
+ }
+ System.out.println("BasicTest.test OK");
+ }
+
+ private void dumptable(Connection connection) throws SQLException {
+ Statement stmt = connection.createStatement();
+ ResultSet rs = stmt.executeQuery("SELECT * FROM PERSON");
+ while (rs.next()) {
+ System.out.println("ID_ " + rs.getInt("ID_") + " Name " + rs.getString("name"));
+ }
+ stmt.close();
+ System.out.println("--");
+ }
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/test/CrossSiteTest.java b/mdbc-server/src/test/java/org/onap/music/mdbc/test/CrossSiteTest.java
new file mode 100755
index 0000000..d4a7a27
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/test/CrossSiteTest.java
@@ -0,0 +1,466 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc.test;
+
+import static org.junit.Assert.*;
+
+import java.io.Reader;
+import java.io.StringReader;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.sql.Timestamp;
+import java.util.Random;
+
+import org.apache.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+
+/**
+ * This test tests a copy of data from DB1 to DB2. It tests the following H2 data types:
+ * VARCHAR, VARBINARY, INTEGER, BOOLEAN, DOUBLE, CLOB, TIMESTAMP.
+ */
+public class CrossSiteTest extends TestCommon {
+ private static final String DB_CONNECTION1 = "avatica://" + "mem:db1";
+ private static final String DB_CONNECTION2 = "avatica://" + "mem:db2";
+ private static final String KEYSPACE = "CrossSite_Test";
+ private final static Logger logger = Logger.getLogger(CrossSiteTest.class);
+
+ private Connection db1, db2;
+
+ //@BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ // drop the keyspace
+ }
+
+ //@Before
+ public void setUp() throws Exception {
+ db1 = getDBConnection(DB_CONNECTION1, KEYSPACE, "0");
+ db2 = getDBConnection(DB_CONNECTION2, KEYSPACE, "1");
+ }
+
+ //@After
+ public void tearDown() throws Exception {
+ db1.close();
+ db2.close();
+ }
+
+ //@Test
+ public void testCopyOneToTwo() {
+ String sql = "CREATE TABLE IF NOT EXISTS DATA(KEY VARCHAR(255), PRIMARY KEY (KEY))";
+ createTable(sql);
+
+ // Put data in DB1
+ try {
+ Statement s = db1.createStatement();
+ s.execute("INSERT INTO DATA(KEY) VALUES('AAA')");
+ s.execute("INSERT INTO DATA(KEY) VALUES('BBB')");
+ s.execute("INSERT INTO DATA(KEY) VALUES('CCC')");
+ s.execute("INSERT INTO DATA(KEY) VALUES('DDD')");
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM DATA");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(4, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ // Delete a row
+ try {
+ Statement s = db1.createStatement();
+ s.execute("DELETE FROM DATA WHERE KEY = 'CCC'");
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Recheck
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM DATA");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(3, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ System.out.println("CrossSiteTest.testCopyOneToTwo OK");
+ }
+
+ //@Test
+ public void testCopyWithPreparedStatement() {
+ String sql = "CREATE TABLE IF NOT EXISTS DATA2(KEY VARCHAR(255), PRIMARY KEY (KEY))";
+ createTable(sql);
+
+ // Put data in DB1
+ try {
+ Statement s = db1.createStatement();
+ PreparedStatement ps = db1.prepareStatement("INSERT INTO DATA2(KEY) VALUES(?)");
+ for (String v : new String[] { "WWW", "XXX", "YYY", "ZZZ" } ) {
+ ps.setString(1, v);
+ ps.execute();
+ }
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM DATA2");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(4, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ System.out.println("CrossSiteTest.testCopyWithPreparedStatement OK");
+ }
+
+ //@Test
+ public void testDataTypes() {
+ String sql = "CREATE TABLE IF NOT EXISTS DATATYPES(KEY VARCHAR(255), I1 INTEGER, B1 BOOLEAN, D1 DOUBLE, S1 VARCHAR, PRIMARY KEY (KEY))";
+ createTable(sql);
+
+ String key = "ThIs Is ThE KeY";
+ String key2 = "ThIs Is another KeY";
+ String s1 = "The Rain in Spain";
+ int i1 = 696969;
+ boolean b1 = true;
+ double pi = Math.PI;
+ double e = Math.E;
+
+ // Put data in DB1
+ try {
+ PreparedStatement ps = db1.prepareStatement("INSERT INTO DATATYPES(KEY, I1, B1, D1, S1) VALUES(?, ?, ?, ?, ?)");
+ ps.setString(1, key);
+ ps.setInt(2, i1);
+ ps.setBoolean(3, b1);
+ ps.setDouble(4, pi);
+ ps.setString(5, s1);
+ ps.execute();
+
+ ps.setString(1, key2);
+ ps.setInt(2, 123456);
+ ps.setBoolean(3, false);
+ ps.setDouble(4, e);
+ ps.setString(5, "Fee fi fo fum!");
+ ps.execute();
+ db1.commit();
+ ps.close();
+ } catch (Exception ex) {
+ fail("1: " + ex.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT * FROM DATATYPES");
+ if (rs.next()) {
+ assertEquals(key, rs.getString(1));
+ assertEquals(i1, rs.getInt(2));
+ assertEquals(b1, rs.getBoolean(3));
+ assertEquals(pi, rs.getDouble(4), 0.0);
+ assertEquals(s1, rs.getString(5));
+ } else {
+ fail("SELECT * FROM DATATYPES");
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ ex.printStackTrace();
+ fail("2: " + ex.toString());
+ }
+ System.out.println("CrossSiteTest.testDataTypes OK");
+ }
+
+ //@Test
+ public void testIdentityColumn() {
+ String sql = "CREATE TABLE IF NOT EXISTS IDENTITYTEST(KEY IDENTITY, S1 VARCHAR, T1 TIMESTAMP, PRIMARY KEY (KEY))";
+ createTable(sql);
+
+ String s1 = "ThIs Is ThE IDENTITY test";
+ Timestamp ts = new Timestamp(-3535344000L);
+
+ // Put data in DB1
+ try {
+ PreparedStatement ps = db1.prepareStatement("INSERT INTO IDENTITYTEST(S1, T1) VALUES(?, ?)");
+ ps.setString(1, s1);
+ ps.setTimestamp(2, ts);
+ ps.execute();
+ db1.commit();
+ ps.close();
+ } catch (Exception ex) {
+ fail("testIdentity 1: " + ex.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT * FROM IDENTITYTEST");
+ if (rs.next()) {
+ assertEquals(s1, rs.getString("s1"));
+ assertEquals(ts, rs.getTimestamp("t1"));
+ } else {
+ fail("SELECT * FROM DATATYPES");
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ ex.printStackTrace();
+ fail("testIdentity 2: " + ex.toString());
+ }
+ System.out.println("CrossSiteTest.testIdentityColumn OK");
+ }
+
+ //@Test
+ public void testBLOBColumn() {
+ String sql = "CREATE TABLE IF NOT EXISTS BLOBTEST (KEY VARCHAR, V1 VARBINARY, C1 CLOB, PRIMARY KEY (KEY))";// add
+ createTable(sql);
+
+ String key = "BLOB test";
+ byte[] v1 = new byte[4096];
+ new Random().nextBytes(v1);
+ String constitution =
+ "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defense, promote the "+
+ "general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America."+
+ "Section 1"+
+ "All legislative Powers herein granted shall be vested in a Congress of the United States, which shall consist of a Senate and House of Representatives."+
+ ""+
+ "Section 2"+
+ "1: The House of Representatives shall be composed of Members chosen every second Year by the People of the several States, and the Electors in each State shall "+
+ "have the Qualifications requisite for Electors of the most numerous Branch of the State Legislature."+
+ ""+
+ "2: No Person shall be a Representative who shall not have attained to the Age of twenty five Years, and been seven Years a Citizen of the United States, "+
+ "and who shall not, when elected, be an Inhabitant of that State in which he shall be chosen."+
+ ""+
+ "3: Representatives and direct Taxes shall be apportioned among the several States which may be included within this Union, according to their respective Numbers, which shall be determined "+
+ "by adding to the whole Number of free Persons, including those bound to Service for a Term of Years, and excluding Indians not taxed, three fifths of all other Persons. "+
+ "2 The actual Enumeration shall be made within three Years after the first Meeting of the Congress of the United States, and within every subsequent Term of ten Years, in such Manner as "+
+ "they shall by Law direct. The Number of Representatives shall not exceed one for every thirty Thousand, but each State shall have at Least one Representative; and until such enumeration "+
+ "shall be made, the State of New Hampshire shall be entitled to chuse three, Massachusetts eight, Rhode-Island and Providence Plantations one, Connecticut five, New-York six, New Jersey four, "+
+ "Pennsylvania eight, Delaware one, Maryland six, Virginia ten, North Carolina five, South Carolina five, and Georgia three."+
+ ""+
+ "4: When vacancies happen in the Representation from any State, the Executive Authority thereof shall issue Writs of Election to fill such Vacancies."+
+ ""+
+ "5: The House of Representatives shall chuse their Speaker and other Officers; and shall have the sole Power of Impeachment."+
+ "etc., etc. ...";
+ Reader c1 = new StringReader(constitution);
+
+ // Put data in DB1
+ try {
+ CallableStatement ps = db1.prepareCall("INSERT INTO BLOBTEST(KEY, V1, C1) VALUES (?, ?, ?)");
+ ps.setString(1, key);
+ ps.setBytes(2, v1);
+ ps.setClob(3, c1);
+ ps.execute();
+ db1.commit();
+ ps.close();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ fail("testBLOBColumn 1: " + ex.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT * FROM BLOBTEST");
+ if (rs.next()) {
+ String v1s = new String(v1);
+ assertEquals(key, rs.getString("key"));
+ assertEquals(v1s, new String(rs.getBytes("v1")));
+ assertEquals(constitution, new String(rs.getBytes("c1")));
+ } else {
+ fail("SELECT * FROM BLOBTEST");
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ ex.printStackTrace();
+ fail("testBLOBColumn 2: " + ex.toString());
+ }
+ System.out.println("CrossSiteTest.testBLOBColumn OK");
+ }
+
+ //@Test
+ public void testSecondaryIndex() {
+ String sql = "CREATE TABLE IF NOT EXISTS ARTISTS (ARTIST VARCHAR, GENRE VARCHAR, AGE INT, PRIMARY KEY (ARTIST))";
+ createTable(sql);
+
+ // Put data in DB1
+ try {
+ Statement s = db1.createStatement();
+ s.execute("INSERT INTO ARTISTS(ARTIST, GENRE, AGE) VALUES('Anne-Sophie', 'classical', 53)");
+ s.execute("INSERT INTO ARTISTS(ARTIST, GENRE, AGE) VALUES('Dizz', 'jazz', 99)");
+ s.execute("INSERT INTO ARTISTS(ARTIST, GENRE, AGE) VALUES('Esperanza', 'jazz', 32)");
+ s.execute("INSERT INTO ARTISTS(ARTIST, GENRE, AGE) VALUES('Miles', 'jazz', 90)");
+ s.execute("INSERT INTO ARTISTS(ARTIST, GENRE, AGE) VALUES('Yo-yo', 'classical', 61)");
+ s.execute("CREATE INDEX BYGENRE on ARTISTS(GENRE)");
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM ARTISTS WHERE GENRE = 'jazz'");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(3, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ // Delete a row
+ try {
+ Statement s = db1.createStatement();
+ s.execute("DELETE FROM ARTISTS WHERE ARTIST = 'Miles'");
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Recheck
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM ARTISTS WHERE GENRE = 'jazz'");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(2, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ System.out.println("CrossSiteTest.testSecondaryIndex OK");
+ }
+
+ //@Test
+ public void testUpdate() {
+ String sql = "CREATE TABLE IF NOT EXISTS UPDATETEST(KEY VARCHAR(255), OTHER VARCHAR(255), PRIMARY KEY (KEY))";
+ createTable(sql);
+
+ // Put data in DB1
+ try {
+ Statement s = db1.createStatement();
+ s.execute("INSERT INTO UPDATETEST(KEY, OTHER) VALUES('foo', 'bar')");
+ s.execute("INSERT INTO UPDATETEST(KEY, OTHER) VALUES('bar', 'nixon')");
+ db1.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Get data in DB2
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db2.createStatement();
+ ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM UPDATETEST");
+ if (rs.next()) {
+ int n = rs.getInt(1);
+ assertEquals(2, n);
+ } else {
+ fail("SELECT COUNT(*) produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ // Update a row
+ try {
+ Statement s = db2.createStatement();
+ s.execute("UPDATE UPDATETEST SET OTHER = 'obama' WHERE KEY = 'bar'");
+ db2.commit();
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ // Recheck
+ logger.info(" Get data in DB2");
+ try {
+ Statement s = db1.createStatement();
+ ResultSet rs = s.executeQuery("SELECT OTHER FROM UPDATETEST WHERE KEY = 'bar'");
+ if (rs.next()) {
+ String str = rs.getString("OTHER");
+ assertEquals("obama", str);
+ } else {
+ fail("SELECT OTHER produced no result");
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ System.out.println("CrossSiteTest.testUpdate OK");
+ }
+
+ private void createTable(String sql) {
+ try {
+ for (Connection db : new Connection[] { db1, db2 }) {
+ logger.info(" start: "+db);
+ Statement s = db.createStatement();
+ s.execute(sql);
+ db.commit();
+ s.close();
+ logger.info(" Tables created");
+ }
+ } catch (Exception e) {
+ fail(e.toString());
+ }
+ }
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/test/TestCommon.java b/mdbc-server/src/test/java/org/onap/music/mdbc/test/TestCommon.java
new file mode 100755
index 0000000..c618f3b
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/test/TestCommon.java
@@ -0,0 +1,44 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc.test;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+
+import org.onap.music.mdbc.mixins.CassandraMixin;
+
+public class TestCommon {
+ public static final String DB_DRIVER = "avatica.Driver";
+ public static final String DB_USER = "";
+ public static final String DB_PASSWORD = "";
+
+ public Connection getDBConnection(String url, String keyspace, String id) throws SQLException, ClassNotFoundException {
+ Class.forName(DB_DRIVER);
+ Properties driver_info = new Properties();
+ driver_info.put(CassandraMixin.KEY_MY_ID, id);
+ driver_info.put(CassandraMixin.KEY_REPLICAS, "0,1,2");
+ driver_info.put(CassandraMixin.KEY_MUSIC_ADDRESS, "localhost");
+ driver_info.put("user", DB_USER);
+ driver_info.put("password", DB_PASSWORD);
+ return DriverManager.getConnection(url, driver_info);
+ }
+}
diff --git a/mdbc-server/src/test/java/org/onap/music/mdbc/test/TransactionTest.java b/mdbc-server/src/test/java/org/onap/music/mdbc/test/TransactionTest.java
new file mode 100755
index 0000000..55b0f09
--- /dev/null
+++ b/mdbc-server/src/test/java/org/onap/music/mdbc/test/TransactionTest.java
@@ -0,0 +1,183 @@
+/*
+ * ============LICENSE_START====================================================
+ * org.onap.music.mdbc
+ * =============================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * 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.mdbc.test;
+
+import static org.junit.Assert.fail;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+
+
+public class TransactionTest extends TestCommon {
+ private static final String DB_CONNECTION1 = "avatica://" + "mem:db1";
+ private static final String DB_CONNECTION2 = "avatica://" + "mem:db2";
+ private static final String KEYSPACE = "CrossSite_Test";
+ private final static Logger logger = Logger.getLogger(CrossSiteTest.class);
+
+ //@Test
+ public void testWithAutocommitTrue() {
+ System.out.println("START TransactionTest.testWithAutocommitTrue");
+ Set<String> vals = new HashSet<String>(Arrays.asList("1", "2", "3"));
+ Connection db1 = null, db2 = null;
+ try {
+ db1 = getDBConnection(DB_CONNECTION1, KEYSPACE, "0");
+ db2 = getDBConnection(DB_CONNECTION2, KEYSPACE, "1");
+ createTable(new Connection[] { db1, db2 });
+ db1.setAutoCommit(true);
+ insert(db1, vals);
+ readcheck(db2, vals);
+ } catch (Exception e) {
+ fail("Unexpected exception: "+e);
+ } finally {
+ try {
+ if (db1 != null)
+ db1.close();
+ if (db2 != null)
+ db2.close();
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ }
+ //@Test
+ public void testCommit() {
+ System.out.println("START TransactionTest.testCommit");
+ Set<String> vals = new HashSet<String>(Arrays.asList("1", "2", "3", "4"));
+ Set<String> val2 = new HashSet<String>(Arrays.asList("1", "2", "4"));
+ Connection db1 = null, db2 = null;
+ try {
+ db1 = getDBConnection(DB_CONNECTION1, KEYSPACE, "0");
+ db2 = getDBConnection(DB_CONNECTION2, KEYSPACE, "1");
+ createTable(new Connection[] { db1, db2 });
+ db1.setAutoCommit(false);
+ insert(db1, vals);
+ delete(db1, new HashSet<String>(Arrays.asList("3")));
+ readcheck(db1, val2);
+ readcheck(db2, new HashSet<String>());
+ db1.commit();
+ readcheck(db2, val2);
+ } catch (Exception e) {
+ fail("Unexpected exception: "+e);
+ } finally {
+ try {
+ if (db1 != null)
+ db1.close();
+ if (db2 != null)
+ db2.close();
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ }
+ //@Test
+ public void testRollback() {
+ System.out.println("START TransactionTest.testRollback");
+ Set<String> vals = new HashSet<String>(Arrays.asList("1", "2", "3", "4"));
+ Connection db1 = null, db2 = null;
+ try {
+ db1 = getDBConnection(DB_CONNECTION1, KEYSPACE, "0");
+ db2 = getDBConnection(DB_CONNECTION2, KEYSPACE, "1");
+ createTable(new Connection[] { db1, db2 });
+ db1.setAutoCommit(false);
+ insert(db1, vals);
+ readcheck(db1, vals);
+ readcheck(db2, new HashSet<String>());
+ db1.rollback();
+ readcheck(db1, new HashSet<String>());
+ readcheck(db2, new HashSet<String>());
+ } catch (Exception e) {
+ fail("Unexpected exception: "+e);
+ } finally {
+ try {
+ if (db1 != null)
+ db1.close();
+ if (db2 != null)
+ db2.close();
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ }
+ private void createTable(Connection[] c) {
+ try {
+ for (Connection db : c) {
+ logger.info(" start: "+db);
+ Statement s = db.createStatement();
+ s.execute("CREATE TABLE IF NOT EXISTS TRANSTEST(KEY VARCHAR(255), PRIMARY KEY (KEY))");
+ s.close();
+ logger.info(" Tables created");
+ }
+ } catch (Exception e) {
+ fail(e.toString());
+ }
+ }
+ private void insert(Connection db, Set<String> vals) {
+ // Put data in DB1
+ try {
+ Statement s = db.createStatement();
+ for (String v : vals)
+ s.execute("INSERT INTO TRANSTEST(KEY) VALUES('"+v+"')");
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ }
+ private void delete(Connection db, Set<String> vals) {
+ // Put data in DB1
+ try {
+ Statement s = db.createStatement();
+ for (String v : vals)
+ s.execute("DELETE FROM TRANSTEST WHERE KEY = '"+v+"'");
+ s.close();
+ } catch (Exception e) {
+ fail("1: " + e.toString());
+ }
+ }
+ private void readcheck(Connection db, Set<String> vals) {
+ try {
+ Statement s = db.createStatement();
+ ResultSet rs = s.executeQuery("SELECT * FROM TRANSTEST");
+ Set<String> newset = new HashSet<String>();
+ while (rs.next()) {
+ String tmp = rs.getString(1);
+ newset.add(tmp);
+ }
+ if (vals.size() != newset.size()) {
+ fail("wrong number of elements, expected "+vals.size()+" got "+newset.size());
+ }
+ for (String t : vals) {
+ if (!newset.contains(t))
+ fail("missing element: "+t);
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ e.printStackTrace();
+ fail("2: " + e.toString());
+ }
+ }
+}