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;
142 private static int cassandraConnectTimeOutMS;
143 private static int cassandraReadTimeOutMS;
146 private static String musicAafNs = "org.onap.music.cadi";
149 public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
150 public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
151 public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
153 // Response/Request tracking headers
154 private static String transIdPrefix = "false";
155 private static String conversationIdPrefix = "false";
156 private static String clientIdPrefix = "false";
157 private static String messageIdPrefix = "false";
158 private static Boolean transIdRequired = false;
159 private static Boolean conversationIdRequired = false;
160 private static Boolean clientIdRequired = false;
161 private static Boolean messageIdRequired = false;
162 private static String cipherEncKey = "";
165 throw new IllegalStateException("Utility Class");
168 public static String getLockUsing() {
172 public static void setLockUsing(String lockUsing) {
173 MusicUtil.lockUsing = lockUsing;
178 * @return cassandra port
180 public static int getCassandraPort() {
181 return cassandraPort;
186 * @param cassandraPort
188 public static void setCassandraPort(int cassandraPort) {
189 MusicUtil.cassandraPort = cassandraPort;
192 * @return the cassName
194 public static String getCassName() {
199 * @return the cassPwd
201 public static String getCassPwd() {
205 public static int getCassandraConnectTimeOutMS() {
206 return cassandraConnectTimeOutMS;
209 public static void setCassandraConnectTimeOutMS(int cassandraConnectTimeOutMS) {
210 MusicUtil.cassandraConnectTimeOutMS = cassandraConnectTimeOutMS;
213 public static int getCassandraReadTimeOutMS() {
214 return cassandraReadTimeOutMS;
217 public static void setCassandraReadTimeOutMS(int cassandraReadTimeOutMS) {
218 MusicUtil.cassandraReadTimeOutMS = cassandraReadTimeOutMS;
222 * Returns An array of property names that should be in the Properties
227 // public static String[] getPropkeys() {
228 // return propKeys.clone();
232 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
233 * property file value - music.properties
237 public static String getMusicPropertiesFilePath() {
238 return musicPropertiesFilePath;
242 * Set MusicPropertiesFilePath
244 * @param musicPropertiesFilePath
246 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
247 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
251 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
256 public static long getDefaultLockLeasePeriod() {
257 return defaultLockLeasePeriod;
261 * Set DefaultLockLeasePeriod
263 * @param defaultLockLeasePeriod
265 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
266 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
274 public static void setDebug(boolean debug) {
275 MusicUtil.debug = debug;
279 * Is Debug - Default = true property file value - debug
283 public static boolean isDebug() {
292 public static void setVersion(String version) {
293 MusicUtil.version = version;
297 * Return the version property file value - version.
301 public static String getVersion() {
306 * Set the build of project which is a combination of the
307 * version and the date.
309 * @param build - version-date.
311 public static void setBuild(String build) {
312 MusicUtil.build = build;
316 * Return the build version-date.
318 public static String getBuild() {
323 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
324 * value - cassandra.host
328 public static String getMyCassaHost() {
333 * Set MyCassHost - Cassandra Hostname
335 * @param myCassaHost .
337 public static void setMyCassaHost(String myCassaHost) {
338 MusicUtil.myCassaHost = myCassaHost;
342 * Gey default retry count
345 public static int getRetryCount() {
351 * @param retryCount .
353 public static void setRetryCount(int retryCount) {
354 MusicUtil.retryCount = retryCount;
359 * This is used to turn keyspace creation api on/off.
362 public static void setKeyspaceActive(Boolean keyspaceActive) {
363 MusicUtil.isKeyspaceActive = keyspaceActive;
367 * This is used to turn keyspace creation api on/off.
368 * @return boolean isKeyspaceActive
370 public static boolean isKeyspaceActive() {
371 return isKeyspaceActive;
375 * This method depricated as its not used or needed.
380 public static String getTestType() {
381 String testType = "";
383 Scanner fileScanner = new Scanner(new File(""));
384 testType = fileScanner.next();// ignore the my id line
385 @SuppressWarnings("unused")
386 String batchSize = fileScanner.next();// ignore the my public ip line
388 } catch (FileNotFoundException e) {
389 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
396 * Method to do a Thread Sleep.
397 * Used for adding a delay.
401 public static void sleep(long time) {
404 } catch (InterruptedException e) {
405 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
406 Thread.currentThread().interrupt();
411 * Utility function to check if the query object is valid.
417 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
419 int noOfValues = queryObject.getValues().size();
421 char[] temp = queryObject.getQuery().toCharArray();
422 for (int i = 0; i < temp.length; i++) {
426 return (noOfValues == noOfParams);
428 return !queryObject.getQuery().isEmpty();
433 public static void setCassName(String cassName) {
434 MusicUtil.cassName = cassName;
437 public static void setCassPwd(String cassPwd) {
438 MusicUtil.cassPwd = cassPwd;
441 @SuppressWarnings("unchecked")
442 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
445 switch (type.getName()) {
447 value = valueObj + "";
451 String valueString = valueObj + "";
452 valueString = valueString.replace("'", "''");
453 value = "'" + valueString + "'";
456 Map<String, Object> otMap = (Map<String, Object>) valueObj;
457 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
461 value = valueObj + "";
472 * @throws MusicTypeConversionException
475 @SuppressWarnings("unchecked")
476 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
477 String valueObjString = valueObj + "";
478 switch (colType.getName()) {
480 return UUID.fromString(valueObjString);
482 return BigInteger.valueOf(Long.parseLong(valueObjString));
484 return Long.parseLong(valueObjString);
486 return Integer.parseInt(valueObjString);
488 return Float.parseFloat(valueObjString);
490 return Double.parseDouble(valueObjString);
492 return Boolean.parseBoolean(valueObjString);
494 return (Map<String, Object>) valueObj;
496 return (List<Object>)valueObj;
500 return valueObjString;
504 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
505 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
511 * Utility function to parse json map into sql like string
514 * @param lineDelimiter
518 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
519 StringBuilder sqlString = new StringBuilder();
521 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
522 Object ot = entry.getValue();
523 String value = ot + "";
524 if (ot instanceof String) {
525 value = "'" + value.replace("'", "''") + "'";
527 sqlString.append("'" + entry.getKey() + "':" + value);
528 if (counter != jMap.size() - 1)
529 sqlString.append(lineDelimiter);
530 counter = counter + 1;
532 return sqlString.toString();
535 @SuppressWarnings("unused")
536 public static String buildVersion(String major, String minor, String patch) {
538 major += "." + minor;
540 major += "." + patch;
547 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
548 * X-latestVerstion will be equal to the latest full version.
549 * X-minorVersion - will be equal to the latest minor version.
550 * X-pathVersion - will be equal to the latest patch version.
551 * Future plans will change this.
558 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
559 ResponseBuilder response = Response.noContent();
560 String versionIn = buildVersion(major,minor,patch);
561 String version = MusicUtil.getVersion();
562 String[] verArray = version.split("\\.",3);
563 if ( minor != null ) {
564 response.header(XMINORVERSION,minor);
566 response.header(XMINORVERSION,verArray[1]);
568 if ( patch != null ) {
569 response.header(XPATCHVERSION,patch);
571 response.header(XPATCHVERSION,verArray[2]);
573 response.header(XLATESTVERSION,version);
574 logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn);
578 public static boolean isValidConsistency(String consistency) {
579 for (String string : cosistencyLevel) {
580 if (string.equalsIgnoreCase(consistency))
587 public static ConsistencyLevel getConsistencyLevel(String consistency) {
588 return consistencyName.get(consistency.toUpperCase());
592 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
593 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
594 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
595 * @param the UUID lock reference associated with the write.
596 * @param the long timeOfWrite which is the actual time at which the write took place
597 * @throws MusicServiceException
598 * @throws MusicQueryException
600 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
601 // TODO: use acquire time instead of music eternity epoch
602 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
607 public static MusicCoreService getMusicCoreService() {
608 if(getLockUsing().equals(MusicUtil.CASSANDRA))
609 return MusicCassaCore.getInstance();
611 return MusicCassaCore.getInstance();
618 public static Map<String, Object> validateLock(String lockName) {
619 Map<String, Object> resultMap = new HashMap<>();
620 String[] locks = lockName.split("\\.");
621 if(locks.length < 3) {
622 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
625 String keyspace= locks[0];
626 if(keyspace.startsWith("$"))
627 keyspace = keyspace.substring(1);
628 resultMap.put("keyspace",keyspace);
633 public static void setIsCadi(boolean isCadi) {
634 MusicUtil.isCadi = isCadi;
637 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
638 PreparedQueryObject updateQuery, String keyspace, String table,
639 Object cqlFormattedPrimaryKeyValue)
642 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
643 // write it back to a quorum
644 Row row = results.one();
645 ColumnDefinitions colInfo = row.getColumnDefinitions();
646 int totalColumns = colInfo.size();
648 StringBuilder fieldValueString = new StringBuilder("");
649 for (Definition definition : colInfo) {
650 String colName = definition.getName();
651 if (colName.equals(primaryKeyName))
653 DataType colType = definition.getType();
654 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
655 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
656 fieldValueString.append(colName + " = ?");
657 updateQuery.addValue(valueString);
658 if (counter != (totalColumns - 1))
659 fieldValueString.append(",");
660 counter = counter + 1;
662 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
663 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
664 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
666 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
667 } catch (MusicServiceException | MusicQueryException e) {
668 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
669 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e);
673 public static boolean getIsCadi() {
674 return MusicUtil.isCadi;
679 * @return a random uuid
681 public static String generateUUID() {
682 String uuid = UUID.randomUUID().toString();
683 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
687 private static String checkPrefix(String prefix){
688 if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) {
696 * @return the transIdPrefix
698 public static String getTransIdPrefix() {
699 return transIdPrefix;
703 * @param transIdPrefix the transIdPrefix to set
705 public static void setTransIdPrefix(String transIdPrefix) {
706 MusicUtil.transIdPrefix = checkPrefix(transIdPrefix);
710 * @return the conversationIdPrefix
712 public static String getConversationIdPrefix() {
713 return conversationIdPrefix;
717 * @param conversationIdPrefix the conversationIdPrefix to set
719 public static void setConversationIdPrefix(String conversationIdPrefix) {
720 MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix);
724 * @return the clientIdPrefix
726 public static String getClientIdPrefix() {
727 return clientIdPrefix;
731 * @param clientIdPrefix the clientIdPrefix to set
733 public static void setClientIdPrefix(String clientIdPrefix) {
734 MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix);
738 * @return the messageIdPrefix
740 public static String getMessageIdPrefix() {
741 return messageIdPrefix;
745 * @param messageIdPrefix the messageIdPrefix to set
747 public static void setMessageIdPrefix(String messageIdPrefix) {
748 MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix);
752 * @return the transIdRequired
754 public static Boolean getTransIdRequired() {
755 return transIdRequired;
760 * @param transIdRequired the transIdRequired to set
762 public static void setTransIdRequired(Boolean transIdRequired) {
763 MusicUtil.transIdRequired = transIdRequired;
768 * @return the conversationIdRequired
770 public static Boolean getConversationIdRequired() {
771 return conversationIdRequired;
776 * @param conversationIdRequired the conversationIdRequired to set
778 public static void setConversationIdRequired(Boolean conversationIdRequired) {
779 MusicUtil.conversationIdRequired = conversationIdRequired;
784 * @return the clientIdRequired
786 public static Boolean getClientIdRequired() {
787 return clientIdRequired;
792 * @param clientIdRequired the clientIdRequired to set
794 public static void setClientIdRequired(Boolean clientIdRequired) {
795 MusicUtil.clientIdRequired = clientIdRequired;
800 * @return the messageIdRequired
802 public static Boolean getMessageIdRequired() {
803 return messageIdRequired;
807 * @param messageIdRequired the messageIdRequired to set
809 public static void setMessageIdRequired(Boolean messageIdRequired) {
810 MusicUtil.messageIdRequired = messageIdRequired;
814 public static String getCipherEncKey() {
815 return MusicUtil.cipherEncKey;
819 public static void setCipherEncKey(String cipherEncKey) {
820 MusicUtil.cipherEncKey = cipherEncKey;
821 if ( null == cipherEncKey || cipherEncKey.equals("") ||
822 cipherEncKey.equals("nothing to see here")) {
823 logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key.");
827 public static String getMusicAafNs() {
828 return MusicUtil.musicAafNs;
832 public static void setMusicAafNs(String musicAafNs) {
833 MusicUtil.musicAafNs = musicAafNs;