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