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