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