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