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;
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" };
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<>();
104 private MusicUtil() {
105 throw new IllegalStateException("Utility Class");
109 * @return cassandra port
111 public static int getCassandraPort() {
112 return cassandraPort;
117 * @param cassandraPort
119 public static void setCassandraPort(int cassandraPort) {
120 MusicUtil.cassandraPort = cassandraPort;
123 * @return the cassName
125 public static String getCassName() {
130 * @return the cassPwd
132 public static String getCassPwd() {
137 * @return the aafEndpointUrl
139 public static String getAafEndpointUrl() {
140 return aafEndpointUrl;
145 * @param aafEndpointUrl
147 public static void setAafEndpointUrl(String aafEndpointUrl) {
148 MusicUtil.aafEndpointUrl = aafEndpointUrl;
155 public static int getMyId() {
163 public static void setMyId(int myId) {
164 MusicUtil.myId = myId;
171 public static List<String> getAllIds() {
179 public static void setAllIds(List<String> allIds) {
180 MusicUtil.allIds = (ArrayList<String>) allIds;
187 public static String getPublicIp() {
195 public static void setPublicIp(String publicIp) {
196 MusicUtil.publicIp = publicIp;
203 public static List<String> getAllPublicIps() {
209 * @param allPublicIps
211 public static void setAllPublicIps(List<String> allPublicIps) {
212 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
216 * Returns An array of property names that should be in the Properties
221 public static String[] getPropkeys() {
226 * Get MusicRestIp - default = localhost property file value - music.rest.ip
230 public static String getMusicRestIp() {
239 public static void setMusicRestIp(String musicRestIp) {
240 MusicUtil.musicRestIp = musicRestIp;
244 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
245 * property file value - music.properties
249 public static String getMusicPropertiesFilePath() {
250 return musicPropertiesFilePath;
254 * Set MusicPropertiesFilePath
256 * @param musicPropertiesFilePath
258 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
259 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
263 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
268 public static long getDefaultLockLeasePeriod() {
269 return defaultLockLeasePeriod;
273 * Set DefaultLockLeasePeriod
275 * @param defaultLockLeasePeriod
277 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
278 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
286 public static void setDebug(boolean debug) {
287 MusicUtil.debug = debug;
291 * Is Debug - Default = true property file value - debug
295 public static boolean isDebug() {
304 public static void setVersion(String version) {
305 MusicUtil.version = version;
309 * Return the version property file value - version
313 public static String getVersion() {
318 * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
319 * value - zookeeper.host
323 public static String getMyZkHost() {
328 * Set MyZkHost - Zookeeper Hostname
332 public static void setMyZkHost(String myZkHost) {
333 MusicUtil.myZkHost = myZkHost;
337 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
338 * value - cassandra.host
342 public static String getMyCassaHost() {
347 * Set MyCassHost - Cassandra Hostname
351 public static void setMyCassaHost(String myCassaHost) {
352 MusicUtil.myCassaHost = myCassaHost;
356 * Get DefaultMusicIp - Default = localhost property file value - music.ip
360 public static String getDefaultMusicIp() {
361 return defaultMusicIp;
367 * @param defaultMusicIp
369 public static void setDefaultMusicIp(String defaultMusicIp) {
370 MusicUtil.defaultMusicIp = defaultMusicIp;
377 public static String getTestType() {
378 String testType = "";
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
386 } catch (FileNotFoundException e) {
387 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
397 public static void sleep(long time) {
400 } catch (InterruptedException e) {
401 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
402 Thread.currentThread().interrupt();
407 * Utility function to check if the query object is valid.
413 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
415 int noOfValues = queryObject.getValues().size();
417 char[] temp = queryObject.getQuery().toCharArray();
418 for (int i = 0; i < temp.length; i++) {
422 return (noOfValues == noOfParams);
424 return !queryObject.getQuery().isEmpty();
429 public static void setCassName(String cassName) {
430 MusicUtil.cassName = cassName;
433 public static void setCassPwd(String cassPwd) {
434 MusicUtil.cassPwd = cassPwd;
437 @SuppressWarnings("unchecked")
438 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
441 switch (type.getName()) {
443 value = valueObj + "";
447 String valueString = valueObj + "";
448 valueString = valueString.replace("'", "''");
449 value = "'" + valueString + "'";
452 Map<String, Object> otMap = (Map<String, Object>) valueObj;
453 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
457 value = valueObj + "";
468 * @throws MusicTypeConversionException
471 @SuppressWarnings("unchecked")
472 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
473 String valueObjString = valueObj + "";
474 switch (colType.getName()) {
476 return UUID.fromString(valueObjString);
478 return BigInteger.valueOf(Long.parseLong(valueObjString));
480 return Long.parseLong(valueObjString);
482 return Integer.parseInt(valueObjString);
484 return Float.parseFloat(valueObjString);
486 return Double.parseDouble(valueObjString);
488 return Boolean.parseBoolean(valueObjString);
490 return (Map<String, Object>) valueObj;
494 return valueObjString;
498 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
499 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
505 * Utility function to parse json map into sql like string
508 * @param lineDelimiter
512 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
513 StringBuilder sqlString = new StringBuilder();
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("'", "''") + "'";
521 sqlString.append("'" + entry.getKey() + "':" + value);
522 if (counter != jMap.size() - 1)
523 sqlString.append(lineDelimiter);
524 counter = counter + 1;
526 return sqlString.toString();
529 @SuppressWarnings("unused")
530 public static String buildVersion(String major, String minor, String patch) {
532 major += "." + minor;
534 major += "." + patch;
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.
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);
560 response.header(XMINORVERSION,verArray[1]);
562 if ( patch != null ) {
563 response.header(XPATCHVERSION,patch);
565 response.header(XPATCHVERSION,verArray[2]);
567 response.header(XLATESTVERSION,version);
568 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
573 public static Map<String,String> extractBasicAuthentication(String authorization){
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());
585 public static void loadProperties() throws Exception {
586 Properties prop = new Properties();
587 InputStream input = null;
589 // load the properties file
590 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
592 } catch (Exception ex) {
593 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
594 throw new Exception();
599 } catch (IOException e) {
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")));