Merge "Add INFO.yaml file"
[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 import com.datastax.driver.core.Cluster;
43 import com.datastax.driver.core.Session;
44 import com.datastax.driver.core.exceptions.NoHostAvailableException;
45 import org.apache.cassandra.exceptions.ConfigurationException;
46 import org.apache.thrift.transport.TTransportException;
47 import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
48 import org.onap.music.datastore.MusicDataStore;
49 import org.onap.music.datastore.PreparedQueryObject;
50
51 public class CassandraCQL {
52
53     public static final String createKeySpace =
54                     "CREATE KEYSPACE IF NOT EXISTS testCassa WITH replication = "
55                     +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;";
56
57     public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testCassa";
58
59     public static final String createTableEmployees =
60                     "CREATE TABLE IF NOT EXISTS testCassa.employees "
61                     + "(vector_ts text,empId uuid,empName text,empSalary varint,address Map<text,text>,PRIMARY KEY (empName)) "
62                     + "WITH comment='Financial Info of employees' "
63                     + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} "
64                     + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};";
65
66     public static final String insertIntoTablePrepared1 =
67                     "INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary) VALUES (?,?,?,?); ";
68
69     public static final String insertIntoTablePrepared2 =
70                     "INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary,address) VALUES (?,?,?,?,?);";
71
72     public static final String selectALL = "SELECT *  FROM testCassa.employees;";
73
74     public static final String selectSpecific =
75                     "SELECT *  FROM testCassa.employees WHERE empName= ?;";
76
77     public static final String updatePreparedQuery =
78                     "UPDATE testCassa.employees  SET vector_ts=?,address= ? WHERE empName= ?;";
79
80     public static final String deleteFromTable = " ";
81
82     public static final String deleteFromTablePrepared = " ";
83
84     // Set Values for Prepared Query
85
86     public static List<Object> setPreparedInsertValues1() {
87
88         List<Object> preppreparedInsertValues1 = new ArrayList<>();
89         String vectorTs =
90                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
91         UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6");
92         BigInteger empSalary = BigInteger.valueOf(23443);
93         String empName = "Mr Test one";
94         preppreparedInsertValues1.add(vectorTs);
95         preppreparedInsertValues1.add(empId);
96         preppreparedInsertValues1.add(empName);
97         preppreparedInsertValues1.add(empSalary);
98         return preppreparedInsertValues1;
99     }
100
101     public static List<Object> setPreparedInsertValues2() {
102
103         List<Object> preparedInsertValues2 = new ArrayList<>();
104         String vectorTs =
105                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
106         UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6");
107         BigInteger empSalary = BigInteger.valueOf(45655);
108         String empName = "Mr Test two";
109         Map<String, String> address = new HashMap<>();
110         preparedInsertValues2.add(vectorTs);
111         preparedInsertValues2.add(empId);
112         preparedInsertValues2.add(empName);
113         preparedInsertValues2.add(empSalary);
114         address.put("Street", "1 some way");
115         address.put("City", "Some town");
116         preparedInsertValues2.add(address);
117         return preparedInsertValues2;
118     }
119
120     public static List<Object> setPreparedUpdateValues() {
121
122         List<Object> preparedUpdateValues = new ArrayList<>();
123         String vectorTs =
124                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
125         Map<String, String> address = new HashMap<>();
126         preparedUpdateValues.add(vectorTs);
127         String empName = "Mr Test one";
128         address.put("Street", "101 Some Way");
129         address.put("City", "New York");
130         preparedUpdateValues.add(address);
131         preparedUpdateValues.add(empName);
132         return preparedUpdateValues;
133     }
134
135     // Generate Different Prepared Query Objects
136     /**
137      * Query Object for Get.
138      * 
139      * @return
140      */
141     public static PreparedQueryObject setPreparedGetQuery() {
142
143         PreparedQueryObject queryObject = new PreparedQueryObject();
144         String empName1 = "Mr Test one";
145         queryObject.appendQueryString(selectSpecific);
146         queryObject.addValue(empName1);
147         return queryObject;
148     }
149
150     /**
151      * Query Object 1 for Insert.
152      * 
153      * @return {@link PreparedQueryObject}
154      */
155     public static PreparedQueryObject setPreparedInsertQueryObject1() {
156
157         PreparedQueryObject queryobject = new PreparedQueryObject();
158         queryobject.appendQueryString(insertIntoTablePrepared1);
159         List<Object> values = setPreparedInsertValues1();
160         if (!values.isEmpty() || values != null) {
161             for (Object o : values) {
162                 queryobject.addValue(o);
163             }
164         }
165         return queryobject;
166
167     }
168
169     /**
170      * Query Object 2 for Insert.
171      * 
172      * @return {@link PreparedQueryObject}
173      */
174     public static PreparedQueryObject setPreparedInsertQueryObject2() {
175
176         PreparedQueryObject queryobject = new PreparedQueryObject();
177         queryobject.appendQueryString(insertIntoTablePrepared2);
178         List<Object> values = setPreparedInsertValues2();
179         if (!values.isEmpty() || values != null) {
180             for (Object o : values) {
181                 queryobject.addValue(o);
182             }
183         }
184         return queryobject;
185
186     }
187
188     /**
189      * Query Object for Update.
190      * 
191      * @return {@link PreparedQueryObject}
192      */
193     public static PreparedQueryObject setPreparedUpdateQueryObject() {
194
195         PreparedQueryObject queryobject = new PreparedQueryObject();
196         queryobject.appendQueryString(updatePreparedQuery);
197         List<Object> values = setPreparedUpdateValues();
198         if (!values.isEmpty() || values != null) {
199             for (Object o : values) {
200                 queryobject.addValue(o);
201             }
202         }
203         return queryobject;
204
205     }
206
207     private static ArrayList<String> getAllPossibleLocalIps() {
208         ArrayList<String> allPossibleIps = new ArrayList<String>();
209         try {
210             Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
211             while (en.hasMoreElements()) {
212                 NetworkInterface ni = (NetworkInterface) en.nextElement();
213                 Enumeration<InetAddress> ee = ni.getInetAddresses();
214                 while (ee.hasMoreElements()) {
215                     InetAddress ia = (InetAddress) ee.nextElement();
216                     allPossibleIps.add(ia.getHostAddress());
217                 }
218             }
219         } catch (SocketException e) {
220             System.out.println(e.getMessage());
221         }
222         return allPossibleIps;
223     }
224
225     public static MusicDataStore connectToEmbeddedCassandra() {
226         Iterator<String> it = getAllPossibleLocalIps().iterator();
227         String address = "localhost";
228
229         Cluster cluster = null;
230         Session session = null;
231         while (it.hasNext()) {
232             try {
233
234                 try {
235                     EmbeddedCassandraServerHelper.startEmbeddedCassandra(80000);
236                 } catch (ConfigurationException | TTransportException | IOException e) {
237
238                     System.out.println(e.getMessage());
239                 }
240
241                 cluster = new Cluster.Builder().addContactPoint(address).withPort(9142).build();
242                 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(20000);
243                 session = cluster.connect();
244
245                 break;
246             } catch (NoHostAvailableException e) {
247                 address = it.next();
248                 System.out.println(e.getMessage());
249
250             }
251         }
252         return new MusicDataStore(cluster, session);
253
254     }
255
256 }