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