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