a31e33f94d311f2605f110dd06925b2150c7856d
[music.git] / src / main / java / org / onap / music / main / MusicUtil.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.main;
23
24 import java.io.File;
25 import java.io.FileNotFoundException;
26 import java.math.BigInteger;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Scanner;
32 import java.util.UUID;
33 import org.onap.music.datastore.PreparedQueryObject;
34 import org.onap.music.eelf.logging.EELFLoggerDelegate;
35 import org.onap.music.exceptions.MusicServiceException;
36
37 import com.datastax.driver.core.DataType;
38
39 /**
40  * @author nelson24
41  * 
42  *         Properties This will take Properties and load them into MusicUtil.
43  *         This is a hack for now. Eventually it would bebest to do this in
44  *         another way.
45  * 
46  */
47 public class MusicUtil {
48         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
49
50         private static int myId = 0;
51         private static ArrayList<String> allIds = new ArrayList<String>();
52         private static String publicIp = "";
53         private static ArrayList<String> allPublicIps = new ArrayList<String>();
54         private static String myZkHost = "localhost";
55         private static String myCassaHost = "localhost";
56         private static String defaultMusicIp = "localhost";
57         private static boolean debug = true;
58         private static String version = "2.3.0";
59         private static String musicRestIp = "localhost";
60         private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties";
61         private static long defaultLockLeasePeriod = 6000;
62         private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
63                         "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
64                         "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" };
65
66         public static final String ATOMIC = "atomic";
67         public static final String EVENTUAL = "eventual";
68         public static final String CRITICAL = "critical";
69         public static final String ATOMICDELETELOCK = "atomic_delete_lock";
70         
71         public static final String DEFAULTKEYSPACENAME = "TBD";
72         private static String cassName = "cassandra";
73         private static String cassPwd;
74         private static String aafEndpointUrl = null;
75
76         /**
77          * @return the cassName
78          */
79         public static String getCassName() {
80                 return cassName;
81         }
82
83         /**
84          * @return the cassPwd
85          */
86         public static String getCassPwd() {
87                 return cassPwd;
88         }
89
90         /**
91          * @return the aafEndpointUrl
92          */
93         public static String getAafEndpointUrl() {
94                 return aafEndpointUrl;
95         }
96
97         /**
98          * 
99          * @param aafEndpointUrl
100          */
101         public static void setAafEndpointUrl(String aafEndpointUrl) {
102                 MusicUtil.aafEndpointUrl = aafEndpointUrl;
103         }
104
105         /**
106          * 
107          * @return
108          */
109         public static int getMyId() {
110                 return myId;
111         }
112
113         /**
114          * 
115          * @param myId
116          */
117         public static void setMyId(int myId) {
118                 MusicUtil.myId = myId;
119         }
120
121         /**
122          * 
123          * @return
124          */
125         public static ArrayList<String> getAllIds() {
126                 return allIds;
127         }
128
129         /**
130          * 
131          * @param allIds
132          */
133         public static void setAllIds(List<String> allIds) {
134                 MusicUtil.allIds = (ArrayList<String>) allIds;
135         }
136
137         /**
138          * 
139          * @return
140          */
141         public static String getPublicIp() {
142                 return publicIp;
143         }
144
145         /**
146          * 
147          * @param publicIp
148          */
149         public static void setPublicIp(String publicIp) {
150                 MusicUtil.publicIp = publicIp;
151         }
152
153         /**
154          * 
155          * @return
156          */
157         public static ArrayList<String> getAllPublicIps() {
158                 return allPublicIps;
159         }
160
161         /**
162          * 
163          * @param allPublicIps
164          */
165         public static void setAllPublicIps(List<String> allPublicIps) {
166                 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
167         }
168
169         /**
170          * Returns An array of property names that should be in the Properties
171          * files.
172          * 
173          * @return
174          */
175         public static String[] getPropkeys() {
176                 return propKeys;
177         }
178
179         /**
180          * Get MusicRestIp - default = localhost property file value - music.rest.ip
181          * 
182          * @return
183          */
184         public static String getMusicRestIp() {
185                 return musicRestIp;
186         }
187
188         /**
189          * Set MusicRestIp
190          * 
191          * @param musicRestIp
192          */
193         public static void setMusicRestIp(String musicRestIp) {
194                 MusicUtil.musicRestIp = musicRestIp;
195         }
196
197         /**
198          * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
199          * property file value - music.properties
200          * 
201          * @return
202          */
203         public static String getMusicPropertiesFilePath() {
204                 return musicPropertiesFilePath;
205         }
206
207         /**
208          * Set MusicPropertiesFilePath
209          * 
210          * @param musicPropertiesFilePath
211          */
212         public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
213                 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
214         }
215
216         /**
217          * Get DefaultLockLeasePeriod - Default = 6000 property file value -
218          * lock.lease.period
219          * 
220          * @return
221          */
222         public static long getDefaultLockLeasePeriod() {
223                 return defaultLockLeasePeriod;
224         }
225
226         /**
227          * Set DefaultLockLeasePeriod
228          * 
229          * @param defaultLockLeasePeriod
230          */
231         public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
232                 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
233         }
234
235         /**
236          * Set Debug
237          * 
238          * @param debug
239          */
240         public static void setDebug(boolean debug) {
241                 MusicUtil.debug = debug;
242         }
243
244         /**
245          * Is Debug - Default = true property file value - debug
246          * 
247          * @return
248          */
249         public static boolean isDebug() {
250                 return debug;
251         }
252
253         /**
254          * Set Version
255          * 
256          * @param version
257          */
258         public static void setVersion(String version) {
259                 MusicUtil.version = version;
260         }
261
262         /**
263          * Return the version property file value - version
264          * 
265          * @return
266          */
267         public static String getVersion() {
268                 return version;
269         }
270
271         /**
272          * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
273          * value - zookeeper.host
274          * 
275          * @return
276          */
277         public static String getMyZkHost() {
278                 return myZkHost;
279         }
280
281         /**
282          * Set MyZkHost - Zookeeper Hostname
283          * 
284          * @param myZkHost
285          */
286         public static void setMyZkHost(String myZkHost) {
287                 MusicUtil.myZkHost = myZkHost;
288         }
289
290         /**
291          * Get MyCassHost - Cassandra Hostname - Default = localhost property file
292          * value - cassandra.host
293          * 
294          * @return
295          */
296         public static String getMyCassaHost() {
297                 return myCassaHost;
298         }
299
300         /**
301          * Set MyCassHost - Cassandra Hostname
302          * 
303          * @param myCassaHost
304          */
305         public static void setMyCassaHost(String myCassaHost) {
306                 MusicUtil.myCassaHost = myCassaHost;
307         }
308
309         /**
310          * Get DefaultMusicIp - Default = localhost property file value - music.ip
311          * 
312          * @return
313          */
314         public static String getDefaultMusicIp() {
315                 return defaultMusicIp;
316         }
317
318         /**
319          * Set DefaultMusicIp
320          * 
321          * @param defaultMusicIp
322          */
323         public static void setDefaultMusicIp(String defaultMusicIp) {
324                 MusicUtil.defaultMusicIp = defaultMusicIp;
325         }
326
327         /**
328          * 
329          * @return
330          */
331         public static String getTestType() {
332                 String testType = "";
333                 try {
334                         Scanner fileScanner = new Scanner(new File(""));
335                         testType = fileScanner.next();// ignore the my id line
336                         String batchSize = fileScanner.next();// ignore the my public ip
337                                                                                                         // line
338                         fileScanner.close();
339                 } catch (FileNotFoundException e) {
340                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
341                 }
342                 return testType;
343
344         }
345
346         /**
347          * 
348          * @param time
349          */
350         public static void sleep(long time) {
351                 try {
352                         Thread.sleep(time);
353                 } catch (InterruptedException e) {
354                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
355                 }
356         }
357
358         /**
359          * Utility function to check if the query object is valid.
360          * 
361          * @param withparams
362          * @param queryObject
363          * @return
364          */
365         public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
366                 if (withparams) {
367                         int noOfValues = queryObject.getValues().size();
368                         int noOfParams = 0;
369                         char[] temp = queryObject.getQuery().toCharArray();
370                         for (int i = 0; i < temp.length; i++) {
371                                 if (temp[i] == '?')
372                                         noOfParams++;
373                         }
374                         return (noOfValues == noOfParams);
375                 } else {
376                         return !queryObject.getQuery().isEmpty();
377                 }
378
379         }
380
381         public static void setCassName(String cassName) {
382                 MusicUtil.cassName = cassName;
383         }
384
385         public static void setCassPwd(String cassPwd) {
386                 MusicUtil.cassPwd = cassPwd;
387         }
388
389         public static String convertToCQLDataType(DataType type, Object valueObj) {
390
391                 String value = "";
392                 switch (type.getName()) {
393                 case UUID:
394                         value = valueObj + "";
395                         break;
396                 case TEXT:
397                 case VARCHAR:
398                         String valueString = valueObj + "";
399                         valueString = valueString.replace("'", "''");
400                         value = "'" + valueString + "'";
401                         break;
402                 case MAP: {
403                         Map<String, Object> otMap = (Map<String, Object>) valueObj;
404                         value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
405                         break;
406                 }
407                 default:
408                         value = valueObj + "";
409                         break;
410                 }
411                 return value;
412         }
413
414         /**
415          * 
416          * @param colType
417          * @param valueObj
418          * @return
419          * @throws Exception
420          */
421         public static Object convertToActualDataType(DataType colType, Object valueObj) {
422                 String valueObjString = valueObj + "";
423                 switch (colType.getName()) {
424                 case UUID:
425                         return UUID.fromString(valueObjString);
426                 case VARINT:
427                         return BigInteger.valueOf(Long.parseLong(valueObjString));
428                 case BIGINT:
429                         return Long.parseLong(valueObjString);
430                 case INT:
431                         return Integer.parseInt(valueObjString);
432                 case FLOAT:
433                         return Float.parseFloat(valueObjString);
434                 case DOUBLE:
435                         return Double.parseDouble(valueObjString);
436                 case BOOLEAN:
437                         return Boolean.parseBoolean(valueObjString);
438                 case MAP:
439                         return (Map<String, Object>) valueObj;
440                 default:
441                         return valueObjString;
442                 }
443         }
444
445         /**
446          *
447          * Utility function to parse json map into sql like string
448          * 
449          * @param jMap
450          * @param lineDelimiter
451          * @return
452          */
453
454         public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) {
455                 StringBuilder sqlString = new StringBuilder();
456                 int counter = 0;
457                 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
458                         Object ot = entry.getValue();
459                         String value = ot + "";
460                         if (ot instanceof String) {
461                                 value = "'" + value.replace("'", "''") + "'";
462                         }
463                         sqlString.append("'" + entry.getKey() + "':" + value);
464                         if (counter != jMap.size() - 1)
465                                 sqlString.append(lineDelimiter);
466                         counter = counter + 1;
467                 }
468                 return sqlString.toString();
469         }
470
471         public static Map<String, HashMap<String, Object>> setErrorResponse(MusicServiceException ex) {
472                 Map<String, HashMap<String, Object>> results = new HashMap<>();
473                 HashMap<String, Object> tempMap = new HashMap<>();
474                 Map<String, Object> result = new HashMap<>();
475                 result.put("error-description", ex.getMessage());
476                 tempMap.put("error", result);
477                 results.put("result", tempMap);
478                 return results;
479         }
480 }