2 * ============LICENSE_START========================================== org.onap.music
3 * =================================================================== Copyright (c) 2017 AT&T
4 * Intellectual Property ===================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6 * in compliance with the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software distributed under the License
11 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12 * or implied. See the License for the specific language governing permissions and limitations under
15 * ============LICENSE_END=============================================
16 * ====================================================================
19 package org.onap.music.unittests;
21 import static org.junit.Assert.assertEquals;
22 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.UUID;
28 import javax.servlet.http.HttpServletResponse;
29 import javax.ws.rs.core.MultivaluedHashMap;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriInfo;
33 import org.junit.After;
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Ignore;
37 import org.junit.Test;
38 import org.junit.runner.RunWith;
39 import org.mindrot.jbcrypt.BCrypt;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.junit.MockitoJUnitRunner;
43 import org.onap.music.authentication.CachingUtil;
44 import org.onap.music.conductor.conditionals.JsonConditional;
45 import org.onap.music.conductor.conditionals.RestMusicConditionalAPI;
46 import org.onap.music.datastore.MusicDataStoreHandle;
47 import org.onap.music.datastore.PreparedQueryObject;
48 import org.onap.music.datastore.jsonobjects.JsonDelete;
49 import org.onap.music.datastore.jsonobjects.JsonInsert;
50 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
51 import org.onap.music.datastore.jsonobjects.JsonSelect;
52 import org.onap.music.datastore.jsonobjects.JsonTable;
53 import org.onap.music.datastore.jsonobjects.JsonUpdate;
54 import org.onap.music.exceptions.MusicServiceException;
55 import org.onap.music.main.MusicCore;
56 import org.onap.music.main.MusicUtil;
57 import org.onap.music.main.ResultType;
58 import org.onap.music.rest.RestMusicDataAPI;
59 import com.datastax.driver.core.DataType;
60 import com.datastax.driver.core.ResultSet;
61 import com.datastax.driver.core.Row;
62 import com.sun.jersey.core.util.Base64;
63 import com.sun.jersey.core.util.MultivaluedMapImpl;
65 @RunWith(MockitoJUnitRunner.class)
66 public class TstRestMusicConditionalAPI {
68 RestMusicDataAPI data = new RestMusicDataAPI();
69 RestMusicConditionalAPI cond = new RestMusicConditionalAPI();
70 static PreparedQueryObject testObject;
73 HttpServletResponse http;
78 static String appName = "TestApp";
79 static String userId = "TestUser";
80 static String password = "TestPassword";
81 static String authData = userId+":"+password;
82 static String wrongAuthData = userId+":"+"pass";
83 static String authorization = new String(Base64.encode(authData.getBytes()));
84 static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
85 static boolean isAAF = false;
86 static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
87 static String keyspaceName = "testcassa";
88 static String tableName = "employees";
89 static String xLatestVersion = "X-latestVersion";
90 static String onboardUUID = null;
93 public static void init() throws Exception {
94 System.out.println("Testing RestMusicConditional class");
97 } catch (Exception e) {
99 throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
104 public void afterEachTest( ) throws MusicServiceException {
105 clearAllTablesFromKeyspace();
109 public static void tearDownAfterClass() throws Exception {
110 testObject = new PreparedQueryObject();
111 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
112 MusicCore.eventualPut(testObject);
116 public void test_insertIntoTable() throws Exception {
117 System.out.println("Testing conditional insert into table");
120 JsonConditional jsonCond = new JsonConditional();
121 Map<String, String> consistencyInfo = new HashMap<>();
122 Map<String, Object> values = new HashMap<>();
123 values.put("id", "test_id");
124 consistencyInfo.put("type", "eventual");
125 HashMap<String, Object> cascadeData = new HashMap<>();
126 HashMap<String, String> cascadeValue = new HashMap<>();
127 cascadeValue.put("created", "hello");
128 cascadeValue.put("updated", "world");
129 cascadeData.put("key", "p1");
130 cascadeData.put("value", cascadeValue);
131 HashMap<String, Map<String, String>> condition = new HashMap<>();
132 HashMap<String, String> exists = new HashMap<>();
133 exists.put("status", "parked");
134 HashMap<String, String> nonexists = new HashMap<>();
135 nonexists.put("status", "underway");
136 condition.put("exists", exists);
137 condition.put("nonexists", nonexists);
139 jsonCond.setPrimaryKey("id");
140 jsonCond.setPrimaryKeyValue("testname");
141 jsonCond.setCasscadeColumnName("plans");
142 jsonCond.setTableValues(values);
143 jsonCond.setCasscadeColumnData(cascadeData);
144 jsonCond.setConditions(condition);
146 Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
147 appName, authorization, keyspaceName, tableName, jsonCond);
149 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
151 assertEquals(200, response.getStatus());
155 public void test4_insertIntoTable2() throws Exception {
156 System.out.println("Testing insert into table #2");
158 JsonInsert jsonInsert = new JsonInsert();
159 Map<String, String> consistencyInfo = new HashMap<>();
160 Map<String, Object> values = new HashMap<>();
161 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
162 values.put("emp_name", "test1");
163 values.put("emp_salary", 1500);
164 consistencyInfo.put("type", "eventual");
165 jsonInsert.setConsistencyInfo(consistencyInfo);
166 jsonInsert.setKeyspaceName(keyspaceName);
167 jsonInsert.setTableName(tableName);
168 jsonInsert.setValues(values);
169 Response response = data.insertIntoTable("1", "1", "1",
170 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
171 jsonInsert, keyspaceName, tableName);
172 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
174 assertEquals(200, response.getStatus());
179 public void test4_insertIntoTable3() throws Exception {
180 System.out.println("Testing insert into table with bad credentials");
182 JsonInsert jsonInsert = new JsonInsert();
183 Map<String, String> consistencyInfo = new HashMap<>();
184 Map<String, Object> values = new HashMap<>();
185 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
186 values.put("emp_name", "test1");
187 values.put("emp_salary", 1500);
188 consistencyInfo.put("type", "eventual");
189 jsonInsert.setConsistencyInfo(consistencyInfo);
190 jsonInsert.setKeyspaceName(keyspaceName);
191 jsonInsert.setTableName(tableName);
192 jsonInsert.setValues(values);
193 Response response = data.insertIntoTable("1", "1", "1",
194 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization,
195 jsonInsert, keyspaceName, tableName);
196 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
198 assertEquals(401, response.getStatus());
203 public void test4_insertIntoTable4() throws Exception {
204 System.out.println("Testing insert into wrong table");
206 JsonInsert jsonInsert = new JsonInsert();
207 Map<String, String> consistencyInfo = new HashMap<>();
208 Map<String, Object> values = new HashMap<>();
209 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
210 values.put("emp_name", "test1");
211 values.put("emp_salary", 1500);
212 consistencyInfo.put("type", "eventual");
213 jsonInsert.setConsistencyInfo(consistencyInfo);
214 jsonInsert.setKeyspaceName(keyspaceName);
215 jsonInsert.setTableName(tableName);
216 jsonInsert.setValues(values);
217 Response response = data.insertIntoTable("1", "1", "1",
218 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
219 jsonInsert, keyspaceName, "wrong");
220 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
222 assertEquals(400, response.getStatus());
227 public void test5_updateTable() throws Exception {
228 System.out.println("Testing conditional update table");
229 createAndInsertIntoTable();
231 Map<String, String> consistencyInfo = new HashMap<>();
232 consistencyInfo.put("type", "eventual");
234 JsonConditional jsonCond = new JsonConditional();
235 Map<String, Object> values = new HashMap<>();
236 values.put("id", "test_id");
237 HashMap<String, Object> cascadeData = new HashMap<>();
238 HashMap<String, String> cascadeValue = new HashMap<>();
239 cascadeValue.put("created", "hello");
240 cascadeValue.put("updated", "world");
241 cascadeData.put("key", "p1");
242 cascadeData.put("value", cascadeValue);
244 jsonCond.setPrimaryKey("id");
245 jsonCond.setPrimaryKeyValue("test_id");
246 jsonCond.setCasscadeColumnName("plans");
247 jsonCond.setTableValues(values);
248 jsonCond.setCasscadeColumnData(cascadeData);
250 Response response = cond.updateConditional("1", "1", "1",
251 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
252 keyspaceName, tableName, jsonCond);
253 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
255 assertEquals(200, response.getStatus());
258 // need mock code to create error for MusicCore methods
260 public void test5_updateTableAuthE() throws Exception {
261 System.out.println("Testing update table #2");
263 //MockitoAnnotations.initMocks(this);
264 JsonUpdate jsonUpdate = new JsonUpdate();
265 Map<String, String> consistencyInfo = new HashMap<>();
266 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
267 Map<String, Object> values = new HashMap<>();
268 row.add("emp_name", "testname");
269 values.put("emp_salary", 2500);
270 consistencyInfo.put("type", "atomic");
271 jsonUpdate.setConsistencyInfo(consistencyInfo);
272 jsonUpdate.setKeyspaceName(keyspaceName);
273 jsonUpdate.setTableName(tableName);
274 jsonUpdate.setValues(values);
275 //add ttl & timestamp
276 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
277 Mockito.when(info.getQueryParameters()).thenReturn(row);
278 //Map<String, Object> m1= new HashMap<>() ;
279 //Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1);
280 Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
281 authorization, jsonUpdate, keyspaceName, tableName, info);
282 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
284 assertEquals(200, response.getStatus());
289 public void test5_updateTableAuthException1() throws Exception {
290 System.out.println("Testing update table authentication error");
292 JsonUpdate jsonUpdate = new JsonUpdate();
293 Map<String, String> consistencyInfo = new HashMap<>();
294 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
295 Map<String, Object> values = new HashMap<>();
296 row.add("emp_name", "testname");
297 values.put("emp_salary", 2500);
298 consistencyInfo.put("type", "atomic");
299 jsonUpdate.setConsistencyInfo(consistencyInfo);
300 jsonUpdate.setKeyspaceName(keyspaceName);
301 jsonUpdate.setTableName(tableName);
302 jsonUpdate.setValues(values);
304 Mockito.when(info.getQueryParameters()).thenReturn(row);
305 String authDatax = ":";
306 String authorizationx = new String(Base64.encode(authDatax.getBytes()));
307 Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
308 authorizationx, jsonUpdate, keyspaceName, tableName, info);
309 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
311 assertEquals(401, response.getStatus());
316 public void test5_updateTableAuthEmpty() throws Exception {
317 System.out.println("Testing update table without authentication");
320 JsonUpdate jsonUpdate = new JsonUpdate();
321 Map<String, String> consistencyInfo = new HashMap<>();
322 MultivaluedMap<String, String> row = new MultivaluedMapImpl();
323 Map<String, Object> values = new HashMap<>();
324 row.add("emp_name", "testname");
325 values.put("emp_salary", 2500);
326 consistencyInfo.put("type", "atomic");
327 jsonUpdate.setConsistencyInfo(consistencyInfo);
328 jsonUpdate.setKeyspaceName(keyspaceName);
329 jsonUpdate.setTableName(tableName);
330 jsonUpdate.setValues(values);
332 Mockito.when(info.getQueryParameters()).thenReturn(row);
333 String authDatax =":"+password;
334 String authorizationx = new String(Base64.encode(authDatax.getBytes()));
335 String appNamex="xx";
336 Response response = data.updateTable("1", "1", "1", "", appNamex,
337 authorizationx, jsonUpdate, keyspaceName, tableName, info);
338 System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
340 assertEquals(401, response.getStatus());
345 private static void createAdminTable() throws Exception {
346 testObject = new PreparedQueryObject();
347 testObject.appendQueryString(CassandraCQL.createAdminKeyspace);
348 MusicCore.eventualPut(testObject);
349 testObject = new PreparedQueryObject();
350 testObject.appendQueryString(CassandraCQL.createAdminTable);
351 MusicCore.eventualPut(testObject);
353 testObject = new PreparedQueryObject();
354 testObject.appendQueryString(
355 "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
356 + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
357 testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
358 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
359 MusicUtil.DEFAULTKEYSPACENAME));
360 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
361 testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
362 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
363 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
364 testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
365 MusicCore.eventualPut(testObject);
367 testObject = new PreparedQueryObject();
368 testObject.appendQueryString(
369 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
370 testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
371 ResultSet rs = MusicCore.get(testObject);
372 List<Row> rows = rs.all();
373 if (rows.size() > 0) {
374 System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid"));
379 private static void createKeyspace() throws Exception {
380 //shouldn't really be doing this here, but create keyspace is currently turned off
381 PreparedQueryObject query = new PreparedQueryObject();
382 query.appendQueryString(CassandraCQL.createKeySpace);
383 MusicCore.eventualPut(query);
385 boolean isAAF = false;
386 String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
387 query = new PreparedQueryObject();
388 query.appendQueryString(
389 "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
390 + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
391 query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
392 query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
393 query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
394 query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
395 query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
396 query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
397 query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
398 CachingUtil.updateMusicCache(keyspaceName, appName);
399 CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
400 MusicCore.eventualPut(query);
403 private void clearAllTablesFromKeyspace() throws MusicServiceException {
404 ArrayList<String> tableNames = new ArrayList<>();
405 PreparedQueryObject query = new PreparedQueryObject();
406 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
407 ResultSet rs = MusicCore.get(query);
409 tableNames.add(row.getString("table_name"));
411 for (String table: tableNames) {
412 query = new PreparedQueryObject();
413 query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
414 MusicCore.eventualPut(query);
419 * Create a table {@link tableName} in {@link keyspaceName}
422 private void createTable() throws Exception {
423 JsonTable jsonTable = new JsonTable();
424 Map<String, String> consistencyInfo = new HashMap<>();
425 Map<String, String> fields = new HashMap<>();
426 fields.put("id", "text");
427 fields.put("plans", "map<text,text>");
428 fields.put("PRIMARY KEY", "(id)");
429 consistencyInfo.put("type", "eventual");
430 jsonTable.setConsistencyInfo(consistencyInfo);
431 jsonTable.setKeyspaceName(keyspaceName);
432 jsonTable.setPrimaryKey("id");
433 jsonTable.setTableName(tableName);
434 jsonTable.setFields(fields);
435 Response response = data.createTable("1", "1", "1",
436 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization,
437 jsonTable, keyspaceName, tableName);
441 * Create table {@link createTable} and insert into said table
444 private void createAndInsertIntoTable() throws Exception {
447 Map<String, String> consistencyInfo = new HashMap<>();
448 consistencyInfo.put("type", "eventual");
449 JsonConditional jsonCond = new JsonConditional();
450 Map<String, Object> values = new HashMap<>();
451 values.put("id", "test_id");
452 HashMap<String, Object> cascadeData = new HashMap<>();
453 HashMap<String, String> cascadeValue = new HashMap<>();
454 cascadeValue.put("created", "hello");
455 cascadeValue.put("updated", "world");
456 cascadeData.put("key", "p1");
457 cascadeData.put("value", cascadeValue);
458 HashMap<String, Map<String, String>> condition = new HashMap<>();
459 HashMap<String, String> exists = new HashMap<>();
460 exists.put("status", "parked");
461 HashMap<String, String> nonexists = new HashMap<>();
462 nonexists.put("status", "underway");
463 condition.put("exists", exists);
464 condition.put("nonexists", nonexists);
466 jsonCond.setPrimaryKey("id");
467 jsonCond.setPrimaryKeyValue("test_id");
468 jsonCond.setCasscadeColumnName("plans");
469 jsonCond.setTableValues(values);
470 jsonCond.setCasscadeColumnData(cascadeData);
471 jsonCond.setConditions(condition);
473 Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
474 appName, authorization, keyspaceName, tableName, jsonCond);