2 * ============LICENSE_START==========================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * ============LICENSE_END=============================================
20 * ====================================================================
22 package org.onap.music.main;
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;
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;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.ResponseBuilder;
44 import org.onap.music.datastore.PreparedQueryObject;
45 import org.onap.music.eelf.logging.EELFLoggerDelegate;
47 import com.datastax.driver.core.DataType;
48 import com.sun.jersey.core.util.Base64;
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
58 public class MusicUtil {
59 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
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";
76 public static final String AUTHORIZATION = "Authorization";
78 private static final String LOCALHOST = "localhost";
79 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
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;
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" };
101 private static String cassName = "cassandra";
102 private static String cassPwd;
103 private static String aafEndpointUrl = null;
104 public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
106 private MusicUtil() {
107 throw new IllegalStateException("Utility Class");
111 * @return cassandra port
113 public static int getCassandraPort() {
114 return cassandraPort;
119 * @param cassandraPort
121 public static void setCassandraPort(int cassandraPort) {
122 MusicUtil.cassandraPort = cassandraPort;
125 * @return the cassName
127 public static String getCassName() {
132 * @return the cassPwd
134 public static String getCassPwd() {
139 * @return the aafEndpointUrl
141 public static String getAafEndpointUrl() {
142 return aafEndpointUrl;
147 * @param aafEndpointUrl
149 public static void setAafEndpointUrl(String aafEndpointUrl) {
150 MusicUtil.aafEndpointUrl = aafEndpointUrl;
157 public static int getMyId() {
165 public static void setMyId(int myId) {
166 MusicUtil.myId = myId;
173 public static List<String> getAllIds() {
181 public static void setAllIds(List<String> allIds) {
182 MusicUtil.allIds = (ArrayList<String>) allIds;
189 public static String getPublicIp() {
197 public static void setPublicIp(String publicIp) {
198 MusicUtil.publicIp = publicIp;
205 public static List<String> getAllPublicIps() {
211 * @param allPublicIps
213 public static void setAllPublicIps(List<String> allPublicIps) {
214 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
218 * Returns An array of property names that should be in the Properties
223 public static String[] getPropkeys() {
228 * Get MusicRestIp - default = localhost property file value - music.rest.ip
232 public static String getMusicRestIp() {
241 public static void setMusicRestIp(String musicRestIp) {
242 MusicUtil.musicRestIp = musicRestIp;
246 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
247 * property file value - music.properties
251 public static String getMusicPropertiesFilePath() {
252 return musicPropertiesFilePath;
256 * Set MusicPropertiesFilePath
258 * @param musicPropertiesFilePath
260 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
261 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
265 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
270 public static long getDefaultLockLeasePeriod() {
271 return defaultLockLeasePeriod;
275 * Set DefaultLockLeasePeriod
277 * @param defaultLockLeasePeriod
279 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
280 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
288 public static void setDebug(boolean debug) {
289 MusicUtil.debug = debug;
293 * Is Debug - Default = true property file value - debug
297 public static boolean isDebug() {
306 public static void setVersion(String version) {
307 MusicUtil.version = version;
311 * Return the version property file value - version
315 public static String getVersion() {
320 * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
321 * value - zookeeper.host
325 public static String getMyZkHost() {
330 * Set MyZkHost - Zookeeper Hostname
334 public static void setMyZkHost(String myZkHost) {
335 MusicUtil.myZkHost = myZkHost;
339 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
340 * value - cassandra.host
344 public static String getMyCassaHost() {
349 * Set MyCassHost - Cassandra Hostname
353 public static void setMyCassaHost(String myCassaHost) {
354 MusicUtil.myCassaHost = myCassaHost;
358 * Get DefaultMusicIp - Default = localhost property file value - music.ip
362 public static String getDefaultMusicIp() {
363 return defaultMusicIp;
369 * @param defaultMusicIp
371 public static void setDefaultMusicIp(String defaultMusicIp) {
372 MusicUtil.defaultMusicIp = defaultMusicIp;
379 public static String getTestType() {
380 String testType = "";
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
388 } catch (FileNotFoundException e) {
389 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
399 public static void sleep(long time) {
402 } catch (InterruptedException e) {
403 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
404 Thread.currentThread().interrupt();
409 * Utility function to check if the query object is valid.
415 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
417 int noOfValues = queryObject.getValues().size();
419 char[] temp = queryObject.getQuery().toCharArray();
420 for (int i = 0; i < temp.length; i++) {
424 return (noOfValues == noOfParams);
426 return !queryObject.getQuery().isEmpty();
431 public static void setCassName(String cassName) {
432 MusicUtil.cassName = cassName;
435 public static void setCassPwd(String cassPwd) {
436 MusicUtil.cassPwd = cassPwd;
439 @SuppressWarnings("unchecked")
440 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
443 switch (type.getName()) {
445 value = valueObj + "";
449 String valueString = valueObj + "";
450 valueString = valueString.replace("'", "''");
451 value = "'" + valueString + "'";
454 Map<String, Object> otMap = (Map<String, Object>) valueObj;
455 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
459 value = valueObj + "";
470 * @throws MusicTypeConversionException
473 @SuppressWarnings("unchecked")
474 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
475 String valueObjString = valueObj + "";
476 switch (colType.getName()) {
478 return UUID.fromString(valueObjString);
480 return BigInteger.valueOf(Long.parseLong(valueObjString));
482 return Long.parseLong(valueObjString);
484 return Integer.parseInt(valueObjString);
486 return Float.parseFloat(valueObjString);
488 return Double.parseDouble(valueObjString);
490 return Boolean.parseBoolean(valueObjString);
492 return (Map<String, Object>) valueObj;
496 return valueObjString;
500 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
501 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
507 * Utility function to parse json map into sql like string
510 * @param lineDelimiter
514 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
515 StringBuilder sqlString = new StringBuilder();
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("'", "''") + "'";
523 sqlString.append("'" + entry.getKey() + "':" + value);
524 if (counter != jMap.size() - 1)
525 sqlString.append(lineDelimiter);
526 counter = counter + 1;
528 return sqlString.toString();
531 @SuppressWarnings("unused")
532 public static String buildVersion(String major, String minor, String patch) {
534 major += "." + minor;
536 major += "." + patch;
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.
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);
562 response.header(XMINORVERSION,verArray[1]);
564 if ( patch != null ) {
565 response.header(XPATCHVERSION,patch);
567 response.header(XPATCHVERSION,verArray[2]);
569 response.header(XLATESTVERSION,version);
570 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
575 public static Map<String,String> extractBasicAuthentication(String authorization){
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());
587 public static void loadProperties() throws Exception {
588 Properties prop = new Properties();
589 InputStream input = null;
591 // load the properties file
592 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
594 } catch (Exception ex) {
595 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
596 throw new Exception();
601 } catch (IOException e) {
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")));
618 public static void setNotifyInterval(int notifyinterval) {
619 MusicUtil.notifyinterval = notifyinterval;
621 public static void setNotifyTimeOut(int notifytimeout) {
622 MusicUtil.notifytimeout = notifytimeout;
625 public static int getNotifyInterval() {
626 return MusicUtil.notifyinterval;
629 public static int getNotifyTimeout() {
630 return MusicUtil.notifytimeout;