aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/client/MusicRestClient.java
blob: 93a2e12b770a7f8c894fe4ce19b4f7260a012466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
 * ============LICENSE_START==========================================
 * org.onap.music
 * ===================================================================
 *  Copyright (c) 2017 AT&T Intellectual Property
 * ===================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 * ============LICENSE_END=============================================
 * ====================================================================
 */
package org.onap.music.client;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.ws.rs.core.MediaType;
import org.onap.music.datastore.jsonobjects.JsonDelete;
import org.onap.music.datastore.jsonobjects.JsonInsert;
import org.onap.music.datastore.jsonobjects.JsonKeySpace;
import org.onap.music.datastore.jsonobjects.JsonTable;
import org.onap.music.main.MusicUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class MusicRestClient {
    String[] musicNodes;

    public MusicRestClient(String[] musicNodes) {
        this.musicNodes = musicNodes;
    }

    public MusicRestClient(String oneMusicNode) {
        musicNodes = new String[1];
        this.musicNodes[0] = oneMusicNode;
    }

    public String getMusicNodeURL() {
        String musicurl = "http://" + getMusicNodeIp() + ":8080/MUSIC/rest";
        return musicurl;
    }

    private String getMusicNodeIp() {
        Random r = new Random();
        int index = r.nextInt(musicNodes.length);
        return musicNodes[index];
    }

    public void createKeyspace(String keyspaceName) {
        Map<String, Object> replicationInfo = new HashMap<String, Object>();
        replicationInfo.put("class", "SimpleStrategy");
        replicationInfo.put("replication_factor", 1);
        String durabilityOfWrites = "false";
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");
        org.onap.music.datastore.jsonobjects.JsonKeySpace jsonKp = new JsonKeySpace();
        jsonKp.setConsistencyInfo(consistencyInfo);
        jsonKp.setDurabilityOfWrites(durabilityOfWrites);
        jsonKp.setReplicationInfo(replicationInfo);

        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);

        WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName);

        ClientResponse response = webResource.accept("application/json").type("application/json")
                        .post(ClientResponse.class, jsonKp);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());

    }

    public void createStringMapTable(String keyspaceName, String tableName,
                    Map<String, String> fields) {
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");

        JsonTable jtab = new JsonTable();
        jtab.setFields(fields);
        jtab.setConsistencyInfo(consistencyInfo);

        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName;
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").type("application/json")
                        .post(ClientResponse.class, jtab);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());

    }

    public void checkMusicVersion() {
        Client client = Client.create();

        WebResource webResource = client.resource(getMusicNodeURL() + "/version");

        ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        String output = response.getEntity(String.class);
    }

    public void createRow(String keyspaceName, String tableName, Map<String, Object> values) {
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");

        JsonInsert jIns = new JsonInsert();
        jIns.setValues(values);
        jIns.setConsistencyInfo(consistencyInfo);
        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);

        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
                        + "/rows";
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").type("application/json")
                        .post(ClientResponse.class, jIns);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:"
                            + url + "values:" + values);


    }

    private void basicUpdateRow(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue, Map<String, Object> values,
                    Map<String, String> consistencyInfo) {
        JsonInsert jIns = new JsonInsert();
        jIns.setValues(values);
        jIns.setConsistencyInfo(consistencyInfo);
        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
                        + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").type("application/json")
                        .put(ClientResponse.class, jIns);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:"
                            + url + " values:" + values);

    }

    public void updateEntry(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue, Map<String, Object> values) {
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");
        basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values,
                        consistencyInfo);
    }

    public void deleteEntry(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue) {
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");

        JsonDelete jDel = new JsonDelete();
        jDel.setConsistencyInfo(consistencyInfo);
        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
                        + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").type("application/json")
                        .delete(ClientResponse.class, jDel);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException(
                            "Failed : HTTP error code : " + response.getStatus() + "url:" + url);

    }

    public Map<String, Object> readRow(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue) {
        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
                        + "/rows?" + primaryKeyName + "=" + primaryKeyValue;
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());

        Map<String, Object> output = response.getEntity(Map.class);
        return output;
    }

    public Map<String, Object> readAllRows(String keyspaceName, String tableName) {
        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);
        String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName
                        + "/rows";
        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());

        Map<String, Object> output = response.getEntity(Map.class);
        return output;
    }


    public void dropKeySpace(String keyspaceName) {
        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "eventual");

        JsonKeySpace jsonKp = new JsonKeySpace();
        jsonKp.setConsistencyInfo(consistencyInfo);

        ClientConfig clientConfig = new DefaultClientConfig();

        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        Client client = Client.create(clientConfig);

        WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName);

        ClientResponse response =
                        webResource.type("application/json").delete(ClientResponse.class, jsonKp);

        if (response.getStatus() < 200 || response.getStatus() > 299)
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    public String createLock(String primaryKeyValue) {
        Client client = Client.create();
        String msg = getMusicNodeURL() + "/locks/create/" + primaryKeyValue;
        WebResource webResource = client.resource(msg);

        WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);

        ClientResponse response = wb.post(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException(
                            "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
        }

        String output = response.getEntity(String.class);

        return output;
    }

    public boolean acquireLock(String lockId) {
        Client client = Client.create();
        String msg = getMusicNodeURL() + "/locks/acquire/" + lockId;
        WebResource webResource = client.resource(msg);


        WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);

        ClientResponse response = wb.get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException(
                            "Failed : HTTP error code : " + response.getStatus() + "url:" + msg);
        }

        String output = response.getEntity(String.class);
        Boolean status = Boolean.parseBoolean(output);
        return status;
    }

    public void releaseLock(String lockId) {
        Client client = Client.create();
        WebResource webResource = client.resource(getMusicNodeURL() + "/locks/release/" + lockId);

        ClientResponse response = webResource.delete(ClientResponse.class);


        if (response.getStatus() != 204) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }
    }


    public void updateRowAtomically(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue, Map<String, Object> values) {
        /*
         * create lock for the candidate. The music API dictates that the lock name must be of the
         * form keyspacename.tableName.primaryKeyName
         */

        String lockName = keyspaceName + "." + tableName + "." + primaryKeyValue;
        String lockId = createLock(lockName);
        while (acquireLock(lockId) != true);


        Map<String, String> consistencyInfo = new HashMap<String, String>();
        consistencyInfo.put("type", "atomic");
        consistencyInfo.put("lockId", lockId);

        basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values,
                        consistencyInfo);

        // release lock now that the operation is done
        releaseLock(lockId);

    }

    public String getMusicId() {

        Client client = Client.create();

        WebResource webResource = client.resource(getMusicNodeURL() + "/nodeId");
        ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        String output = response.getEntity(String.class);
        return output;
    }

    public void deleteRowAtomically(String keyspaceName, String tableName, String primaryKeyName,
                    String primaryKeyValue, Map<String, Object> values) {

    }

    public void deleteLock(String lockName) {
        Client client = Client.create();
        WebResource webResource = client.resource(getMusicNodeURL() + "/locks/delete/" + lockName);

        ClientResponse response = webResource.delete(ClientResponse.class);


        if (response.getStatus() != 204) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }
    }
}