92c5d8183907a9ef717d02722d1d0d33d1e86d64
[music.git] / src / test / java / org / onap / music / unittests / TstRestMusicLockAPI.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 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.UUID;
32
33 import javax.ws.rs.core.Response;
34
35 import org.junit.After;
36 import org.junit.AfterClass;
37 import org.junit.BeforeClass;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.junit.runner.RunWith;
41 import org.mindrot.jbcrypt.BCrypt;
42 import org.mockito.junit.MockitoJUnitRunner;
43 import org.onap.music.authentication.CachingUtil;
44 import org.onap.music.datastore.MusicDataStoreHandle;
45 import org.onap.music.datastore.PreparedQueryObject;
46 import org.onap.music.datastore.jsonobjects.JsonInsert;
47 import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
48 import org.onap.music.datastore.jsonobjects.JsonTable;
49 import org.onap.music.exceptions.MusicServiceException;
50 import org.onap.music.lockingservice.cassandra.CassaLockStore;
51 import org.onap.music.main.MusicCore;
52 import org.onap.music.main.MusicUtil;
53 import org.onap.music.rest.RestMusicDataAPI;
54 import org.onap.music.rest.RestMusicLocksAPI;
55 import com.datastax.driver.core.DataType;
56 import com.datastax.driver.core.ResultSet;
57 import com.datastax.driver.core.Row;
58 import com.sun.jersey.core.util.Base64;
59
60 @RunWith(MockitoJUnitRunner.class)
61 public class TstRestMusicLockAPI {
62
63         RestMusicLocksAPI lock = new RestMusicLocksAPI();
64         RestMusicDataAPI data = new RestMusicDataAPI();
65         static PreparedQueryObject testObject;
66
67         static String appName = "TestApp";
68         static String userId = "TestUser";
69         static String password = "TestPassword";
70         static String authData = userId+":"+password;
71         static String wrongAuthData = userId+":"+"pass";
72         static String authorization = new String(Base64.encode(authData.getBytes()));
73         static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
74         static boolean isAAF = false;
75         static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
76         static String keyspaceName = "testcassa";
77         static String tableName = "employees";
78         static String onboardUUID = null;
79         static String lockName = "testcassa.employees.testname";
80         static String malformedLock = "malformedLock";
81
82         @BeforeClass
83         public static void init() throws Exception {
84                 System.out.println("Testing RestMusicLock class");
85                 try {
86                         createKeyspace();
87                 } catch (Exception e) {
88                         e.printStackTrace();
89                         throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
90                 }
91         }
92         
93         @After
94         public void afterEachTest( ) throws MusicServiceException {
95                 clearAllTablesFromKeyspace();
96         }
97
98         @AfterClass
99         public static void tearDownAfterClass() throws Exception {
100                 testObject = new PreparedQueryObject();
101                 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
102                 MusicCore.eventualPut(testObject);
103         }
104
105     @SuppressWarnings("unchecked")
106         @Test
107     public void test_createLockReference() throws Exception {
108         System.out.println("Testing create lockref");
109         createAndInsertIntoTable();
110         Response response =lock.createLockReference(lockName,"1","1",authorization,
111                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
112                 Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
113         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
114
115         assertEquals(200, response.getStatus());
116         assertTrue(respMap.containsKey("lock"));
117         assertTrue(((Map<String,String>) respMap.get("lock")).containsKey("lock"));
118     }
119     
120     @Test
121     public void test_createLockReference_wrongAuth() throws Exception {
122         System.out.println("Testing create lockref with wrong auth");
123         createAndInsertIntoTable();
124         Response response =lock.createLockReference(lockName,"1","1", wrongAuthorization,
125                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
126         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
127
128         assertEquals(401, response.getStatus());
129     }
130     
131     @Test
132     public void test_createLockReference_malformedLockName() throws Exception {
133         System.out.println("Testing create lockref w/ malformed lock");
134         createAndInsertIntoTable();
135         Response response =lock.createLockReference(malformedLock,"1","1",authorization,
136                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
137         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
138
139         assertEquals(400, response.getStatus());
140     }
141
142     @Test
143     public void test_accquireLock() throws Exception {
144         System.out.println("Testing acquire lock");
145                 createAndInsertIntoTable();
146         String lockRef = createLockReference();
147
148         Response response = lock.accquireLock(lockRef, "1", "1", authorization,
149                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
150         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
151         assertEquals(200, response.getStatus());
152     }
153     
154     @Test
155     public void test_accquireLock_wrongAuth() throws Exception {
156         System.out.println("Testing acquire lock w/ wrong auth");
157         createAndInsertIntoTable();
158         String lockRef = createLockReference();
159
160         Response response = lock.accquireLock(lockRef, "1", "1", wrongAuthorization,
161                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
162         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
163         assertEquals(401, response.getStatus());
164     }
165     
166     @Test
167     public void test_accquireBadLock() throws Exception {
168         System.out.println("Testing acquire lock that is not lock-holder");
169         createAndInsertIntoTable();
170
171         String lockRef1 = createLockReference();
172         String lockRef2 = createLockReference();
173
174
175         Response response = lock.accquireLock(lockRef2, "1", "1", authorization,
176                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
177         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
178         assertEquals(400, response.getStatus());
179     }
180     
181     @Test
182     public void test_accquireLock_malformedLock() throws Exception {
183         System.out.println("Testing acquire lock w/ malformedLock");
184         createAndInsertIntoTable();
185
186         Response response = lock.accquireLock(malformedLock, "1", "1", wrongAuthorization,
187                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
188         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
189         assertEquals(400, response.getStatus());
190     }
191     
192     @Test
193     public void test_accquireLockWLease() throws Exception {
194         System.out.println("Testing acquire lock with lease");
195         createAndInsertIntoTable();
196         String lockRef = createLockReference();
197
198         JsonLeasedLock jsonLock = new JsonLeasedLock();
199         jsonLock.setLeasePeriod(10000); //10 second lease period?
200         Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", authorization,
201                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
202         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
203         assertEquals(200, response.getStatus());
204     }
205     
206     @Test
207     public void test_accquireLockWLease_wrongAuth() throws Exception {
208         System.out.println("Testing acquire lock with lease w/ wrong Auth");
209         createAndInsertIntoTable();
210         String lockRef = createLockReference();
211
212         JsonLeasedLock jsonLock = new JsonLeasedLock();
213         jsonLock.setLeasePeriod(10000); //10 second lease period?
214         Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", wrongAuthorization,
215                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
216         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
217         assertEquals(401, response.getStatus());
218     }
219     
220     @Test
221     public void test_accquireLockWLease_malformedLock() throws Exception {
222         System.out.println("Testing acquire lock with lease w/ malformed lock");
223         createAndInsertIntoTable();
224         String lockRef = createLockReference();
225
226         JsonLeasedLock jsonLock = new JsonLeasedLock();
227         jsonLock.setLeasePeriod(10000); //10 second lease period?
228         Response response = lock.accquireLockWithLease(jsonLock, malformedLock, "1", "1",
229                 wrongAuthorization, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
230         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
231         assertEquals(400, response.getStatus());
232     }
233     
234     @Test
235     public void test_currentLockHolder() throws Exception {
236         System.out.println("Testing get current lock holder");
237                 createAndInsertIntoTable();
238
239         String lockRef = createLockReference();
240
241         Response response = lock.currentLockHolder(lockName, "1", "1", authorization,
242                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
243         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
244         assertEquals(200, response.getStatus());
245         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
246         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
247     }
248     
249     @Test
250     public void test_currentLockHolder_wrongAuth() throws Exception {
251         System.out.println("Testing get current lock holder w/ wrong Auth");
252         createAndInsertIntoTable();
253
254         String lockRef = createLockReference();
255
256         Response response = lock.currentLockHolder(lockName, "1", "1", wrongAuthorization,
257                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
258         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
259         assertEquals(401, response.getStatus());
260     }
261     
262     @Test
263     public void test_currentLockHolder_malformedLock() throws Exception {
264         System.out.println("Testing get current lock holder w/ malformed lock");
265         createAndInsertIntoTable();
266
267         String lockRef = createLockReference();
268
269         Response response = lock.currentLockHolder(malformedLock, "1", "1", wrongAuthorization,
270                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
271         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
272         assertEquals(400, response.getStatus());
273     }
274     
275     @Test
276     public void test_unLock() throws Exception {
277         System.out.println("Testing unlock");
278                 createAndInsertIntoTable();
279         String lockRef = createLockReference();
280
281         Response response = lock.unLock(lockRef, "1", "1", authorization,
282                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
283         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
284         assertEquals(200, response.getStatus());
285     }
286     
287     @Test
288     public void test_unLock_wrongAuth() throws Exception {
289         System.out.println("Testing unlock w/ wrong auth");
290         createAndInsertIntoTable();
291         String lockRef = createLockReference();
292
293         Response response = lock.unLock(lockRef, "1", "1", wrongAuthorization,
294                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
295         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
296         assertEquals(401, response.getStatus());
297     }
298     
299     @Test
300     public void test_unLock_malformedLock() throws Exception {
301         System.out.println("Testing unlock w/ malformedLock");
302         createAndInsertIntoTable();
303         String lockRef = createLockReference();
304
305         Response response = lock.unLock("malformedLock", "1", "1", wrongAuthorization,
306                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
307         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
308         assertEquals(400, response.getStatus());
309     }
310     
311     @Test
312     public void test_getLockState() throws Exception {
313         System.out.println("Testing get lock state");
314         createAndInsertIntoTable();
315
316         String lockRef = createLockReference();
317
318         Response response = lock.currentLockState(lockName, "1", "1", authorization,
319                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
320         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
321         assertEquals(200, response.getStatus());
322         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
323         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
324     }
325     
326     @Test
327     public void test_getLockState_wrongAuth() throws Exception {
328         System.out.println("Testing get lock state w/ wrong auth");
329         createAndInsertIntoTable();
330
331         String lockRef = createLockReference();
332
333         Response response = lock.currentLockState(lockName, "1", "1", wrongAuthorization,
334                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
335         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
336         assertEquals(401, response.getStatus());
337     }
338     
339     @Test
340     public void test_getLockState_malformedLock() throws Exception {
341         System.out.println("Testing get lock state w/ malformedLock");
342         createAndInsertIntoTable();
343
344         String lockRef = createLockReference();
345
346         Response response = lock.currentLockState(malformedLock, "1", "1", wrongAuthorization,
347                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
348         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
349         assertEquals(400, response.getStatus());
350     }
351     
352     @Test
353     public void test_deleteLock() throws Exception {
354         System.out.println("Testing delete lock");
355         createAndInsertIntoTable();
356
357         String lockRef = createLockReference();
358
359         Response response = lock.deleteLock(lockName, "1", "1",
360                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, appName);
361         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
362         assertEquals(200, response.getStatus());
363     }
364     
365     @Test
366     public void test_deleteLock_wrongAuth() throws Exception {
367         System.out.println("Testing delete lock w/ wrong auth");
368         createAndInsertIntoTable();
369
370         String lockRef = createLockReference();
371
372         Response response = lock.deleteLock(lockName, "1", "1",
373                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", wrongAuthorization, appName);
374         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
375         assertEquals(401, response.getStatus());
376     }
377     
378     @Test
379     public void test_deleteLock_malformedLock() throws Exception {
380         System.out.println("Testing delete lock w/ malformed lock");
381         createAndInsertIntoTable();
382
383         String lockRef = createLockReference();
384
385         Response response = lock.deleteLock(malformedLock, "1", "1",
386                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", wrongAuthorization, appName);
387         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
388         assertEquals(400, response.getStatus());
389     }
390         
391         /**
392          * Create table and lock reference
393          * @return the lock ref created
394          * @throws Exception 
395          */
396         @SuppressWarnings("unchecked")
397         private String createLockReference() throws Exception {
398         Response response =lock.createLockReference(lockName,"1","1",authorization,
399                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
400         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
401                 return ((Map<String,String>) respMap.get("lock")).get("lock");
402         }
403
404         
405         
406
407         private static void createKeyspace() throws Exception {
408                 //shouldn't really be doing this here, but create keyspace is currently turned off
409                 PreparedQueryObject query = new PreparedQueryObject();
410                 query.appendQueryString(CassandraCQL.createKeySpace);
411                 MusicCore.eventualPut(query);
412                 
413                 boolean isAAF = false;
414         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
415         query = new PreparedQueryObject();
416         query.appendQueryString(
417                     "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
418                                     + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
419         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
420         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
421         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
422         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
423         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
424         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
425         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
426         CachingUtil.updateMusicCache(keyspaceName, appName);
427         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
428         MusicCore.eventualPut(query);
429         }
430         
431         private void clearAllTablesFromKeyspace() throws MusicServiceException {
432                 ArrayList<String> tableNames = new ArrayList<>();
433                 PreparedQueryObject query = new PreparedQueryObject();
434                 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
435                 ResultSet rs = MusicCore.get(query);
436                 for (Row row: rs) {
437                         tableNames.add(row.getString("table_name"));
438                 }
439                 for (String table: tableNames) {
440                         query = new PreparedQueryObject();
441                         query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
442                         MusicCore.eventualPut(query);
443                 }
444         }
445         
446         /**
447          * Create a table {@link tableName} in {@link keyspaceName}
448          * @throws Exception
449          */
450         private void createTable() throws Exception {
451                 JsonTable jsonTable = new JsonTable();
452                 Map<String, String> consistencyInfo = new HashMap<>();
453                 Map<String, String> fields = new HashMap<>();
454                 fields.put("uuid", "text");
455                 fields.put("emp_name", "text");
456                 fields.put("emp_salary", "varint");
457                 fields.put("PRIMARY KEY", "(emp_name)");
458                 consistencyInfo.put("type", "eventual");
459                 jsonTable.setConsistencyInfo(consistencyInfo);
460                 jsonTable.setKeyspaceName(keyspaceName);
461                 jsonTable.setPrimaryKey("emp_name");
462                 jsonTable.setTableName(tableName);
463                 jsonTable.setFields(fields);
464                 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
465                 Response response = data.createTable("1", "1", "1",
466                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization, 
467                                 jsonTable, keyspaceName, tableName);
468         }
469         
470         /**
471          * Create table {@link createTable} and insert into said table
472          * @throws Exception
473          */
474         private void createAndInsertIntoTable() throws Exception {
475                 createTable();
476                 
477                 JsonInsert jsonInsert = new JsonInsert();
478                 Map<String, String> consistencyInfo = new HashMap<>();
479                 Map<String, Object> values = new HashMap<>();
480                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
481                 values.put("emp_name", "testname");
482                 values.put("emp_salary", 500);
483                 consistencyInfo.put("type", "eventual");
484                 jsonInsert.setConsistencyInfo(consistencyInfo);
485                 jsonInsert.setKeyspaceName(keyspaceName);
486                 jsonInsert.setTableName(tableName);
487                 jsonInsert.setValues(values);
488                 Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
489                                 appName, authorization, jsonInsert, keyspaceName, tableName);
490         }
491 }