2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2019 IBM.
8 * Modifications Copyright (c) 2019 Samsung.
9 * ===================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
22 * ============LICENSE_END=============================================
23 * ====================================================================
26 package org.onap.music.main;
28 import com.datastax.driver.core.ColumnDefinitions;
29 import com.datastax.driver.core.ColumnDefinitions.Definition;
30 import com.datastax.driver.core.ResultSet;
31 import com.datastax.driver.core.Row;
33 import java.io.FileNotFoundException;
34 import java.math.BigInteger;
35 import java.nio.ByteBuffer;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Scanner;
40 import java.util.UUID;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.Response.ResponseBuilder;
44 import org.onap.music.datastore.MusicDataStoreHandle;
45 import org.onap.music.datastore.PreparedQueryObject;
46 import org.onap.music.eelf.logging.EELFLoggerDelegate;
47 import org.onap.music.eelf.logging.format.AppMessages;
48 import org.onap.music.eelf.logging.format.ErrorSeverity;
49 import org.onap.music.eelf.logging.format.ErrorTypes;
50 import org.onap.music.exceptions.MusicQueryException;
51 import org.onap.music.exceptions.MusicServiceException;
52 import org.onap.music.service.MusicCoreService;
53 import org.onap.music.service.impl.MusicCassaCore;
55 import com.datastax.driver.core.ConsistencyLevel;
56 import com.datastax.driver.core.DataType;
61 * Properties This will take Properties and load them into MusicUtil.
62 * This is a hack for now. Eventually it would bebest to do this in
66 public class MusicUtil {
67 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
69 // Consistancy Constants
70 public static final String ATOMIC = "atomic";
71 public static final String EVENTUAL = "eventual";
72 public static final String CRITICAL = "critical";
73 public static final String EVENTUAL_NB = "eventual_nb";
74 public static final String ALL = "all";
75 public static final String QUORUM = "quorum";
76 public static final String LOCAL_QUORUM = "local_quorum";
77 public static final String ONE = "one";
78 public static final String ATOMICDELETELOCK = "atomic_delete_lock";
81 private static final String XLATESTVERSION = "X-latestVersion";
82 private static final String XMINORVERSION = "X-minorVersion";
83 private static final String XPATCHVERSION = "X-patchVersion";
84 public static final String AUTHORIZATION = "Authorization";
87 public static final String SELECT = "select";
88 public static final String INSERT = "insert";
89 public static final String UPDATE = "update";
90 public static final String UPSERT = "upsert";
91 public static final String USERID = "userId";
92 public static final String PASSWORD = "";
93 public static final String CASSANDRA = "cassandra";
95 private static final String LOCALHOST = "localhost";
96 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
97 public static final String DEFAULTKEYSPACENAME = "TBD";
99 private static long defaultLockLeasePeriod = 6000;
100 // Amount of times to retry to delete a lock in atomic.
101 private static int retryCount = 3;
102 private static String lockUsing = MusicUtil.CASSANDRA;
104 private static boolean isCadi = false;
105 // Keyspace Creation on/off
106 private static boolean isKeyspaceActive = false;
107 private static boolean debug = true;
108 private static String version = "0.0.0";
109 private static String build = "";
111 private static String musicPropertiesFilePath = PROPERTIES_FILE;
112 // private static final String[] propKeys = new String[] { MusicUtil.class.getDeclaredMethod(arg0, )"build","cassandra.host", "debug",
113 // "version", "music.properties", "lock.lease.period", "cassandra.user",
114 // "cassandra.password", "aaf.endpoint.url","admin.username","admin.password",
115 // "music.namespace","admin.aaf.role","cassandra.port","lock.using","retry.count",
116 // "transId.header.required","conversation.header.required","clientId.header.required",
117 // "messageId.header.required","transId.header.prefix","conversation.header.prefix",
118 // "clientId.header.prefix","messageId.header.prefix"};
119 // Consistency Constants and variables.
120 private static final String[] cosistencyLevel = new String[] {
121 "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO",
122 "THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
123 private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
125 consistencyName.put("ONE",ConsistencyLevel.ONE);
126 consistencyName.put("TWO",ConsistencyLevel.TWO);
127 consistencyName.put("THREE",ConsistencyLevel.THREE);
128 consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
129 consistencyName.put("ALL",ConsistencyLevel.ALL);
130 consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
131 consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
132 consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
133 consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
134 consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
138 private static String cassName = "cassandra";
139 private static String cassPwd;
140 private static String myCassaHost = LOCALHOST;
141 private static int cassandraPort = 9042;
144 private static String musicAafNs = "org.onap.music.cadi";
147 public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
148 public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
149 public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
151 // Response/Request tracking headers
152 private static String transIdPrefix = "false";
153 private static String conversationIdPrefix = "false";
154 private static String clientIdPrefix = "false";
155 private static String messageIdPrefix = "false";
156 private static Boolean transIdRequired = false;
157 private static Boolean conversationIdRequired = false;
158 private static Boolean clientIdRequired = false;
159 private static Boolean messageIdRequired = false;
160 private static String cipherEncKey = "";
163 throw new IllegalStateException("Utility Class");
166 public static String getLockUsing() {
170 public static void setLockUsing(String lockUsing) {
171 MusicUtil.lockUsing = lockUsing;
176 * @return cassandra port
178 public static int getCassandraPort() {
179 return cassandraPort;
184 * @param cassandraPort
186 public static void setCassandraPort(int cassandraPort) {
187 MusicUtil.cassandraPort = cassandraPort;
190 * @return the cassName
192 public static String getCassName() {
197 * @return the cassPwd
199 public static String getCassPwd() {
204 * Returns An array of property names that should be in the Properties
209 // public static String[] getPropkeys() {
210 // return propKeys.clone();
214 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
215 * property file value - music.properties
219 public static String getMusicPropertiesFilePath() {
220 return musicPropertiesFilePath;
224 * Set MusicPropertiesFilePath
226 * @param musicPropertiesFilePath
228 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
229 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
233 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
238 public static long getDefaultLockLeasePeriod() {
239 return defaultLockLeasePeriod;
243 * Set DefaultLockLeasePeriod
245 * @param defaultLockLeasePeriod
247 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
248 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
256 public static void setDebug(boolean debug) {
257 MusicUtil.debug = debug;
261 * Is Debug - Default = true property file value - debug
265 public static boolean isDebug() {
274 public static void setVersion(String version) {
275 MusicUtil.version = version;
279 * Return the version property file value - version.
283 public static String getVersion() {
288 * Set the build of project which is a combination of the
289 * version and the date.
291 * @param build - version-date.
293 public static void setBuild(String build) {
294 MusicUtil.build = build;
298 * Return the build version-date.
300 public static String getBuild() {
305 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
306 * value - cassandra.host
310 public static String getMyCassaHost() {
315 * Set MyCassHost - Cassandra Hostname
317 * @param myCassaHost .
319 public static void setMyCassaHost(String myCassaHost) {
320 MusicUtil.myCassaHost = myCassaHost;
324 * Gey default retry count
327 public static int getRetryCount() {
333 * @param retryCount .
335 public static void setRetryCount(int retryCount) {
336 MusicUtil.retryCount = retryCount;
341 * This is used to turn keyspace creation api on/off.
344 public static void setKeyspaceActive(Boolean keyspaceActive) {
345 MusicUtil.isKeyspaceActive = keyspaceActive;
349 * This is used to turn keyspace creation api on/off.
350 * @return boolean isKeyspaceActive
352 public static boolean isKeyspaceActive() {
353 return isKeyspaceActive;
357 * This method depricated as its not used or needed.
362 public static String getTestType() {
363 String testType = "";
365 Scanner fileScanner = new Scanner(new File(""));
366 testType = fileScanner.next();// ignore the my id line
367 @SuppressWarnings("unused")
368 String batchSize = fileScanner.next();// ignore the my public ip line
370 } catch (FileNotFoundException e) {
371 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
378 * Method to do a Thread Sleep.
379 * Used for adding a delay.
383 public static void sleep(long time) {
386 } catch (InterruptedException e) {
387 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
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 @SuppressWarnings("unchecked")
424 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
427 switch (type.getName()) {
429 value = valueObj + "";
433 String valueString = valueObj + "";
434 valueString = valueString.replace("'", "''");
435 value = "'" + valueString + "'";
438 Map<String, Object> otMap = (Map<String, Object>) valueObj;
439 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
443 value = valueObj + "";
454 * @throws MusicTypeConversionException
457 @SuppressWarnings("unchecked")
458 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
459 String valueObjString = valueObj + "";
460 switch (colType.getName()) {
462 return UUID.fromString(valueObjString);
464 return BigInteger.valueOf(Long.parseLong(valueObjString));
466 return Long.parseLong(valueObjString);
468 return Integer.parseInt(valueObjString);
470 return Float.parseFloat(valueObjString);
472 return Double.parseDouble(valueObjString);
474 return Boolean.parseBoolean(valueObjString);
476 return (Map<String, Object>) valueObj;
478 return (List<Object>)valueObj;
482 return valueObjString;
486 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
487 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
493 * Utility function to parse json map into sql like string
496 * @param lineDelimiter
500 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
501 StringBuilder sqlString = new StringBuilder();
503 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
504 Object ot = entry.getValue();
505 String value = ot + "";
506 if (ot instanceof String) {
507 value = "'" + value.replace("'", "''") + "'";
509 sqlString.append("'" + entry.getKey() + "':" + value);
510 if (counter != jMap.size() - 1)
511 sqlString.append(lineDelimiter);
512 counter = counter + 1;
514 return sqlString.toString();
517 @SuppressWarnings("unused")
518 public static String buildVersion(String major, String minor, String patch) {
520 major += "." + minor;
522 major += "." + patch;
529 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
530 * X-latestVerstion will be equal to the latest full version.
531 * X-minorVersion - will be equal to the latest minor version.
532 * X-pathVersion - will be equal to the latest patch version.
533 * Future plans will change this.
540 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
541 ResponseBuilder response = Response.noContent();
542 String versionIn = buildVersion(major,minor,patch);
543 String version = MusicUtil.getVersion();
544 String[] verArray = version.split("\\.",3);
545 if ( minor != null ) {
546 response.header(XMINORVERSION,minor);
548 response.header(XMINORVERSION,verArray[1]);
550 if ( patch != null ) {
551 response.header(XPATCHVERSION,patch);
553 response.header(XPATCHVERSION,verArray[2]);
555 response.header(XLATESTVERSION,version);
556 logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn);
560 public static boolean isValidConsistency(String consistency) {
561 for (String string : cosistencyLevel) {
562 if (string.equalsIgnoreCase(consistency))
569 public static ConsistencyLevel getConsistencyLevel(String consistency) {
570 return consistencyName.get(consistency.toUpperCase());
574 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
575 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
576 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
577 * @param the UUID lock reference associated with the write.
578 * @param the long timeOfWrite which is the actual time at which the write took place
579 * @throws MusicServiceException
580 * @throws MusicQueryException
582 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
583 // TODO: use acquire time instead of music eternity epoch
584 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
589 public static MusicCoreService getMusicCoreService() {
590 if(getLockUsing().equals(MusicUtil.CASSANDRA))
591 return MusicCassaCore.getInstance();
593 return MusicCassaCore.getInstance();
600 public static Map<String, Object> validateLock(String lockName) {
601 Map<String, Object> resultMap = new HashMap<>();
602 String[] locks = lockName.split("\\.");
603 if(locks.length < 3) {
604 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
607 String keyspace= locks[0];
608 if(keyspace.startsWith("$"))
609 keyspace = keyspace.substring(1);
610 resultMap.put("keyspace",keyspace);
615 public static void setIsCadi(boolean isCadi) {
616 MusicUtil.isCadi = isCadi;
619 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
620 PreparedQueryObject updateQuery, String keyspace, String table,
621 Object cqlFormattedPrimaryKeyValue)
624 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
625 // write it back to a quorum
626 Row row = results.one();
627 ColumnDefinitions colInfo = row.getColumnDefinitions();
628 int totalColumns = colInfo.size();
630 StringBuilder fieldValueString = new StringBuilder("");
631 for (Definition definition : colInfo) {
632 String colName = definition.getName();
633 if (colName.equals(primaryKeyName))
635 DataType colType = definition.getType();
636 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
637 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
638 fieldValueString.append(colName + " = ?");
639 updateQuery.addValue(valueString);
640 if (counter != (totalColumns - 1))
641 fieldValueString.append(",");
642 counter = counter + 1;
644 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
645 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
646 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
648 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
649 } catch (MusicServiceException | MusicQueryException e) {
650 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
651 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e);
655 public static boolean getIsCadi() {
656 return MusicUtil.isCadi;
661 * @return a random uuid
663 public static String generateUUID() {
664 String uuid = UUID.randomUUID().toString();
665 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
669 private static String checkPrefix(String prefix){
670 if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) {
678 * @return the transIdPrefix
680 public static String getTransIdPrefix() {
681 return transIdPrefix;
685 * @param transIdPrefix the transIdPrefix to set
687 public static void setTransIdPrefix(String transIdPrefix) {
688 MusicUtil.transIdPrefix = checkPrefix(transIdPrefix);
692 * @return the conversationIdPrefix
694 public static String getConversationIdPrefix() {
695 return conversationIdPrefix;
699 * @param conversationIdPrefix the conversationIdPrefix to set
701 public static void setConversationIdPrefix(String conversationIdPrefix) {
702 MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix);
706 * @return the clientIdPrefix
708 public static String getClientIdPrefix() {
709 return clientIdPrefix;
713 * @param clientIdPrefix the clientIdPrefix to set
715 public static void setClientIdPrefix(String clientIdPrefix) {
716 MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix);
720 * @return the messageIdPrefix
722 public static String getMessageIdPrefix() {
723 return messageIdPrefix;
727 * @param messageIdPrefix the messageIdPrefix to set
729 public static void setMessageIdPrefix(String messageIdPrefix) {
730 MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix);
734 * @return the transIdRequired
736 public static Boolean getTransIdRequired() {
737 return transIdRequired;
742 * @param transIdRequired the transIdRequired to set
744 public static void setTransIdRequired(Boolean transIdRequired) {
745 MusicUtil.transIdRequired = transIdRequired;
750 * @return the conversationIdRequired
752 public static Boolean getConversationIdRequired() {
753 return conversationIdRequired;
758 * @param conversationIdRequired the conversationIdRequired to set
760 public static void setConversationIdRequired(Boolean conversationIdRequired) {
761 MusicUtil.conversationIdRequired = conversationIdRequired;
766 * @return the clientIdRequired
768 public static Boolean getClientIdRequired() {
769 return clientIdRequired;
774 * @param clientIdRequired the clientIdRequired to set
776 public static void setClientIdRequired(Boolean clientIdRequired) {
777 MusicUtil.clientIdRequired = clientIdRequired;
782 * @return the messageIdRequired
784 public static Boolean getMessageIdRequired() {
785 return messageIdRequired;
789 * @param messageIdRequired the messageIdRequired to set
791 public static void setMessageIdRequired(Boolean messageIdRequired) {
792 MusicUtil.messageIdRequired = messageIdRequired;
796 public static String getCipherEncKey() {
797 return MusicUtil.cipherEncKey;
801 public static void setCipherEncKey(String cipherEncKey) {
802 MusicUtil.cipherEncKey = cipherEncKey;
803 if ( null == cipherEncKey || cipherEncKey.equals("") ||
804 cipherEncKey.equals("nothing to see here")) {
805 logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key.");
809 public static String getMusicAafNs() {
810 return MusicUtil.musicAafNs;
814 public static void setMusicAafNs(String musicAafNs) {
815 MusicUtil.musicAafNs = musicAafNs;