Create authentication interface
[music.git] / src / test / java / org / onap / music / unittests / TstRestMusicLockAPI.java
1 /*
2  * ============LICENSE_START========================================== org.onap.music
3  * =================================================================== Copyright (c) 2017 AT&T
4  * Intellectual Property ===================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the 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
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * 
15  * ============LICENSE_END=============================================
16  * ====================================================================
17  */
18
19 package org.onap.music.unittests;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertTrue;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.UUID;
28
29 import javax.ws.rs.core.Response;
30
31 import org.junit.After;
32 import org.junit.AfterClass;
33 import org.junit.BeforeClass;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mindrot.jbcrypt.BCrypt;
38 import org.mockito.junit.MockitoJUnitRunner;
39 import org.onap.music.authentication.CachingUtil;
40 import org.onap.music.datastore.MusicDataStoreHandle;
41 import org.onap.music.datastore.PreparedQueryObject;
42 import org.onap.music.datastore.jsonobjects.JsonInsert;
43 import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
44 import org.onap.music.datastore.jsonobjects.JsonTable;
45 import org.onap.music.exceptions.MusicServiceException;
46 import org.onap.music.lockingservice.cassandra.CassaLockStore;
47 import org.onap.music.main.MusicCore;
48 import org.onap.music.main.MusicUtil;
49 import org.onap.music.rest.RestMusicDataAPI;
50 import org.onap.music.rest.RestMusicLocksAPI;
51 import com.datastax.driver.core.DataType;
52 import com.datastax.driver.core.ResultSet;
53 import com.datastax.driver.core.Row;
54 import com.sun.jersey.core.util.Base64;
55
56 @RunWith(MockitoJUnitRunner.class)
57 public class TstRestMusicLockAPI {
58
59         RestMusicLocksAPI lock = new RestMusicLocksAPI();
60         RestMusicDataAPI data = new RestMusicDataAPI();
61         static PreparedQueryObject testObject;
62
63         static String appName = "TestApp";
64         static String userId = "TestUser";
65         static String password = "TestPassword";
66         static String authData = userId+":"+password;
67         static String wrongAuthData = userId+":"+"pass";
68         static String authorization = new String(Base64.encode(authData.getBytes()));
69         static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
70         static boolean isAAF = false;
71         static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
72         static String keyspaceName = "testcassa";
73         static String tableName = "employees";
74         static String onboardUUID = null;
75         static String lockName = "testcassa.employees.testname";
76
77         @BeforeClass
78         public static void init() throws Exception {
79                 System.out.println("Testing RestMusicLock class");
80                 try {
81                         createKeyspace();
82                 } catch (Exception e) {
83                         e.printStackTrace();
84                         throw new Exception("Unable to initialize before TestRestMusicData test class. " + e.getMessage());
85                 }
86         }
87         
88         @After
89         public void afterEachTest( ) throws MusicServiceException {
90                 clearAllTablesFromKeyspace();
91         }
92
93         @AfterClass
94         public static void tearDownAfterClass() throws Exception {
95                 testObject = new PreparedQueryObject();
96                 testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
97                 MusicCore.eventualPut(testObject);
98         }
99
100     @SuppressWarnings("unchecked")
101         @Test
102     public void test_createLockReference() throws Exception {
103         System.out.println("Testing create lockref");
104         createAndInsertIntoTable();
105         Response response =lock.createLockReference(lockName,"1","1",authorization,
106                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
107                 Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
108         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
109
110         assertEquals(200, response.getStatus());
111         assertTrue(respMap.containsKey("lock"));
112         assertTrue(((Map<String,String>) respMap.get("lock")).containsKey("lock"));
113     }
114
115     @Test
116     public void test_accquireLock() throws Exception {
117         System.out.println("Testing acquire lock");
118                 createAndInsertIntoTable();
119         String lockRef = createLockReference();
120
121         Response response = lock.accquireLock(lockRef, "1", "1", authorization,
122                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
123         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
124         assertEquals(200, response.getStatus());
125     }
126     
127     @Test
128     public void test_accquireLockWLease() throws Exception {
129         System.out.println("Testing acquire lock with lease");
130         createAndInsertIntoTable();
131         String lockRef = createLockReference();
132
133         JsonLeasedLock jsonLock = new JsonLeasedLock();
134         jsonLock.setLeasePeriod(10000); //10 second lease period?
135         Response response = lock.accquireLockWithLease(jsonLock, lockRef, "1", "1", authorization,
136                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
137         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
138         assertEquals(200, response.getStatus());
139     }
140     
141     @Test
142     public void test_accquireBadLock() throws Exception {
143         System.out.println("Testing acquire lock that is not lock-holder");
144                 createAndInsertIntoTable();
145
146         String lockRef1 = createLockReference();
147         String lockRef2 = createLockReference();
148
149
150         Response response = lock.accquireLock(lockRef2, "1", "1", authorization,
151                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
152         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
153         assertEquals(400, response.getStatus());
154     }
155     
156     @Test
157     public void test_currentLockHolder() throws Exception {
158         System.out.println("Testing get current lock holder");
159                 createAndInsertIntoTable();
160
161         String lockRef = createLockReference();
162
163         Response response = lock.currentLockHolder(lockName, "1", "1", authorization,
164                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
165         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
166         assertEquals(200, response.getStatus());
167         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
168         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
169     }
170     
171     @Test
172     public void test_unLock() throws Exception {
173         System.out.println("Testing unlock");
174                 createAndInsertIntoTable();
175         String lockRef = createLockReference();
176
177         Response response = lock.unLock(lockRef, "1", "1", authorization,
178                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
179         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
180         assertEquals(200, response.getStatus());
181     }
182     
183     @Test
184     public void test_getLockState() throws Exception {
185         System.out.println("Testing get lock state");
186         createAndInsertIntoTable();
187
188         String lockRef = createLockReference();
189
190         Response response = lock.currentLockState(lockName, "1", "1", authorization,
191                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
192         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
193         assertEquals(200, response.getStatus());
194         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
195         assertEquals(lockRef, ((Map<String,String>) respMap.get("lock")).get("lock-holder"));
196     }
197     
198     @Test
199     public void test_deleteLock() throws Exception {
200         System.out.println("Testing get lock state");
201         createAndInsertIntoTable();
202
203         String lockRef = createLockReference();
204
205         Response response = lock.deleteLock(lockName, "1", "1",
206                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", authorization, appName);
207         System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
208         assertEquals(200, response.getStatus());
209     }
210         
211         /**
212          * Create table and lock reference
213          * @return the lock ref created
214          * @throws Exception 
215          */
216         @SuppressWarnings("unchecked")
217         private String createLockReference() throws Exception {
218         Response response =lock.createLockReference(lockName,"1","1",authorization,
219                         "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName);
220         Map<String,Object> respMap = (Map<String, Object>) response.getEntity();
221                 return ((Map<String,String>) respMap.get("lock")).get("lock");
222         }
223
224         
225         
226
227         private static void createKeyspace() throws Exception {
228                 //shouldn't really be doing this here, but create keyspace is currently turned off
229                 PreparedQueryObject query = new PreparedQueryObject();
230                 query.appendQueryString(CassandraCQL.createKeySpace);
231                 MusicCore.eventualPut(query);
232                 
233                 boolean isAAF = false;
234         String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
235         query = new PreparedQueryObject();
236         query.appendQueryString(
237                     "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
238                                     + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
239         query.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
240         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
241         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
242         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
243         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
244         query.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
245         query.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
246         CachingUtil.updateMusicCache(keyspaceName, appName);
247         CachingUtil.updateMusicValidateCache(appName, userId, hashedpwd);
248         MusicCore.eventualPut(query);
249         }
250         
251         private void clearAllTablesFromKeyspace() throws MusicServiceException {
252                 ArrayList<String> tableNames = new ArrayList<>();
253                 PreparedQueryObject query = new PreparedQueryObject();
254                 query.appendQueryString("SELECT table_name FROM system_schema.tables WHERE keyspace_name = '"+keyspaceName+"';");
255                 ResultSet rs = MusicCore.get(query);
256                 for (Row row: rs) {
257                         tableNames.add(row.getString("table_name"));
258                 }
259                 for (String table: tableNames) {
260                         query = new PreparedQueryObject();
261                         query.appendQueryString("DROP TABLE " + keyspaceName + "." + table);
262                         MusicCore.eventualPut(query);
263                 }
264         }
265         
266         /**
267          * Create a table {@link tableName} in {@link keyspaceName}
268          * @throws Exception
269          */
270         private void createTable() throws Exception {
271                 JsonTable jsonTable = new JsonTable();
272                 Map<String, String> consistencyInfo = new HashMap<>();
273                 Map<String, String> fields = new HashMap<>();
274                 fields.put("uuid", "text");
275                 fields.put("emp_name", "text");
276                 fields.put("emp_salary", "varint");
277                 fields.put("PRIMARY KEY", "(emp_name)");
278                 consistencyInfo.put("type", "eventual");
279                 jsonTable.setConsistencyInfo(consistencyInfo);
280                 jsonTable.setKeyspaceName(keyspaceName);
281                 jsonTable.setPrimaryKey("emp_name");
282                 jsonTable.setTableName(tableName);
283                 jsonTable.setFields(fields);
284                 //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
285                 Response response = data.createTable("1", "1", "1",
286                                 "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",appName, authorization, 
287                                 jsonTable, keyspaceName, tableName);
288         }
289         
290         /**
291          * Create table {@link createTable} and insert into said table
292          * @throws Exception
293          */
294         private void createAndInsertIntoTable() throws Exception {
295                 createTable();
296                 
297                 JsonInsert jsonInsert = new JsonInsert();
298                 Map<String, String> consistencyInfo = new HashMap<>();
299                 Map<String, Object> values = new HashMap<>();
300                 values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
301                 values.put("emp_name", "testname");
302                 values.put("emp_salary", 500);
303                 consistencyInfo.put("type", "eventual");
304                 jsonInsert.setConsistencyInfo(consistencyInfo);
305                 jsonInsert.setKeyspaceName(keyspaceName);
306                 jsonInsert.setTableName(tableName);
307                 jsonInsert.setValues(values);
308                 Response response = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
309                                 appName, authorization, jsonInsert, keyspaceName, tableName);
310         }
311 }