Sonar and CLM fixes and Unit test
[music.git] / src / test / java / org / onap / music / e2eTests / TestMusicE2E.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 package org.onap.music.e2eTests;
23
24 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.Map;
31 import javax.ws.rs.core.MediaType;
32 import org.onap.music.datastore.jsonobjects.JsonDelete;
33 import org.onap.music.datastore.jsonobjects.JsonInsert;
34 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
35 import org.onap.music.datastore.jsonobjects.JsonTable;
36 import com.sun.jersey.api.client.Client;
37 import com.sun.jersey.api.client.ClientResponse;
38 import com.sun.jersey.api.client.WebResource;
39 import com.sun.jersey.api.client.config.ClientConfig;
40 import com.sun.jersey.api.client.config.DefaultClientConfig;
41 import com.sun.jersey.api.json.JSONConfiguration;
42
43 public class TestMusicE2E {
44     String keyspaceName;
45     ArrayList<String> lockNames;
46     MusicConnector musicHandle;
47
48     public TestMusicE2E(String[] musicIps) {
49         lockNames = new ArrayList<String>();
50         musicHandle = new MusicConnector(musicIps);
51         bootStrap();
52     }
53
54     public void createVotingKeyspace() {
55         keyspaceName = "VotingAppForMusic" + System.currentTimeMillis();
56         Map<String, Object> replicationInfo = new HashMap<String, Object>();
57         replicationInfo.put("class", "SimpleStrategy");
58         replicationInfo.put("replication_factor", 1);
59         String durabilityOfWrites = "false";
60         Map<String, String> consistencyInfo = new HashMap<String, String>();
61         consistencyInfo.put("type", "eventual");
62         JsonKeySpace jsonKp = new JsonKeySpace();
63         jsonKp.setConsistencyInfo(consistencyInfo);
64         jsonKp.setDurabilityOfWrites(durabilityOfWrites);
65         jsonKp.setReplicationInfo(replicationInfo);
66
67         ClientConfig clientConfig = new DefaultClientConfig();
68
69         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
70
71         Client client = Client.create(clientConfig);
72
73         WebResource webResource = client
74                         .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName);
75
76         ClientResponse response = webResource.accept("application/json").type("application/json")
77                         .post(ClientResponse.class, jsonKp);
78
79         if (response.getStatus() < 200 || response.getStatus() > 299)
80             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
81
82     }
83
84     public void createVotingTable() {
85         Map<String, String> fields = new HashMap<String, String>();
86         fields.put("name", "text");
87         fields.put("count", "varint");
88         fields.put("PRIMARY KEY", "(name)");
89
90
91         Map<String, String> consistencyInfo = new HashMap<String, String>();
92         consistencyInfo.put("type", "eventual");
93
94         JsonTable jtab = new JsonTable();
95         jtab.setFields(fields);
96         jtab.setConsistencyInfo(consistencyInfo);
97
98         ClientConfig clientConfig = new DefaultClientConfig();
99
100         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
101
102         Client client = Client.create(clientConfig);
103         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
104                         + "/tables/votecount";
105         System.out.println("create url:" + url);
106         WebResource webResource = client.resource(url);
107
108         ClientResponse response = webResource.accept("application/json").type("application/json")
109                         .post(ClientResponse.class, jtab);
110
111         if (response.getStatus() < 200 || response.getStatus() > 299)
112             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
113
114     }
115
116     private void checkMusicVersion() {
117         Client client = Client.create();
118         System.out.println(musicHandle.getMusicNodeURL() + "/version");
119
120
121         // System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
122         WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/version");
123
124
125         ClientResponse response = webResource.accept("text/plain").header("Connection", "close")
126                         .get(ClientResponse.class);
127
128         if (response.getStatus() != 200) {
129             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
130         }
131
132         String output = response.getEntity(String.class);
133
134         // System.out.println("Output from Server .... \n");
135         System.out.println(output);
136
137     }
138
139     private void createEntryForCandidate(String candidateName) {
140         Map<String, Object> values = new HashMap<String, Object>();
141         values.put("name", candidateName);
142         values.put("count", 0);
143
144         Map<String, String> consistencyInfo = new HashMap<String, String>();
145         consistencyInfo.put("type", "eventual");
146
147         JsonInsert jIns = new JsonInsert();
148         jIns.setValues(values);
149         jIns.setConsistencyInfo(consistencyInfo);
150         ClientConfig clientConfig = new DefaultClientConfig();
151
152         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
153
154         Client client = Client.create(clientConfig);
155
156         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
157                         + "/tables/votecount/rows";
158         WebResource webResource = client.resource(url);
159
160         ClientResponse response = webResource.accept("application/json").type("application/json")
161                         .post(ClientResponse.class, jIns);
162
163         if (response.getStatus() < 200 || response.getStatus() > 299)
164             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:"
165                             + url + " candidate name:" + candidateName);
166
167
168     }
169
170     private String createLock(String lockName) {
171         Client client = Client.create();
172         String msg = musicHandle.getMusicNodeURL() + "/locks/create/" + lockName;
173         WebResource webResource = client.resource(msg);
174         System.out.println(msg);
175         WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);
176
177         ClientResponse response = wb.post(ClientResponse.class);
178
179         if (response.getStatus() != 200) {
180             throw new RuntimeException(
181                             "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
182         }
183
184         String output = response.getEntity(String.class);
185
186         // System.out.println("Server response .... \n");
187         // System.out.println(output);
188         return output;
189     }
190
191     private boolean acquireLock(String lockId) {
192         Client client = Client.create();
193         String msg = musicHandle.getMusicNodeURL() + "/locks/acquire/" + lockId;
194         System.out.println(msg);
195         WebResource webResource = client.resource(msg);
196
197
198         WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);
199
200         ClientResponse response = wb.get(ClientResponse.class);
201
202         if (response.getStatus() != 200) {
203             throw new RuntimeException(
204                             "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
205         }
206
207         String output = response.getEntity(String.class);
208         Boolean status = Boolean.parseBoolean(output);
209         System.out.println("Server response .... \n");
210         System.out.println(output);
211         return status;
212     }
213
214     private void unlock(String lockId) {
215         Client client = Client.create();
216         WebResource webResource =
217                         client.resource(musicHandle.getMusicNodeURL() + "/locks/release/" + lockId);
218
219         ClientResponse response = webResource.delete(ClientResponse.class);
220
221
222         if (response.getStatus() != 204) {
223             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
224         }
225     }
226
227     private void updateVoteCountAtomically(String candidateName, int count) {
228         /*
229          * create lock for the candidate. The music API dictates that the lock name must be of the
230          * form keyspacename.tableName.primaryKeyName
231          */
232         System.out.println("trying to acquire lock!");
233
234         String lockName = keyspaceName + ".votecount." + candidateName;
235         lockNames.add(lockName);
236         String lockId = createLock(lockName);
237         while (acquireLock(lockId) != true);
238
239         System.out.println("acquired lock!");
240         // update candidate entry if you have the lock
241         Map<String, Object> values = new HashMap<String, Object>();
242         values.put("count", count);
243
244         Map<String, String> consistencyInfo = new HashMap<String, String>();
245         consistencyInfo.put("type", "critical");
246         consistencyInfo.put("lockId", lockId);
247
248         JsonInsert jIns = new JsonInsert();
249         jIns.setValues(values);
250         jIns.setConsistencyInfo(consistencyInfo);
251         ClientConfig clientConfig = new DefaultClientConfig();
252
253         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
254
255         Client client = Client.create(clientConfig);
256         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
257                         + "/tables/votecount/rows?name=" + candidateName;
258         System.out.println(url);
259         WebResource webResource = client.resource(url);
260
261         ClientResponse response = webResource.accept("application/json").type("application/json")
262                         .put(ClientResponse.class, jIns);
263
264         if (response.getStatus() < 200 || response.getStatus() > 299)
265             throw new RuntimeException(
266                             "Failed : HTTP error code : " + response.getStatus() + "url:" + url);
267
268         // release lock now that the operation is done
269         unlock(lockId);
270
271     }
272
273     private void deleteCandidateEntryEventually(String candidateName) {
274         Map<String, String> consistencyInfo = new HashMap<String, String>();
275         consistencyInfo.put("type", "eventual");
276
277         JsonDelete jDel = new JsonDelete();
278         jDel.setConsistencyInfo(consistencyInfo);
279         ClientConfig clientConfig = new DefaultClientConfig();
280
281         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
282
283         Client client = Client.create(clientConfig);
284         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
285                         + "/tables/votecount/rows?name=" + candidateName;
286         System.out.println(url);
287         WebResource webResource = client.resource(url);
288
289         ClientResponse response = webResource.accept("application/json").type("application/json")
290                         .delete(ClientResponse.class, jDel);
291
292         if (response.getStatus() < 200 || response.getStatus() > 299)
293             throw new RuntimeException(
294                             "Failed : HTTP error code : " + response.getStatus() + "url:" + url);
295
296     }
297
298     public Map<String, Object> readVoteCountForCandidate(String candidateName) {
299         ClientConfig clientConfig = new DefaultClientConfig();
300
301         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
302
303         Client client = Client.create(clientConfig);
304         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
305                         + "/tables/votecount/rows?name=" + candidateName;
306         WebResource webResource = client.resource(url);
307
308         ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
309
310         if (response.getStatus() < 200 || response.getStatus() > 299)
311             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
312
313         Map<String, Object> output = response.getEntity(Map.class);
314         return output;
315     }
316
317     public Map<String, Object> readAllVotes() {
318         ClientConfig clientConfig = new DefaultClientConfig();
319
320         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
321
322         Client client = Client.create(clientConfig);
323         String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName
324                         + "/tables/votecount/rows";
325         WebResource webResource = client.resource(url);
326
327         ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
328
329         if (response.getStatus() < 200 || response.getStatus() > 299)
330             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
331
332         Map<String, Object> output = response.getEntity(Map.class);
333         return output;
334     }
335
336
337     /*
338      * Unable to use this because of the error: Exception in thread "main"
339      * com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method
340      * DELETE doesn't support output. Seems to be a error in the rest java combination according to
341      * the interwebs
342      */
343     private void dropKeySpace() {
344         Map<String, String> consistencyInfo = new HashMap<String, String>();
345         consistencyInfo.put("type", "eventual");
346
347         JsonKeySpace jsonKp = new JsonKeySpace();
348         jsonKp.setConsistencyInfo(consistencyInfo);
349
350         ClientConfig clientConfig = new DefaultClientConfig();
351
352         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
353
354         Client client = Client.create(clientConfig);
355
356         WebResource webResource = client
357                         .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName);
358
359         ClientResponse response =
360                         webResource.type("application/json").delete(ClientResponse.class, jsonKp);
361
362         if (response.getStatus() < 200 || response.getStatus() > 299)
363             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
364     }
365
366     private void deleteLock(String lockName) {
367         Client client = Client.create();
368         WebResource webResource = client
369                         .resource(musicHandle.getMusicNodeURL() + "/locks/delete/" + lockName);
370
371         ClientResponse response = webResource.delete(ClientResponse.class);
372
373
374         if (response.getStatus() != 204) {
375             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
376         }
377     }
378
379     private void resetMusic() {
380         Client client = Client.create();
381         WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/reset");
382
383         ClientResponse response = webResource.delete(ClientResponse.class);
384
385
386         if (response.getStatus() != 204) {
387             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
388         }
389
390     }
391
392     public void deleteAllLocks() {
393         for (String lockName : lockNames) {
394             deleteLock(lockName);
395         }
396     }
397
398
399     public void bootStrap() {
400         checkMusicVersion();
401         createVotingKeyspace();
402
403
404         createVotingTable();
405
406
407         // the next few lines just create an entry in the voting table for all these candidates with
408         // vote count as 0
409         createEntryForCandidate("Popeye");
410
411         createEntryForCandidate("Judy");
412
413         createEntryForCandidate("Flash");
414
415         createEntryForCandidate("Mickey");
416
417     }
418
419     public void overAllTests() {
420         // update the count atomically
421         updateVoteCountAtomically("Popeye", 5);
422
423         updateVoteCountAtomically("Judy", 7);
424
425         updateVoteCountAtomically("Mickey", 8);
426
427         updateVoteCountAtomically("Flash", 2);
428
429
430         // read votecount
431         System.out.println(readAllVotes());
432
433         System.out.println(readVoteCountForCandidate("Popeye"));
434
435         System.out.println(readVoteCountForCandidate("Flash"));
436
437         deleteCandidateEntryEventually("Mickey");
438
439         System.out.println(readAllVotes());
440
441         dropKeySpace();
442
443         deleteAllLocks();
444     }
445
446     public void flipTest() {
447         checkMusicVersion();
448     }
449
450     public static String executeBashScript(String pathToScript, String arg1, String arg2) {
451         try {
452             ProcessBuilder pb = new ProcessBuilder(pathToScript, arg1, arg2);
453             final Process process = pb.start();
454             InputStream is = process.getInputStream();
455             InputStreamReader isr = new InputStreamReader(is);
456             BufferedReader br = new BufferedReader(isr);
457             return br.readLine();
458         } catch (IOException e) {
459             e.printStackTrace();
460         }
461         return null;
462     }
463
464     public static void main(String[] args) {
465         long start = System.currentTimeMillis();
466         for (int i = 0; i < 2; ++i) {
467             TestMusicE2E vHandle = new TestMusicE2E(args);
468             vHandle.overAllTests();
469
470             System.out.println("=====================================");
471             System.out.println("Test no." + i + " completed:");
472         }
473         long diff = System.currentTimeMillis() - start;
474         System.out.println(diff);
475     }
476
477
478 }