Remove zookeeper reference
[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
81         @BeforeClass
82         public static void init() throws Exception {
83                 System.out.println("Testing RestMusicLock class");
84                 try {
85                         createKeyspace();
86                 } catch (Exception e) {
87                         e.printStackTrace();
88                         throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
89                 }
90         }
91         
92         @After
93         public void afterEachTest( ) throws MusicServiceException {
94                 clearAllTablesFromKeyspace();
95         }
96
97         @AfterClass
98         public static void tearDownAfterClass() throws Exception {
99                 testObject = new PreparedQueryObject();
100                 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
101                 MusicCore.eventualPut(testObject);
102         }
103
104     @SuppressWarnings("unchecked")
105         @Test
106     public void test_createLockReference() throws Exception {
107         System.out.println("Testing create lockref");
108         createAndInsertIntoTable();
109         Response response =lock.createLockReference(lockName,"1","1",authorization,
110                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
111                 Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
112         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
113
114         assertEquals(200, response.getStatus());
115         assertTrue(respMap.containsKey("lock"));
116         assertTrue(((Map<String,String>) respMap.get("lock")).containsKey("lock"));
117     }
118
119     @Test
120     public void test_accquireLock() throws Exception {
121         System.out.println("Testing acquire lock");
122                 createAndInsertIntoTable();
123         String lockRef = createLockReference();
124
125         Response response = lock.accquireLock(lockRef, "1", "1", authorization,
126                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
127         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
128         assertEquals(200, response.getStatus());
129     }
130     
131     @Test
132     public void test_accquireLockWLease() throws Exception {
133         System.out.println("Testing acquire lock with lease");
134         createAndInsertIntoTable();
135         String lockRef = createLockReference();
136
137         JsonLeasedLock jsonLock = new JsonLeasedLock();
138         jsonLock.setLeasePeriod(10000); //10 second lease period?
139         Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", authorization,
140                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
141         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
142         assertEquals(200, response.getStatus());
143     }
144     
145     @Test
146     public void test_accquireBadLock() throws Exception {
147         System.out.println("Testing acquire lock that is not lock-holder");
148                 createAndInsertIntoTable();
149
150         String lockRef1 = createLockReference();
151         String lockRef2 = createLockReference();
152
153
154         Response response = lock.accquireLock(lockRef2, "1", "1", authorization,
155                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
156         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
157         assertEquals(400, response.getStatus());
158     }
159     
160     @Test
161     public void test_currentLockHolder() throws Exception {
162         System.out.println("Testing get current lock holder");
163                 createAndInsertIntoTable();
164
165         String lockRef = createLockReference();
166
167         Response response = lock.currentLockHolder(lockName, "1", "1", authorization,
168                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
169         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
170         assertEquals(200, response.getStatus());
171         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
172         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
173     }
174     
175     @Test
176     public void test_unLock() throws Exception {
177         System.out.println("Testing unlock");
178                 createAndInsertIntoTable();
179         String lockRef = createLockReference();
180
181         Response response = lock.unLock(lockRef, "1", "1", authorization,
182                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
183         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
184         assertEquals(200, response.getStatus());
185     }
186     
187     @Test
188     public void test_getLockState() throws Exception {
189         System.out.println("Testing get lock state");
190         createAndInsertIntoTable();
191
192         String lockRef = createLockReference();
193
194         Response response = lock.currentLockState(lockName, "1", "1", authorization,
195                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
196         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
197         assertEquals(200, response.getStatus());
198         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
199         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
200     }
201     
202     @Test
203     public void test_deleteLock() throws Exception {
204         System.out.println("Testing get lock state");
205         createAndInsertIntoTable();
206
207         String lockRef = createLockReference();
208
209         Response response = lock.deleteLock(lockName, "1", "1",
210                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, appName);
211         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
212         assertEquals(200, response.getStatus());
213     }
214         
215         /**
216          * Create table and lock reference
217          * @return the lock ref created
218          * @throws Exception 
219          */
220         @SuppressWarnings("unchecked")
221         private String createLockReference() throws Exception {
222         Response response =lock.createLockReference(lockName,"1","1",authorization,
223                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
224         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
225                 return ((Map<String,String>) respMap.get("lock")).get("lock");
226         }
227
228         
229         
230
231         private static void createKeyspace() throws Exception {
232                 //shouldn't really be doing this here, but create keyspace is currently turned off
233                 PreparedQueryObject query = new PreparedQueryObject();
234                 query.appendQueryString(CassandraCQL.createKeySpace);
235                 MusicCore.eventualPut(query);
236                 
237                 boolean isAAF = false;
238         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
239         query = new PreparedQueryObject();
240         query.appendQueryString(
241                     "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
242                                     + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
243         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
244         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
245         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
246         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
247         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
248         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
249         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
250         CachingUtil.updateMusicCache(keyspaceName, appName);
251         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
252         MusicCore.eventualPut(query);
253         }
254         
255         private void clearAllTablesFromKeyspace() throws MusicServiceException {
256                 ArrayList<String> tableNames = new ArrayList<>();
257                 PreparedQueryObject query = new PreparedQueryObject();
258                 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
259                 ResultSet rs = MusicCore.get(query);
260                 for (Row row: rs) {
261                         tableNames.add(row.getString("table_name"));
262                 }
263                 for (String table: tableNames) {
264                         query = new PreparedQueryObject();
265                         query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
266                         MusicCore.eventualPut(query);
267                 }
268         }
269         
270         /**
271          * Create a table {@link tableName} in {@link keyspaceName}
272          * @throws Exception
273          */
274         private void createTable() throws Exception {
275                 JsonTable jsonTable = new JsonTable();
276                 Map<String, String> consistencyInfo = new HashMap<>();
277                 Map<String, String> fields = new HashMap<>();
278                 fields.put("uuid", "text");
279                 fields.put("emp_name", "text");
280                 fields.put("emp_salary", "varint");
281                 fields.put("PRIMARY KEY", "(emp_name)");
282                 consistencyInfo.put("type", "eventual");
283                 jsonTable.setConsistencyInfo(consistencyInfo);
284                 jsonTable.setKeyspaceName(keyspaceName);
285                 jsonTable.setPrimaryKey("emp_name");
286                 jsonTable.setTableName(tableName);
287                 jsonTable.setFields(fields);
288                 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
289                 Response response = data.createTable("1", "1", "1",
290                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization, 
291                                 jsonTable, keyspaceName, tableName);
292         }
293         
294         /**
295          * Create table {@link createTable} and insert into said table
296          * @throws Exception
297          */
298         private void createAndInsertIntoTable() throws Exception {
299                 createTable();
300                 
301                 JsonInsert jsonInsert = new JsonInsert();
302                 Map<String, String> consistencyInfo = new HashMap<>();
303                 Map<String, Object> values = new HashMap<>();
304                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
305                 values.put("emp_name", "testname");
306                 values.put("emp_salary", 500);
307                 consistencyInfo.put("type", "eventual");
308                 jsonInsert.setConsistencyInfo(consistencyInfo);
309                 jsonInsert.setKeyspaceName(keyspaceName);
310                 jsonInsert.setTableName(tableName);
311                 jsonInsert.setValues(values);
312                 Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
313                                 appName, authorization, jsonInsert, keyspaceName, tableName);
314         }
315 }