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