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