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.math.BigInteger;
27 import java.nio.ByteBuffer;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
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;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.Response.ResponseBuilder;
41 import org.onap.music.datastore.PreparedQueryObject;
42 import org.onap.music.eelf.logging.EELFLoggerDelegate;
44 import com.datastax.driver.core.DataType;
45 import com.sun.jersey.core.util.Base64;
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
55 public class MusicUtil {
56 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
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";
74 private static final String LOCALHOST = "localhost";
75 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
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" };
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<>();
99 throw new IllegalStateException("Utility Class");
104 * @return the cassName
106 public static String getCassName() {
111 * @return the cassPwd
113 public static String getCassPwd() {
118 * @return the aafEndpointUrl
120 public static String getAafEndpointUrl() {
121 return aafEndpointUrl;
126 * @param aafEndpointUrl
128 public static void setAafEndpointUrl(String aafEndpointUrl) {
129 MusicUtil.aafEndpointUrl = aafEndpointUrl;
136 public static int getMyId() {
144 public static void setMyId(int myId) {
145 MusicUtil.myId = myId;
152 public static List<String> getAllIds() {
160 public static void setAllIds(List<String> allIds) {
161 MusicUtil.allIds = (ArrayList<String>) allIds;
168 public static String getPublicIp() {
176 public static void setPublicIp(String publicIp) {
177 MusicUtil.publicIp = publicIp;
184 public static List<String> getAllPublicIps() {
190 * @param allPublicIps
192 public static void setAllPublicIps(List<String> allPublicIps) {
193 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
197 * Returns An array of property names that should be in the Properties
202 public static String[] getPropkeys() {
207 * Get MusicRestIp - default = localhost property file value - music.rest.ip
211 public static String getMusicRestIp() {
220 public static void setMusicRestIp(String musicRestIp) {
221 MusicUtil.musicRestIp = musicRestIp;
225 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
226 * property file value - music.properties
230 public static String getMusicPropertiesFilePath() {
231 return musicPropertiesFilePath;
235 * Set MusicPropertiesFilePath
237 * @param musicPropertiesFilePath
239 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
240 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
244 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
249 public static long getDefaultLockLeasePeriod() {
250 return defaultLockLeasePeriod;
254 * Set DefaultLockLeasePeriod
256 * @param defaultLockLeasePeriod
258 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
259 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
267 public static void setDebug(boolean debug) {
268 MusicUtil.debug = debug;
272 * Is Debug - Default = true property file value - debug
276 public static boolean isDebug() {
285 public static void setVersion(String version) {
286 MusicUtil.version = version;
290 * Return the version property file value - version
294 public static String getVersion() {
299 * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
300 * value - zookeeper.host
304 public static String getMyZkHost() {
309 * Set MyZkHost - Zookeeper Hostname
313 public static void setMyZkHost(String myZkHost) {
314 MusicUtil.myZkHost = myZkHost;
318 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
319 * value - cassandra.host
323 public static String getMyCassaHost() {
328 * Set MyCassHost - Cassandra Hostname
332 public static void setMyCassaHost(String myCassaHost) {
333 MusicUtil.myCassaHost = myCassaHost;
337 * Get DefaultMusicIp - Default = localhost property file value - music.ip
341 public static String getDefaultMusicIp() {
342 return defaultMusicIp;
348 * @param defaultMusicIp
350 public static void setDefaultMusicIp(String defaultMusicIp) {
351 MusicUtil.defaultMusicIp = defaultMusicIp;
358 public static String getTestType() {
359 String testType = "";
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
367 } catch (FileNotFoundException e) {
368 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
378 public static void sleep(long time) {
381 } catch (InterruptedException e) {
382 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
383 Thread.currentThread().interrupt();
388 * Utility function to check if the query object is valid.
394 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
396 int noOfValues = queryObject.getValues().size();
398 char[] temp = queryObject.getQuery().toCharArray();
399 for (int i = 0; i < temp.length; i++) {
403 return (noOfValues == noOfParams);
405 return !queryObject.getQuery().isEmpty();
410 public static void setCassName(String cassName) {
411 MusicUtil.cassName = cassName;
414 public static void setCassPwd(String cassPwd) {
415 MusicUtil.cassPwd = cassPwd;
418 @SuppressWarnings("unchecked")
419 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
422 switch (type.getName()) {
424 value = valueObj + "";
428 String valueString = valueObj + "";
429 valueString = valueString.replace("'", "''");
430 value = "'" + valueString + "'";
433 Map<String, Object> otMap = (Map<String, Object>) valueObj;
434 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
438 value = valueObj + "";
449 * @throws MusicTypeConversionException
452 @SuppressWarnings("unchecked")
453 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
454 String valueObjString = valueObj + "";
455 switch (colType.getName()) {
457 return UUID.fromString(valueObjString);
459 return BigInteger.valueOf(Long.parseLong(valueObjString));
461 return Long.parseLong(valueObjString);
463 return Integer.parseInt(valueObjString);
465 return Float.parseFloat(valueObjString);
467 return Double.parseDouble(valueObjString);
469 return Boolean.parseBoolean(valueObjString);
471 return (Map<String, Object>) valueObj;
475 return valueObjString;
479 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
480 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
486 * Utility function to parse json map into sql like string
489 * @param lineDelimiter
493 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
494 StringBuilder sqlString = new StringBuilder();
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("'", "''") + "'";
502 sqlString.append("'" + entry.getKey() + "':" + value);
503 if (counter != jMap.size() - 1)
504 sqlString.append(lineDelimiter);
505 counter = counter + 1;
507 return sqlString.toString();
510 @SuppressWarnings("unused")
511 public static String buildVersion(String major, String minor, String patch) {
513 major += "." + minor;
515 major += "." + patch;
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.
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);
541 response.header(XMINORVERSION,verArray[1]);
543 if ( patch != null ) {
544 response.header(XPATCHVERSION,patch);
546 response.header(XPATCHVERSION,verArray[2]);
548 response.header(XLATESTVERSION,version);
549 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
554 public static Map<String,String> extractBasicAuthentication(String authorization){
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());