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 * ====================================================================
23 package org.onap.music.main;
26 import java.io.FileNotFoundException;
27 import java.math.BigInteger;
28 import java.util.ArrayList;
29 import java.util.List;
31 import java.util.Scanner;
32 import java.util.UUID;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.Response.ResponseBuilder;
35 import org.onap.music.datastore.PreparedQueryObject;
36 import org.onap.music.eelf.logging.EELFLoggerDelegate;
37 import com.datastax.driver.core.DataType;
39 import java.io.FileNotFoundException;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.util.Properties;
48 * Properties This will take Properties and load them into MusicUtil.
49 * This is a hack for now. Eventually it would bebest to do this in
53 public class MusicUtil {
54 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
56 public static final String ATOMIC = "atomic";
57 public static final String EVENTUAL = "eventual";
58 public static final String CRITICAL = "critical";
59 public static final String ATOMICDELETELOCK = "atomic_delete_lock";
60 public static final String DEFAULTKEYSPACENAME = "TBD";
61 private static final String XLATESTVERSION = "X-latestVersion";
62 private static final String XMINORVERSION = "X-minorVersion";
63 private static final String XPATCHVERSION = "X-patchVersion";
65 private static final String LOCALHOST = "localhost";
66 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
68 private static int myId = 0;
69 private static ArrayList<String> allIds = new ArrayList<>();
70 private static String publicIp = "";
71 private static ArrayList<String> allPublicIps = new ArrayList<>();
72 private static String myZkHost = LOCALHOST;
73 private static String myCassaHost = LOCALHOST;
74 private static String defaultMusicIp = LOCALHOST;
75 private static boolean debug = true;
76 private static String version = "2.3.0";
77 private static String musicRestIp = LOCALHOST;
78 private static String musicPropertiesFilePath = PROPERTIES_FILE;
79 private static long defaultLockLeasePeriod = 6000;
80 private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
81 "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
82 "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" };
84 private static String cassName = "cassandra";
85 private static String cassPwd = "cassandra";
86 private static String aafEndpointUrl = null;
87 private static int cassandraPort = 9042;
90 throw new IllegalStateException("Utility Class");
95 * @return the cassName
97 public static String getCassName() {
102 * @return the cassPwd
104 public static String getCassPwd() {
109 * @return the aafEndpointUrl
111 public static String getAafEndpointUrl() {
112 return aafEndpointUrl;
117 * @param aafEndpointUrl
119 public static void setAafEndpointUrl(String aafEndpointUrl) {
120 MusicUtil.aafEndpointUrl = aafEndpointUrl;
127 public static int getMyId() {
135 public static void setMyId(int myId) {
136 MusicUtil.myId = myId;
143 public static List<String> getAllIds() {
151 public static void setAllIds(List<String> allIds) {
152 MusicUtil.allIds = (ArrayList<String>) allIds;
159 public static String getPublicIp() {
167 public static void setPublicIp(String publicIp) {
168 MusicUtil.publicIp = publicIp;
175 public static List<String> getAllPublicIps() {
181 * @param allPublicIps
183 public static void setAllPublicIps(List<String> allPublicIps) {
184 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
188 * Returns An array of property names that should be in the Properties
193 public static String[] getPropkeys() {
198 * Get MusicRestIp - default = localhost property file value - music.rest.ip
202 public static String getMusicRestIp() {
211 public static void setMusicRestIp(String musicRestIp) {
212 MusicUtil.musicRestIp = musicRestIp;
216 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
217 * property file value - music.properties
221 public static String getMusicPropertiesFilePath() {
222 return musicPropertiesFilePath;
226 * Set MusicPropertiesFilePath
228 * @param musicPropertiesFilePath
230 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
231 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
235 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
240 public static long getDefaultLockLeasePeriod() {
241 return defaultLockLeasePeriod;
245 * Set DefaultLockLeasePeriod
247 * @param defaultLockLeasePeriod
249 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
250 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
258 public static void setDebug(boolean debug) {
259 MusicUtil.debug = debug;
263 * Is Debug - Default = true property file value - debug
267 public static boolean isDebug() {
276 public static void setVersion(String version) {
277 MusicUtil.version = version;
281 * Return the version property file value - version
285 public static String getVersion() {
290 * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
291 * value - zookeeper.host
295 public static String getMyZkHost() {
300 * Set MyZkHost - Zookeeper Hostname
304 public static void setMyZkHost(String myZkHost) {
305 MusicUtil.myZkHost = myZkHost;
309 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
310 * value - cassandra.host
314 public static String getMyCassaHost() {
319 * Set MyCassHost - Cassandra Hostname
323 public static void setMyCassaHost(String myCassaHost) {
324 MusicUtil.myCassaHost = myCassaHost;
328 * Get DefaultMusicIp - Default = localhost property file value - music.ip
332 public static String getDefaultMusicIp() {
333 return defaultMusicIp;
339 * @param defaultMusicIp
341 public static void setDefaultMusicIp(String defaultMusicIp) {
342 MusicUtil.defaultMusicIp = defaultMusicIp;
347 * @return cassandra port
349 public static int getCassandraPort() {
350 return cassandraPort;
355 * @param cassandraPort
357 public static void setCassandraPort(int cassandraPort) {
358 MusicUtil.cassandraPort = cassandraPort;
364 public static String getTestType() {
365 String testType = "";
367 Scanner fileScanner = new Scanner(new File(""));
368 testType = fileScanner.next();// ignore the my id line
369 String batchSize = fileScanner.next();// ignore the my public ip
372 } catch (FileNotFoundException e) {
373 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
383 public static void sleep(long time) {
386 } catch (InterruptedException e) {
387 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
388 Thread.currentThread().interrupt();
393 * Utility function to check if the query object is valid.
399 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
401 int noOfValues = queryObject.getValues().size();
403 char[] temp = queryObject.getQuery().toCharArray();
404 for (int i = 0; i < temp.length; i++) {
408 return (noOfValues == noOfParams);
410 return !queryObject.getQuery().isEmpty();
415 public static void setCassName(String cassName) {
416 MusicUtil.cassName = cassName;
419 public static void setCassPwd(String cassPwd) {
420 MusicUtil.cassPwd = cassPwd;
423 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
426 switch (type.getName()) {
428 value = valueObj + "";
432 String valueString = valueObj + "";
433 valueString = valueString.replace("'", "''");
434 value = "'" + valueString + "'";
437 Map<String, Object> otMap = (Map<String, Object>) valueObj;
438 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
442 value = valueObj + "";
453 * @throws MusicTypeConversionException
456 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
457 String valueObjString = valueObj + "";
458 switch (colType.getName()) {
460 return UUID.fromString(valueObjString);
462 return BigInteger.valueOf(Long.parseLong(valueObjString));
464 return Long.parseLong(valueObjString);
466 return Integer.parseInt(valueObjString);
468 return Float.parseFloat(valueObjString);
470 return Double.parseDouble(valueObjString);
472 return Boolean.parseBoolean(valueObjString);
474 return (Map<String, Object>) valueObj;
476 return valueObjString;
482 * Utility function to parse json map into sql like string
485 * @param lineDelimiter
489 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
490 StringBuilder sqlString = new StringBuilder();
492 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
493 Object ot = entry.getValue();
494 String value = ot + "";
495 if (ot instanceof String) {
496 value = "'" + value.replace("'", "''") + "'";
498 sqlString.append("'" + entry.getKey() + "':" + value);
499 if (counter != jMap.size() - 1)
500 sqlString.append(lineDelimiter);
501 counter = counter + 1;
503 return sqlString.toString();
506 @SuppressWarnings("unused")
507 public static String buildVersion(String major, String minor, String patch) {
509 major += "." + minor;
511 major += "." + patch;
518 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
519 * X-latestVerstion will be equal to the latest full version.
520 * X-minorVersion - will be equal to the latest minor version.
521 * X-pathVersion - will be equal to the latest patch version.
522 * Future plans will change this.
529 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
530 ResponseBuilder response = Response.noContent();
531 String versionIn = buildVersion(major,minor,patch);
532 String version = MusicUtil.getVersion();
533 String[] verArray = version.split("\\.",3);
534 if ( minor != null ) {
535 response.header(XMINORVERSION,minor);
537 response.header(XMINORVERSION,verArray[1]);
539 if ( patch != null ) {
540 response.header(XPATCHVERSION,patch);
542 response.header(XPATCHVERSION,verArray[2]);
544 response.header(XLATESTVERSION,version);
545 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
550 public static void loadProperties() throws Exception {
551 CipherUtil.readAndSetKeyString();
552 Properties prop = new Properties();
553 InputStream input = null;
555 // load the properties file
556 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
558 } catch (Exception ex) {
559 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
560 throw new Exception();
565 } catch (IOException e) {
570 String cassPwd = prop.getProperty("cassandra.password");
571 String isEncrypted = prop.getProperty("cassandra.password.isencrypted");
572 if("true".equals(isEncrypted)) {
573 logger.debug(EELFLoggerDelegate.applicationLogger,"Decrypting....");
574 cassPwd = CipherUtil.decryptPKC(cassPwd);
575 logger.debug(EELFLoggerDelegate.applicationLogger,"Password Decrypted");
576 MusicUtil.setCassPwd(cassPwd);
578 MusicUtil.setCassPwd(cassPwd);
579 // get the property value and return it
580 MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
581 String zkHosts = prop.getProperty("zookeeper.host");
582 MusicUtil.setMyZkHost(zkHosts);
583 MusicUtil.setCassName(prop.getProperty("cassandra.user"));
584 String cassPort = prop.getProperty("cassandra.port");
586 MusicUtil.setCassandraPort(Integer.parseInt(cassPort));