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