3adab912e9ccab60581ee7298dc7a4f415acbcec
[music.git] / src / test / java / org / onap / music / unittests / TstRestMusicConditionalAPI.java
1 /*
2  * ============LICENSE_START========================================== org.onap.music
3  * =================================================================== Copyright (c) 2017 AT&T Intellectual Property
4  * =================================================================== Licensed under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
6  * License at
7  * 
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
11  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
12  * specific language governing permissions and limitations under the License.
13  * 
14  * ============LICENSE_END=============================================
15  * ====================================================================
16  */
17
18 package org.onap.music.unittests;
19
20 import static org.junit.Assert.assertEquals;
21 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.UUID;
27 import javax.servlet.http.HttpServletResponse;
28 import javax.ws.rs.core.MultivaluedHashMap;
29 import javax.ws.rs.core.MultivaluedMap;
30 import javax.ws.rs.core.Response;
31 import javax.ws.rs.core.UriInfo;
32 import org.junit.After;
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.junit.runner.RunWith;
38 import org.mindrot.jbcrypt.BCrypt;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.junit.MockitoJUnitRunner;
42 import org.onap.music.authentication.CachingUtil;
43 import org.onap.music.conductor.conditionals.JsonConditional;
44 import org.onap.music.conductor.conditionals.RestMusicConditionalAPI;
45 import org.onap.music.datastore.MusicDataStoreHandle;
46 import org.onap.music.datastore.PreparedQueryObject;
47 import org.onap.music.datastore.jsonobjects.JsonDelete;
48 import org.onap.music.datastore.jsonobjects.JsonInsert;
49 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
50 import org.onap.music.datastore.jsonobjects.JsonSelect;
51 import org.onap.music.datastore.jsonobjects.JsonTable;
52 import org.onap.music.datastore.jsonobjects.JsonUpdate;
53 import org.onap.music.exceptions.MusicServiceException;
54 import org.onap.music.main.MusicCore;
55 import org.onap.music.main.MusicUtil;
56 import org.onap.music.main.ResultType;
57 import org.onap.music.rest.RestMusicDataAPI;
58 import com.datastax.driver.core.DataType;
59 import com.datastax.driver.core.ResultSet;
60 import com.datastax.driver.core.Row;
61 import com.sun.jersey.core.util.Base64;
62 import com.sun.jersey.core.util.MultivaluedMapImpl;
63
64 @RunWith(MockitoJUnitRunner.class)
65 public class TstRestMusicConditionalAPI {
66
67     RestMusicDataAPI data = new RestMusicDataAPI();
68     RestMusicConditionalAPI cond = new RestMusicConditionalAPI();
69     static PreparedQueryObject testObject;
70
71     @Mock
72     HttpServletResponse http;
73
74     @Mock
75     UriInfo info;
76
77     static String appName = "TestApp";
78     static String userId = "TestUser";
79     static String password = "TestPassword";
80     static String authData = userId + ":" + password;
81     static String wrongAuthData = userId + ":" + "pass";
82     static String authorization = new String(Base64.encode(authData.getBytes()));
83     static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
84     static boolean isAAF = false;
85     static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
86     static String keyspaceName = "testcassa";
87     static String tableName = "employees";
88     static String xLatestVersion = "X-latestVersion";
89     static String onboardUUID = null;
90
91     @BeforeClass
92     public static void init() throws Exception {
93         System.out.println("Testing RestMusicConditional class");
94         try {
95             createKeyspace();
96         } catch (Exception e) {
97             e.printStackTrace();
98             throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
99         }
100     }
101
102     @After
103     public void afterEachTest() throws MusicServiceException {
104         clearAllTablesFromKeyspace();
105     }
106
107     @AfterClass
108     public static void tearDownAfterClass() throws Exception {
109         testObject = new PreparedQueryObject();
110         testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
111         MusicCore.eventualPut(testObject);
112     }
113
114     @Test
115     public void test_insertIntoTable() throws Exception {
116         System.out.println("Testing conditional insert into table");
117         createTable();
118
119         JsonConditional jsonCond = new JsonConditional();
120         Map<String, String> consistencyInfo = new HashMap<>();
121         Map<String, Object> values = new HashMap<>();
122         values.put("id", "test_id");
123         consistencyInfo.put("type", "eventual");
124         HashMap<String, Object> cascadeData = new HashMap<>();
125         HashMap<String, String> cascadeValue = new HashMap<>();
126         cascadeValue.put("created", "hello");
127         cascadeValue.put("updated", "world");
128         cascadeData.put("key", "p1");
129         cascadeData.put("value", cascadeValue);
130         HashMap<String, Map<String, String>> condition = new HashMap<>();
131         HashMap<String, String> exists = new HashMap<>();
132         exists.put("status", "parked");
133         HashMap<String, String> nonexists = new HashMap<>();
134         nonexists.put("status", "underway");
135         condition.put("exists", exists);
136         condition.put("nonexists", nonexists);
137
138         jsonCond.setPrimaryKey("id");
139         jsonCond.setPrimaryKeyValue("testname");
140         jsonCond.setCasscadeColumnName("plans");
141         jsonCond.setTableValues(values);
142         jsonCond.setCasscadeColumnData(cascadeData);
143         jsonCond.setConditions(condition);
144
145         Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
146                 authorization, keyspaceName, tableName, jsonCond);
147
148         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
149
150         assertEquals(200, response.getStatus());
151     }
152     /*
153      * @Test public void test4_insertIntoTable2() throws Exception { System.out.println("Testing insert into table #2");
154      * createTable(); JsonInsert jsonInsert = new JsonInsert(); Map<String, String> consistencyInfo = new HashMap<>();
155      * Map<String, Object> values = new HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
156      * values.put("emp_name", "test1"); values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual");
157      * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName);
158      * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1",
159      * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, tableName);
160      * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
161      * 
162      * assertEquals(200, response.getStatus()); }
163      * 
164      * // Auth Error
165      * 
166      * @Test public void test4_insertIntoTable3() throws Exception {
167      * System.out.println("Testing insert into table with bad credentials"); createTable(); JsonInsert jsonInsert = new
168      * JsonInsert(); Map<String, String> consistencyInfo = new HashMap<>(); Map<String, Object> values = new
169      * HashMap<>(); values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1");
170      * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual");
171      * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName);
172      * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1",
173      * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization, jsonInsert, keyspaceName,
174      * tableName); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
175      * 
176      * assertEquals(401, response.getStatus()); }
177      * 
178      * // Table wrong
179      * 
180      * @Test public void test4_insertIntoTable4() throws Exception {
181      * System.out.println("Testing insert into wrong table"); createTable(); JsonInsert jsonInsert = new JsonInsert();
182      * Map<String, String> consistencyInfo = new HashMap<>(); Map<String, Object> values = new HashMap<>();
183      * values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6"); values.put("emp_name", "test1");
184      * values.put("emp_salary", 1500); consistencyInfo.put("type", "eventual");
185      * jsonInsert.setConsistencyInfo(consistencyInfo); jsonInsert.setKeyspaceName(keyspaceName);
186      * jsonInsert.setTableName(tableName); jsonInsert.setValues(values); Response response = data.insertIntoTable("1",
187      * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonInsert, keyspaceName, "wrong");
188      * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
189      * 
190      * assertEquals(400, response.getStatus()); }
191      */
192
193     @Test
194     public void test5_updateTable() throws Exception {
195         System.out.println("Testing conditional update table");
196         createAndInsertIntoTable();
197
198         Map<String, String> consistencyInfo = new HashMap<>();
199         consistencyInfo.put("type", "eventual");
200
201         JsonConditional jsonCond = new JsonConditional();
202         Map<String, Object> values = new HashMap<>();
203         values.put("id", "test_id");
204         HashMap<String, Object> cascadeData = new HashMap<>();
205         HashMap<String, String> cascadeValue = new HashMap<>();
206         cascadeValue.put("created", "hello");
207         cascadeValue.put("updated", "world");
208         cascadeData.put("key", "p1");
209         cascadeData.put("value", cascadeValue);
210
211         jsonCond.setPrimaryKey("id");
212         jsonCond.setPrimaryKeyValue("test_id");
213         jsonCond.setCasscadeColumnName("plans");
214         jsonCond.setTableValues(values);
215         jsonCond.setCasscadeColumnData(cascadeData);
216
217         Response response = cond.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
218                 authorization, keyspaceName, tableName, jsonCond);
219         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
220
221         assertEquals(200, response.getStatus());
222     }
223     /*
224      * // need mock code to create error for MusicCore methods
225      * 
226      * @Test public void test5_updateTableAuthE() throws Exception { System.out.println("Testing update table #2");
227      * createTable(); //MockitoAnnotations.initMocks(this); JsonUpdate jsonUpdate = new JsonUpdate(); Map<String,
228      * String> consistencyInfo = new HashMap<>(); MultivaluedMap<String, String> row = new MultivaluedMapImpl();
229      * Map<String, Object> values = new HashMap<>(); row.add("emp_name", "testname"); values.put("emp_salary", 2500);
230      * consistencyInfo.put("type", "atomic"); jsonUpdate.setConsistencyInfo(consistencyInfo);
231      * jsonUpdate.setKeyspaceName(keyspaceName); jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values); //add
232      * ttl & timestamp //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
233      * Mockito.when(info.getQueryParameters()).thenReturn(row); //Map<String, Object> m1= new HashMap<>() ;
234      * //Mockito.when(MusicCore.autheticateUser(appName,userId,password,keyspaceName,
235      * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6","updateTable")).thenReturn(m1); Response response = data.updateTable("1",
236      * "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization, jsonUpdate, keyspaceName, tableName,
237      * info); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
238      * 
239      * assertEquals(200, response.getStatus()); }
240      * 
241      * @Ignore
242      * 
243      * @Test public void test5_updateTableAuthException1() throws Exception {
244      * System.out.println("Testing update table authentication error"); createTable(); JsonUpdate jsonUpdate = new
245      * JsonUpdate(); Map<String, String> consistencyInfo = new HashMap<>(); MultivaluedMap<String, String> row = new
246      * MultivaluedMapImpl(); Map<String, Object> values = new HashMap<>(); row.add("emp_name", "testname");
247      * values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic");
248      * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName);
249      * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values);
250      * 
251      * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax = ":"; String authorizationx = new
252      * String(Base64.encode(authDatax.getBytes())); Response response = data.updateTable("1", "1", "1",
253      * "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorizationx, jsonUpdate, keyspaceName, tableName, info);
254      * System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
255      * 
256      * assertEquals(401, response.getStatus()); }
257      * 
258      * @Ignore
259      * 
260      * @Test public void test5_updateTableAuthEmpty() throws Exception {
261      * System.out.println("Testing update table without authentication"); createTable();
262      * 
263      * JsonUpdate jsonUpdate = new JsonUpdate(); Map<String, String> consistencyInfo = new HashMap<>();
264      * MultivaluedMap<String, String> row = new MultivaluedMapImpl(); Map<String, Object> values = new HashMap<>();
265      * row.add("emp_name", "testname"); values.put("emp_salary", 2500); consistencyInfo.put("type", "atomic");
266      * jsonUpdate.setConsistencyInfo(consistencyInfo); jsonUpdate.setKeyspaceName(keyspaceName);
267      * jsonUpdate.setTableName(tableName); jsonUpdate.setValues(values);
268      * 
269      * Mockito.when(info.getQueryParameters()).thenReturn(row); String authDatax =":"+password; String authorizationx =
270      * new String(Base64.encode(authDatax.getBytes())); String appNamex="xx"; Response response = data.updateTable("1",
271      * "1", "1", "", appNamex, authorizationx, jsonUpdate, keyspaceName, tableName, info); System.out.println("Status: "
272      * + response.getStatus() + ". Entity " + response.getEntity());
273      * 
274      * assertEquals(401, response.getStatus()); }
275      * 
276      */
277
278     private static void createKeyspace() throws Exception {
279         // shouldn't really be doing this here, but create keyspace is currently turned off
280         PreparedQueryObject query = new PreparedQueryObject();
281         query.appendQueryString(CassandraCQL.createKeySpace);
282         MusicCore.eventualPut(query);
283
284         boolean isAAF = false;
285         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
286         query = new PreparedQueryObject();
287         query.appendQueryString("INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
288                 + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
289         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
290         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
291         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
292         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
293         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
294         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
295         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
296         CachingUtil.updateMusicCache(keyspaceName, appName);
297         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
298         MusicCore.eventualPut(query);
299     }
300
301     private void clearAllTablesFromKeyspace() throws MusicServiceException {
302         ArrayList<String> tableNames = new ArrayList<>();
303         PreparedQueryObject query = new PreparedQueryObject();
304         query.appendQueryString(
305                 "SELECT table_name FROM system_schema.tables WHERE keyspace_name = '" + keyspaceName + "';");
306         ResultSet rs = MusicCore.get(query);
307         for (Row row : rs) {
308             tableNames.add(row.getString("table_name"));
309         }
310         for (String table : tableNames) {
311             query = new PreparedQueryObject();
312             query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
313             MusicCore.eventualPut(query);
314         }
315     }
316
317     /**
318      * Create a table {@link tableName} in {@link keyspaceName}
319      * 
320      * @throws Exception
321      */
322     private void createTable() throws Exception {
323         JsonTable jsonTable = new JsonTable();
324         Map<String, String> consistencyInfo = new HashMap<>();
325         Map<String, String> fields = new HashMap<>();
326         fields.put("id", "text");
327         fields.put("plans", "map<text,text>");
328         fields.put("PRIMARY KEY", "(id)");
329         consistencyInfo.put("type", "eventual");
330         jsonTable.setConsistencyInfo(consistencyInfo);
331         jsonTable.setKeyspaceName(keyspaceName);
332         jsonTable.setPrimaryKey("id");
333         jsonTable.setTableName(tableName);
334         jsonTable.setFields(fields);
335         Response response = data.createTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
336                 authorization, jsonTable, keyspaceName, tableName);
337     }
338
339     /**
340      * Create table {@link createTable} and insert into said table
341      * 
342      * @throws Exception
343      */
344     private void createAndInsertIntoTable() throws Exception {
345         createTable();
346
347         Map<String, String> consistencyInfo = new HashMap<>();
348         consistencyInfo.put("type", "eventual");
349         JsonConditional jsonCond = new JsonConditional();
350         Map<String, Object> values = new HashMap<>();
351         values.put("id", "test_id");
352         HashMap<String, Object> cascadeData = new HashMap<>();
353         HashMap<String, String> cascadeValue = new HashMap<>();
354         cascadeValue.put("created", "hello");
355         cascadeValue.put("updated", "world");
356         cascadeData.put("key", "p1");
357         cascadeData.put("value", cascadeValue);
358         HashMap<String, Map<String, String>> condition = new HashMap<>();
359         HashMap<String, String> exists = new HashMap<>();
360         exists.put("status", "parked");
361         HashMap<String, String> nonexists = new HashMap<>();
362         nonexists.put("status", "underway");
363         condition.put("exists", exists);
364         condition.put("nonexists", nonexists);
365
366         jsonCond.setPrimaryKey("id");
367         jsonCond.setPrimaryKeyValue("test_id");
368         jsonCond.setCasscadeColumnName("plans");
369         jsonCond.setTableValues(values);
370         jsonCond.setCasscadeColumnData(cascadeData);
371         jsonCond.setConditions(condition);
372
373         Response response = cond.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
374                 authorization, keyspaceName, tableName, jsonCond);
375     }
376 }