93a2e12b770a7f8c894fe4ce19b4f7260a012466
[music.git] / src / main / java / org / onap / music / client / MusicRestClient.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.client;
23
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Random;
27 import javax.ws.rs.core.MediaType;
28 import org.onap.music.datastore.jsonobjects.JsonDelete;
29 import org.onap.music.datastore.jsonobjects.JsonInsert;
30 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
31 import org.onap.music.datastore.jsonobjects.JsonTable;
32 import org.onap.music.main.MusicUtil;
33 import com.sun.jersey.api.client.Client;
34 import com.sun.jersey.api.client.ClientResponse;
35 import com.sun.jersey.api.client.WebResource;
36 import com.sun.jersey.api.client.config.ClientConfig;
37 import com.sun.jersey.api.client.config.DefaultClientConfig;
38 import com.sun.jersey.api.json.JSONConfiguration;
39
40 public class MusicRestClient {
41     String[] musicNodes;
42
43     public MusicRestClient(String[] musicNodes) {
44         this.musicNodes = musicNodes;
45     }
46
47     public MusicRestClient(String oneMusicNode) {
48         musicNodes = new String[1];
49         this.musicNodes[0] = oneMusicNode;
50     }
51
52     public String getMusicNodeURL() {
53         String musicurl = "http://" + getMusicNodeIp() + ":8080/MUSIC/rest";
54         return musicurl;
55     }
56
57     private String getMusicNodeIp() {
58         Random r = new Random();
59         int index = r.nextInt(musicNodes.length);
60         return musicNodes[index];
61     }
62
63     public void createKeyspace(String keyspaceName) {
64         Map<String, Object> replicationInfo = new HashMap<String, Object>();
65         replicationInfo.put("class", "SimpleStrategy");
66         replicationInfo.put("replication_factor", 1);
67         String durabilityOfWrites = "false";
68         Map<String, String> consistencyInfo = new HashMap<String, String>();
69         consistencyInfo.put("type", "eventual");
70         org.onap.music.datastore.jsonobjects.JsonKeySpace jsonKp = new JsonKeySpace();
71         jsonKp.setConsistencyInfo(consistencyInfo);
72         jsonKp.setDurabilityOfWrites(durabilityOfWrites);
73         jsonKp.setReplicationInfo(replicationInfo);
74
75         ClientConfig clientConfig = new DefaultClientConfig();
76
77         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
78
79         Client client = Client.create(clientConfig);
80
81         WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName);
82
83         ClientResponse response = webResource.accept("application/json").type("application/json")
84                         .post(ClientResponse.class, jsonKp);
85
86         if (response.getStatus() < 200 || response.getStatus() > 299)
87             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
88
89     }
90
91     public void createStringMapTable(String keyspaceName, String tableName,
92                     Map<String, String> fields) {
93         Map<String, String> consistencyInfo = new HashMap<String, String>();
94         consistencyInfo.put("type", "eventual");
95
96         JsonTable jtab = new JsonTable();
97         jtab.setFields(fields);
98         jtab.setConsistencyInfo(consistencyInfo);
99
100         ClientConfig clientConfig = new DefaultClientConfig();
101
102         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
103
104         Client client = Client.create(clientConfig);
105         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName;
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     public void checkMusicVersion() {
117         Client client = Client.create();
118
119         WebResource webResource = client.resource(getMusicNodeURL() + "/version");
120
121         ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class);
122
123         if (response.getStatus() != 200) {
124             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
125         }
126
127         String output = response.getEntity(String.class);
128     }
129
130     public void createRow(String keyspaceName, String tableName, Map<String, Object> values) {
131         Map<String, String> consistencyInfo = new HashMap<String, String>();
132         consistencyInfo.put("type", "eventual");
133
134         JsonInsert jIns = new JsonInsert();
135         jIns.setValues(values);
136         jIns.setConsistencyInfo(consistencyInfo);
137         ClientConfig clientConfig = new DefaultClientConfig();
138
139         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
140
141         Client client = Client.create(clientConfig);
142
143         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
144                         + "/rows";
145         WebResource webResource = client.resource(url);
146
147         ClientResponse response = webResource.accept("application/json").type("application/json")
148                         .post(ClientResponse.class, jIns);
149
150         if (response.getStatus() < 200 || response.getStatus() > 299)
151             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:"
152                             + url + "values:" + values);
153
154
155     }
156
157     private void basicUpdateRow(String keyspaceName, String tableName, String primaryKeyName,
158                     String primaryKeyValue, Map<String, Object> values,
159                     Map<String, String> consistencyInfo) {
160         JsonInsert jIns = new JsonInsert();
161         jIns.setValues(values);
162         jIns.setConsistencyInfo(consistencyInfo);
163         ClientConfig clientConfig = new DefaultClientConfig();
164
165         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
166
167         Client client = Client.create(clientConfig);
168         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
169                         + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
170         WebResource webResource = client.resource(url);
171
172         ClientResponse response = webResource.accept("application/json").type("application/json")
173                         .put(ClientResponse.class, jIns);
174
175         if (response.getStatus() < 200 || response.getStatus() > 299)
176             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:"
177                             + url + " values:" + values);
178
179     }
180
181     public void updateEntry(String keyspaceName, String tableName, String primaryKeyName,
182                     String primaryKeyValue, Map<String, Object> values) {
183         Map<String, String> consistencyInfo = new HashMap<String, String>();
184         consistencyInfo.put("type", "eventual");
185         basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values,
186                         consistencyInfo);
187     }
188
189     public void deleteEntry(String keyspaceName, String tableName, String primaryKeyName,
190                     String primaryKeyValue) {
191         Map<String, String> consistencyInfo = new HashMap<String, String>();
192         consistencyInfo.put("type", "eventual");
193
194         JsonDelete jDel = new JsonDelete();
195         jDel.setConsistencyInfo(consistencyInfo);
196         ClientConfig clientConfig = new DefaultClientConfig();
197
198         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
199
200         Client client = Client.create(clientConfig);
201         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
202                         + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
203         WebResource webResource = client.resource(url);
204
205         ClientResponse response = webResource.accept("application/json").type("application/json")
206                         .delete(ClientResponse.class, jDel);
207
208         if (response.getStatus() < 200 || response.getStatus() > 299)
209             throw new RuntimeException(
210                             "Failed : HTTP error code : " + response.getStatus() + "url:" + url);
211
212     }
213
214     public Map<String, Object> readRow(String keyspaceName, String tableName, String primaryKeyName,
215                     String primaryKeyValue) {
216         ClientConfig clientConfig = new DefaultClientConfig();
217
218         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
219
220         Client client = Client.create(clientConfig);
221         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
222                         + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
223         WebResource webResource = client.resource(url);
224
225         ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
226
227         if (response.getStatus() < 200 || response.getStatus() > 299)
228             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
229
230         Map<String, Object> output = response.getEntity(Map.class);
231         return output;
232     }
233
234     public Map<String, Object> readAllRows(String keyspaceName, String tableName) {
235         ClientConfig clientConfig = new DefaultClientConfig();
236
237         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
238
239         Client client = Client.create(clientConfig);
240         String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
241                         + "/rows";
242         WebResource webResource = client.resource(url);
243
244         ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
245
246         if (response.getStatus() < 200 || response.getStatus() > 299)
247             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
248
249         Map<String, Object> output = response.getEntity(Map.class);
250         return output;
251     }
252
253
254     public void dropKeySpace(String keyspaceName) {
255         Map<String, String> consistencyInfo = new HashMap<String, String>();
256         consistencyInfo.put("type", "eventual");
257
258         JsonKeySpace jsonKp = new JsonKeySpace();
259         jsonKp.setConsistencyInfo(consistencyInfo);
260
261         ClientConfig clientConfig = new DefaultClientConfig();
262
263         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
264
265         Client client = Client.create(clientConfig);
266
267         WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName);
268
269         ClientResponse response =
270                         webResource.type("application/json").delete(ClientResponse.class, jsonKp);
271
272         if (response.getStatus() < 200 || response.getStatus() > 299)
273             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
274     }
275
276     public String createLock(String primaryKeyValue) {
277         Client client = Client.create();
278         String msg = getMusicNodeURL() + "/locks/create/" + primaryKeyValue;
279         WebResource webResource = client.resource(msg);
280
281         WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);
282
283         ClientResponse response = wb.post(ClientResponse.class);
284
285         if (response.getStatus() != 200) {
286             throw new RuntimeException(
287                             "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
288         }
289
290         String output = response.getEntity(String.class);
291
292         return output;
293     }
294
295     public boolean acquireLock(String lockId) {
296         Client client = Client.create();
297         String msg = getMusicNodeURL() + "/locks/acquire/" + lockId;
298         WebResource webResource = client.resource(msg);
299
300
301         WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);
302
303         ClientResponse response = wb.get(ClientResponse.class);
304
305         if (response.getStatus() != 200) {
306             throw new RuntimeException(
307                             "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
308         }
309
310         String output = response.getEntity(String.class);
311         Boolean status = Boolean.parseBoolean(output);
312         return status;
313     }
314
315     public void releaseLock(String lockId) {
316         Client client = Client.create();
317         WebResource webResource = client.resource(getMusicNodeURL() + "/locks/release/" + lockId);
318
319         ClientResponse response = webResource.delete(ClientResponse.class);
320
321
322         if (response.getStatus() != 204) {
323             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
324         }
325     }
326
327
328     public void updateRowAtomically(String keyspaceName, String tableName, String primaryKeyName,
329                     String primaryKeyValue, Map<String, Object> values) {
330         /*
331          * create lock for the candidate. The music API dictates that the lock name must be of the
332          * form keyspacename.tableName.primaryKeyName
333          */
334
335         String lockName = keyspaceName + "." + tableName + "." + primaryKeyValue;
336         String lockId = createLock(lockName);
337         while (acquireLock(lockId) != true);
338
339
340         Map<String, String> consistencyInfo = new HashMap<String, String>();
341         consistencyInfo.put("type", "atomic");
342         consistencyInfo.put("lockId", lockId);
343
344         basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values,
345                         consistencyInfo);
346
347         // release lock now that the operation is done
348         releaseLock(lockId);
349
350     }
351
352     public String getMusicId() {
353
354         Client client = Client.create();
355
356         WebResource webResource = client.resource(getMusicNodeURL() + "/nodeId");
357         ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class);
358
359         if (response.getStatus() != 200) {
360             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
361         }
362
363         String output = response.getEntity(String.class);
364         return output;
365     }
366
367     public void deleteRowAtomically(String keyspaceName, String tableName, String primaryKeyName,
368                     String primaryKeyValue, Map<String, Object> values) {
369
370     }
371
372     public void deleteLock(String lockName) {
373         Client client = Client.create();
374         WebResource webResource = client.resource(getMusicNodeURL() + "/locks/delete/" + lockName);
375
376         ClientResponse response = webResource.delete(ClientResponse.class);
377
378
379         if (response.getStatus() != 204) {
380             throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
381         }
382     }
383 }
384