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