aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/main/MusicUtil.java
blob: 5bc9f94fab144bddf097b63c216e9d72f9ec832d (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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
 * ============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.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
import org.onap.music.exceptions.MusicServiceException;

import com.datastax.driver.core.DataType;

/**
 * @author nelson24
 * 
 *         Properties This will take Properties and load them into MusicUtil.
 *         This is a hack for now. Eventually it would bebest to do this in
 *         another way.
 * 
 */
public class MusicUtil {
    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
    
    public static final String ATOMIC = "atomic";
    public static final String EVENTUAL = "eventual";
    public static final String CRITICAL = "critical";
    public static final String ATOMICDELETELOCK = "atomic_delete_lock";
    
    public static final String DEFAULTKEYSPACENAME = "TBD";

    
    private static int myId = 0;
    private static ArrayList<String> allIds = new ArrayList<>();
    private static String publicIp = "";
    private static ArrayList<String> allPublicIps = new ArrayList<>();
    private static String myZkHost = "localhost";
    private static String myCassaHost = "localhost";
    private static String defaultMusicIp = "localhost";
    private static boolean debug = true;
    private static String version = "2.3.0";
    private static String musicRestIp = "localhost";
    private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties";
    private static long defaultLockLeasePeriod = 6000;
    private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
            "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
            "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" };

    private static String cassName = "cassandra";
    private static String cassPwd;
    private static String aafEndpointUrl = null;

    private MusicUtil() {
        throw new IllegalStateException("Utility Class");
    }
    
    
    /**
     * @return the cassName
     */
    public static String getCassName() {
        return cassName;
    }

    /**
     * @return the cassPwd
     */
    public static String getCassPwd() {
        return cassPwd;
    }

    /**
     * @return the aafEndpointUrl
     */
    public static String getAafEndpointUrl() {
        return aafEndpointUrl;
    }

    /**
     * 
     * @param aafEndpointUrl
     */
    public static void setAafEndpointUrl(String aafEndpointUrl) {
        MusicUtil.aafEndpointUrl = aafEndpointUrl;
    }

    /**
     * 
     * @return
     */
    public static int getMyId() {
        return myId;
    }

    /**
     * 
     * @param myId
     */
    public static void setMyId(int myId) {
        MusicUtil.myId = myId;
    }

    /**
     * 
     * @return
     */
    public static List<String> getAllIds() {
        return allIds;
    }

    /**
     * 
     * @param allIds
     */
    public static void setAllIds(List<String> allIds) {
        MusicUtil.allIds = (ArrayList<String>) allIds;
    }

    /**
     * 
     * @return
     */
    public static String getPublicIp() {
        return publicIp;
    }

    /**
     * 
     * @param publicIp
     */
    public static void setPublicIp(String publicIp) {
        MusicUtil.publicIp = publicIp;
    }

    /**
     * 
     * @return
     */
    public static List<String> getAllPublicIps() {
        return allPublicIps;
    }

    /**
     * 
     * @param allPublicIps
     */
    public static void setAllPublicIps(List<String> allPublicIps) {
        MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
    }

    /**
     * Returns An array of property names that should be in the Properties
     * files.
     * 
     * @return
     */
    public static String[] getPropkeys() {
        return propKeys;
    }

    /**
     * Get MusicRestIp - default = localhost property file value - music.rest.ip
     * 
     * @return
     */
    public static String getMusicRestIp() {
        return musicRestIp;
    }

    /**
     * Set MusicRestIp
     * 
     * @param musicRestIp
     */
    public static void setMusicRestIp(String musicRestIp) {
        MusicUtil.musicRestIp = musicRestIp;
    }

    /**
     * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
     * property file value - music.properties
     * 
     * @return
     */
    public static String getMusicPropertiesFilePath() {
        return musicPropertiesFilePath;
    }

    /**
     * Set MusicPropertiesFilePath
     * 
     * @param musicPropertiesFilePath
     */
    public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
        MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
    }

    /**
     * Get DefaultLockLeasePeriod - Default = 6000 property file value -
     * lock.lease.period
     * 
     * @return
     */
    public static long getDefaultLockLeasePeriod() {
        return defaultLockLeasePeriod;
    }

    /**
     * Set DefaultLockLeasePeriod
     * 
     * @param defaultLockLeasePeriod
     */
    public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
        MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
    }

    /**
     * Set Debug
     * 
     * @param debug
     */
    public static void setDebug(boolean debug) {
        MusicUtil.debug = debug;
    }

    /**
     * Is Debug - Default = true property file value - debug
     * 
     * @return
     */
    public static boolean isDebug() {
        return debug;
    }

    /**
     * Set Version
     * 
     * @param version
     */
    public static void setVersion(String version) {
        MusicUtil.version = version;
    }

    /**
     * Return the version property file value - version
     * 
     * @return
     */
    public static String getVersion() {
        return version;
    }

    /**
     * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
     * value - zookeeper.host
     * 
     * @return
     */
    public static String getMyZkHost() {
        return myZkHost;
    }

    /**
     * Set MyZkHost - Zookeeper Hostname
     * 
     * @param myZkHost
     */
    public static void setMyZkHost(String myZkHost) {
        MusicUtil.myZkHost = myZkHost;
    }

    /**
     * Get MyCassHost - Cassandra Hostname - Default = localhost property file
     * value - cassandra.host
     * 
     * @return
     */
    public static String getMyCassaHost() {
        return myCassaHost;
    }

    /**
     * Set MyCassHost - Cassandra Hostname
     * 
     * @param myCassaHost
     */
    public static void setMyCassaHost(String myCassaHost) {
        MusicUtil.myCassaHost = myCassaHost;
    }

    /**
     * Get DefaultMusicIp - Default = localhost property file value - music.ip
     * 
     * @return
     */
    public static String getDefaultMusicIp() {
        return defaultMusicIp;
    }

    /**
     * Set DefaultMusicIp
     * 
     * @param defaultMusicIp
     */
    public static void setDefaultMusicIp(String defaultMusicIp) {
        MusicUtil.defaultMusicIp = defaultMusicIp;
    }

    /**
     * 
     * @return
     */
    public static String getTestType() {
        String testType = "";
        try {
            Scanner fileScanner = new Scanner(new File(""));
            testType = fileScanner.next();// ignore the my id line
            String batchSize = fileScanner.next();// ignore the my public ip
                                                    // line
            fileScanner.close();
        } catch (FileNotFoundException e) {
            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
        }
        return testType;

    }

    /**
     * 
     * @param time
     */
    public static void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
            Thread.currentThread().interrupt();
        }
    }

    /**
     * Utility function to check if the query object is valid.
     * 
     * @param withparams
     * @param queryObject
     * @return
     */
    public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
        if (withparams) {
            int noOfValues = queryObject.getValues().size();
            int noOfParams = 0;
            char[] temp = queryObject.getQuery().toCharArray();
            for (int i = 0; i < temp.length; i++) {
                if (temp[i] == '?')
                    noOfParams++;
            }
            return (noOfValues == noOfParams);
        } else {
            return !queryObject.getQuery().isEmpty();
        }

    }

    public static void setCassName(String cassName) {
        MusicUtil.cassName = cassName;
    }

    public static void setCassPwd(String cassPwd) {
        MusicUtil.cassPwd = cassPwd;
    }

    public static String convertToCQLDataType(DataType type, Object valueObj) {

        String value = "";
        switch (type.getName()) {
        case UUID:
            value = valueObj + "";
            break;
        case TEXT:
        case VARCHAR:
            String valueString = valueObj + "";
            valueString = valueString.replace("'", "''");
            value = "'" + valueString + "'";
            break;
        case MAP: {
            Map<String, Object> otMap = (Map<String, Object>) valueObj;
            value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
            break;
        }
        default:
            value = valueObj + "";
            break;
        }
        return value;
    }

    /**
     * 
     * @param colType
     * @param valueObj
     * @return
     * @throws Exception
     */
    public static Object convertToActualDataType(DataType colType, Object valueObj)  throws Exception{
        String valueObjString = valueObj + "";
        switch (colType.getName()) {
        case UUID:
            return UUID.fromString(valueObjString);
        case VARINT:
            return BigInteger.valueOf(Long.parseLong(valueObjString));
        case BIGINT:
            return Long.parseLong(valueObjString);
        case INT:
            return Integer.parseInt(valueObjString);
        case FLOAT:
            return Float.parseFloat(valueObjString);
        case DOUBLE:
            return Double.parseDouble(valueObjString);
        case BOOLEAN:
            return Boolean.parseBoolean(valueObjString);
        case MAP:
            return (Map<String, Object>) valueObj;
        default:
            return valueObjString;
        }
    }

    /**
     *
     * Utility function to parse json map into sql like string
     * 
     * @param jMap
     * @param lineDelimiter
     * @return
     */

    public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) {
        StringBuilder sqlString = new StringBuilder();
        int counter = 0;
        for (Map.Entry<String, Object> entry : jMap.entrySet()) {
            Object ot = entry.getValue();
            String value = ot + "";
            if (ot instanceof String) {
                value = "'" + value.replace("'", "''") + "'";
            }
            sqlString.append("'" + entry.getKey() + "':" + value);
            if (counter != jMap.size() - 1)
                sqlString.append(lineDelimiter);
            counter = counter + 1;
        }
        return sqlString.toString();
    }

    public static Map<String, HashMap<String, Object>> setErrorResponse(MusicServiceException ex) {
        Map<String, HashMap<String, Object>> results = new HashMap<>();
        HashMap<String, Object> tempMap = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        result.put("error-description", ex.getMessage());
        tempMap.put("error", result);
        results.put("result", tempMap);
        return results;
    }
}