Merge "MusicLockingExceptionTest - Junit test cases"
[music.git] / src / test / java / org / onap / music / unittests / CassandraCQL.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22
23 package org.onap.music.unittests;
24
25 /**
26  * @author srupane
27  * 
28  */
29
30 import java.io.IOException;
31 import java.math.BigInteger;
32 import java.net.InetAddress;
33 import java.net.NetworkInterface;
34 import java.net.SocketException;
35 import java.util.ArrayList;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.UUID;
42
43 //import org.apache.thrift.transport.TTransportException;
44 import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
45 import org.onap.music.datastore.MusicDataStore;
46 import org.onap.music.datastore.PreparedQueryObject;
47
48 import com.datastax.driver.core.Cluster;
49 import com.datastax.driver.core.Session;
50 import com.datastax.driver.core.exceptions.NoHostAvailableException;
51
52 public class CassandraCQL {
53
54     public static final String createKeySpace =
55                     "CREATE KEYSPACE IF NOT EXISTS testCassa WITH replication = "
56                     +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;";
57
58     public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testCassa";
59
60     public static final String createTableEmployees =
61                     "CREATE TABLE IF NOT EXISTS testCassa.employees "
62                     + "(vector_ts text,empId uuid,empName text,empSalary varint,address Map<text,text>,PRIMARY KEY (empName)) "
63                     + "WITH comment='Financial Info of employees' "
64                     + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} "
65                     + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};";
66
67     public static final String insertIntoTablePrepared1 =
68                     "INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary) VALUES (?,?,?,?); ";
69
70     public static final String insertIntoTablePrepared2 =
71                     "INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary,address) VALUES (?,?,?,?,?);";
72
73     public static final String selectALL = "SELECT *  FROM testCassa.employees;";
74
75     public static final String selectSpecific =
76                     "SELECT *  FROM testCassa.employees WHERE empName= ?;";
77
78     public static final String updatePreparedQuery =
79                     "UPDATE testCassa.employees  SET vector_ts=?,address= ? WHERE empName= ?;";
80
81     public static final String deleteFromTable = " ";
82
83     public static final String deleteFromTablePrepared = " ";
84
85     // Set Values for Prepared Query
86
87     public static List<Object> setPreparedInsertValues1() {
88
89         List<Object> preppreparedInsertValues1 = new ArrayList<>();
90         String vectorTs =
91                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
92         UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6");
93         BigInteger empSalary = BigInteger.valueOf(23443);
94         String empName = "Mr Test one";
95         preppreparedInsertValues1.add(vectorTs);
96         preppreparedInsertValues1.add(empId);
97         preppreparedInsertValues1.add(empName);
98         preppreparedInsertValues1.add(empSalary);
99         return preppreparedInsertValues1;
100     }
101
102     public static List<Object> setPreparedInsertValues2() {
103
104         List<Object> preparedInsertValues2 = new ArrayList<>();
105         String vectorTs =
106                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
107         UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6");
108         BigInteger empSalary = BigInteger.valueOf(45655);
109         String empName = "Mr Test two";
110         Map<String, String> address = new HashMap<>();
111         preparedInsertValues2.add(vectorTs);
112         preparedInsertValues2.add(empId);
113         preparedInsertValues2.add(empName);
114         preparedInsertValues2.add(empSalary);
115         address.put("Street", "1 some way");
116         address.put("City", "Some town");
117         preparedInsertValues2.add(address);
118         return preparedInsertValues2;
119     }
120
121     public static List<Object> setPreparedUpdateValues() {
122
123         List<Object> preparedUpdateValues = new ArrayList<>();
124         String vectorTs =
125                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
126         Map<String, String> address = new HashMap<>();
127         preparedUpdateValues.add(vectorTs);
128         String empName = "Mr Test one";
129         address.put("Street", "101 Some Way");
130         address.put("City", "New York");
131         preparedUpdateValues.add(address);
132         preparedUpdateValues.add(empName);
133         return preparedUpdateValues;
134     }
135
136     // Generate Different Prepared Query Objects
137     /**
138      * Query Object for Get.
139      * 
140      * @return
141      */
142     public static PreparedQueryObject setPreparedGetQuery() {
143
144         PreparedQueryObject queryObject = new PreparedQueryObject();
145         String empName1 = "Mr Test one";
146         queryObject.appendQueryString(selectSpecific);
147         queryObject.addValue(empName1);
148         return queryObject;
149     }
150
151     /**
152      * Query Object 1 for Insert.
153      * 
154      * @return {@link PreparedQueryObject}
155      */
156     public static PreparedQueryObject setPreparedInsertQueryObject1() {
157
158         PreparedQueryObject queryobject = new PreparedQueryObject();
159         queryobject.appendQueryString(insertIntoTablePrepared1);
160         List<Object> values = setPreparedInsertValues1();
161         if (!values.isEmpty() || values != null) {
162             for (Object o : values) {
163                 queryobject.addValue(o);
164             }
165         }
166         return queryobject;
167
168     }
169
170     /**
171      * Query Object 2 for Insert.
172      * 
173      * @return {@link PreparedQueryObject}
174      */
175     public static PreparedQueryObject setPreparedInsertQueryObject2() {
176
177         PreparedQueryObject queryobject = new PreparedQueryObject();
178         queryobject.appendQueryString(insertIntoTablePrepared2);
179         List<Object> values = setPreparedInsertValues2();
180         if (!values.isEmpty() || values != null) {
181             for (Object o : values) {
182                 queryobject.addValue(o);
183             }
184         }
185         return queryobject;
186
187     }
188
189     /**
190      * Query Object for Update.
191      * 
192      * @return {@link PreparedQueryObject}
193      */
194     public static PreparedQueryObject setPreparedUpdateQueryObject() {
195
196         PreparedQueryObject queryobject = new PreparedQueryObject();
197         queryobject.appendQueryString(updatePreparedQuery);
198         List<Object> values = setPreparedUpdateValues();
199         if (!values.isEmpty() || values != null) {
200             for (Object o : values) {
201                 queryobject.addValue(o);
202             }
203         }
204         return queryobject;
205
206     }
207
208     private static ArrayList<String> getAllPossibleLocalIps() {
209         ArrayList<String> allPossibleIps = new ArrayList<String>();
210         try {
211             Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
212             while (en.hasMoreElements()) {
213                 NetworkInterface ni = (NetworkInterface) en.nextElement();
214                 Enumeration<InetAddress> ee = ni.getInetAddresses();
215                 while (ee.hasMoreElements()) {
216                     InetAddress ia = (InetAddress) ee.nextElement();
217                     allPossibleIps.add(ia.getHostAddress());
218                 }
219             }
220         } catch (SocketException e) {
221             System.out.println(e.getMessage());
222         }
223         return allPossibleIps;
224     }
225
226     public static MusicDataStore connectToEmbeddedCassandra() {
227         Iterator<String> it = getAllPossibleLocalIps().iterator();
228         String address = "localhost";
229
230         Cluster cluster = null;
231         Session session = null;
232         while (it.hasNext()) {
233             try {
234
235                 try {
236                      EmbeddedCassandraServerHelper.startEmbeddedCassandra();
237                 } catch (Exception e) {
238                          e.printStackTrace();
239                 }
240                 cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build();
241                 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000);
242                 session = cluster.connect();
243
244                 break;
245             } catch (NoHostAvailableException e) {
246                 address = it.next();
247                 System.out.println(e.getMessage());
248
249             }
250         }
251         return new MusicDataStore(cluster, session);
252
253     }
254
255 }