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