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