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