2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2018 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 ONE = "one";
77 public static final String ATOMICDELETELOCK = "atomic_delete_lock";
80 private static final String XLATESTVERSION = "X-latestVersion";
81 private static final String XMINORVERSION = "X-minorVersion";
82 private static final String XPATCHVERSION = "X-patchVersion";
83 public static final String AUTHORIZATION = "Authorization";
86 public static final String SELECT = "select";
87 public static final String INSERT = "insert";
88 public static final String UPDATE = "update";
89 public static final String UPSERT = "upsert";
90 public static final String USERID = "userId";
91 public static final String PASSWORD = "";
92 public static final String CASSANDRA = "cassandra";
94 private static final String LOCALHOST = "localhost";
95 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
96 public static final String DEFAULTKEYSPACENAME = "TBD";
98 private static long defaultLockLeasePeriod = 6000;
99 // Amount of times to retry to delete a lock in atomic.
100 private static int retryCount = 3;
101 private static String lockUsing = MusicUtil.CASSANDRA;
103 private static boolean isCadi = false;
104 // Keyspace Creation on/off
105 private static boolean isKeyspaceActive = false;
106 private static boolean debug = true;
107 private static String version = "0.0.0";
108 private static String build = "";
110 private static String musicPropertiesFilePath = PROPERTIES_FILE;
111 // private static final String[] propKeys = new String[] { MusicUtil.class.getDeclaredMethod(arg0, )"build","cassandra.host", "debug",
112 // "version", "music.properties", "lock.lease.period", "cassandra.user",
113 // "cassandra.password", "aaf.endpoint.url","admin.username","admin.password",
114 // "music.namespace","admin.aaf.role","cassandra.port","lock.using","retry.count",
115 // "transId.header.required","conversation.header.required","clientId.header.required",
116 // "messageId.header.required","transId.header.prefix","conversation.header.prefix",
117 // "clientId.header.prefix","messageId.header.prefix"};
118 // Consistency Constants and variables.
119 private static final String[] cosistencyLevel = new String[] {
120 "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO",
121 "THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
122 private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
124 consistencyName.put("ONE",ConsistencyLevel.ONE);
125 consistencyName.put("TWO",ConsistencyLevel.TWO);
126 consistencyName.put("THREE",ConsistencyLevel.THREE);
127 consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
128 consistencyName.put("ALL",ConsistencyLevel.ALL);
129 consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
130 consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
131 consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
132 consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
133 consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
137 private static String cassName = "cassandra";
138 private static String cassPwd;
139 private static String myCassaHost = LOCALHOST;
140 private static int cassandraPort = 9042;
143 private static String musicAafNs = "org.onap.music.cadi";
146 public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
147 public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
148 public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
150 // Response/Request tracking headers
151 private static String transIdPrefix = "false";
152 private static String conversationIdPrefix = "false";
153 private static String clientIdPrefix = "false";
154 private static String messageIdPrefix = "false";
155 private static Boolean transIdRequired = false;
156 private static Boolean conversationIdRequired = false;
157 private static Boolean clientIdRequired = false;
158 private static Boolean messageIdRequired = false;
159 private static String cipherEncKey = "";
162 public static String getLockUsing() {
166 public static void setLockUsing(String lockUsing) {
167 MusicUtil.lockUsing = lockUsing;
171 throw new IllegalStateException("Utility Class");
175 * @return cassandra port
177 public static int getCassandraPort() {
178 return cassandraPort;
183 * @param cassandraPort
185 public static void setCassandraPort(int cassandraPort) {
186 MusicUtil.cassandraPort = cassandraPort;
189 * @return the cassName
191 public static String getCassName() {
196 * @return the cassPwd
198 public static String getCassPwd() {
203 * Returns An array of property names that should be in the Properties
208 // public static String[] getPropkeys() {
209 // return propKeys.clone();
213 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
214 * property file value - music.properties
218 public static String getMusicPropertiesFilePath() {
219 return musicPropertiesFilePath;
223 * Set MusicPropertiesFilePath
225 * @param musicPropertiesFilePath
227 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
228 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
232 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
237 public static long getDefaultLockLeasePeriod() {
238 return defaultLockLeasePeriod;
242 * Set DefaultLockLeasePeriod
244 * @param defaultLockLeasePeriod
246 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
247 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
255 public static void setDebug(boolean debug) {
256 MusicUtil.debug = debug;
260 * Is Debug - Default = true property file value - debug
264 public static boolean isDebug() {
273 public static void setVersion(String version) {
274 MusicUtil.version = version;
278 * Return the version property file value - version.
282 public static String getVersion() {
287 * Set the build of project which is a combination of the
288 * version and the date.
290 * @param build - version-date.
292 public static void setBuild(String build) {
293 MusicUtil.build = build;
297 * Return the build version-date.
299 public static String getBuild() {
304 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
305 * value - cassandra.host
309 public static String getMyCassaHost() {
314 * Set MyCassHost - Cassandra Hostname
316 * @param myCassaHost .
318 public static void setMyCassaHost(String myCassaHost) {
319 MusicUtil.myCassaHost = myCassaHost;
323 * Gey default retry count
326 public static int getRetryCount() {
332 * @param retryCount .
334 public static void setRetryCount(int retryCount) {
335 MusicUtil.retryCount = retryCount;
340 * This is used to turn keyspace creation api on/off.
343 public static void setKeyspaceActive(Boolean keyspaceActive) {
344 MusicUtil.isKeyspaceActive = keyspaceActive;
348 * This is used to turn keyspace creation api on/off.
349 * @return boolean isKeyspaceActive
351 public static boolean isKeyspaceActive() {
352 return isKeyspaceActive;
356 * This method depricated as its not used or needed.
361 public static String getTestType() {
362 String testType = "";
364 Scanner fileScanner = new Scanner(new File(""));
365 testType = fileScanner.next();// ignore the my id line
366 @SuppressWarnings("unused")
367 String batchSize = fileScanner.next();// ignore the my public ip line
369 } catch (FileNotFoundException e) {
370 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
377 * Method to do a Thread Sleep.
378 * Used for adding a delay.
382 public static void sleep(long time) {
385 } catch (InterruptedException e) {
386 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
387 Thread.currentThread().interrupt();
392 * Utility function to check if the query object is valid.
398 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
400 int noOfValues = queryObject.getValues().size();
402 char[] temp = queryObject.getQuery().toCharArray();
403 for (int i = 0; i < temp.length; i++) {
407 return (noOfValues == noOfParams);
409 return !queryObject.getQuery().isEmpty();
414 public static void setCassName(String cassName) {
415 MusicUtil.cassName = cassName;
418 public static void setCassPwd(String cassPwd) {
419 MusicUtil.cassPwd = cassPwd;
422 @SuppressWarnings("unchecked")
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 @SuppressWarnings("unchecked")
457 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
458 String valueObjString = valueObj + "";
459 switch (colType.getName()) {
461 return UUID.fromString(valueObjString);
463 return BigInteger.valueOf(Long.parseLong(valueObjString));
465 return Long.parseLong(valueObjString);
467 return Integer.parseInt(valueObjString);
469 return Float.parseFloat(valueObjString);
471 return Double.parseDouble(valueObjString);
473 return Boolean.parseBoolean(valueObjString);
475 return (Map<String, Object>) valueObj;
477 return (List<Object>)valueObj;
481 return valueObjString;
485 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
486 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
492 * Utility function to parse json map into sql like string
495 * @param lineDelimiter
499 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
500 StringBuilder sqlString = new StringBuilder();
502 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
503 Object ot = entry.getValue();
504 String value = ot + "";
505 if (ot instanceof String) {
506 value = "'" + value.replace("'", "''") + "'";
508 sqlString.append("'" + entry.getKey() + "':" + value);
509 if (counter != jMap.size() - 1)
510 sqlString.append(lineDelimiter);
511 counter = counter + 1;
513 return sqlString.toString();
516 @SuppressWarnings("unused")
517 public static String buildVersion(String major, String minor, String patch) {
519 major += "." + minor;
521 major += "." + patch;
528 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
529 * X-latestVerstion will be equal to the latest full version.
530 * X-minorVersion - will be equal to the latest minor version.
531 * X-pathVersion - will be equal to the latest patch version.
532 * Future plans will change this.
539 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
540 ResponseBuilder response = Response.noContent();
541 String versionIn = buildVersion(major,minor,patch);
542 String version = MusicUtil.getVersion();
543 String[] verArray = version.split("\\.",3);
544 if ( minor != null ) {
545 response.header(XMINORVERSION,minor);
547 response.header(XMINORVERSION,verArray[1]);
549 if ( patch != null ) {
550 response.header(XPATCHVERSION,patch);
552 response.header(XPATCHVERSION,verArray[2]);
554 response.header(XLATESTVERSION,version);
555 logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn);
559 public static boolean isValidConsistency(String consistency) {
560 for (String string : cosistencyLevel) {
561 if (string.equalsIgnoreCase(consistency))
568 public static ConsistencyLevel getConsistencyLevel(String consistency) {
569 return consistencyName.get(consistency.toUpperCase());
573 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
574 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
575 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
576 * @param the UUID lock reference associated with the write.
577 * @param the long timeOfWrite which is the actual time at which the write took place
578 * @throws MusicServiceException
579 * @throws MusicQueryException
581 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
582 // TODO: use acquire time instead of music eternity epoch
583 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
588 public static MusicCoreService getMusicCoreService() {
589 if(getLockUsing().equals(MusicUtil.CASSANDRA))
590 return MusicCassaCore.getInstance();
592 return MusicCassaCore.getInstance();
599 public static Map<String, Object> validateLock(String lockName) {
600 Map<String, Object> resultMap = new HashMap<>();
601 String[] locks = lockName.split("\\.");
602 if(locks.length < 3) {
603 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
606 String keyspace= locks[0];
607 if(keyspace.startsWith("$"))
608 keyspace = keyspace.substring(1);
609 resultMap.put("keyspace",keyspace);
614 public static void setIsCadi(boolean isCadi) {
615 MusicUtil.isCadi = isCadi;
618 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
619 PreparedQueryObject updateQuery, String keyspace, String table,
620 Object cqlFormattedPrimaryKeyValue)
623 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
624 // write it back to a quorum
625 Row row = results.one();
626 ColumnDefinitions colInfo = row.getColumnDefinitions();
627 int totalColumns = colInfo.size();
629 StringBuilder fieldValueString = new StringBuilder("");
630 for (Definition definition : colInfo) {
631 String colName = definition.getName();
632 if (colName.equals(primaryKeyName))
634 DataType colType = definition.getType();
635 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
636 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
637 fieldValueString.append(colName + " = ?");
638 updateQuery.addValue(valueString);
639 if (counter != (totalColumns - 1))
640 fieldValueString.append(",");
641 counter = counter + 1;
643 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
644 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
645 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
647 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
648 } catch (MusicServiceException | MusicQueryException e) {
649 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
650 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e);
654 public static boolean getIsCadi() {
655 return MusicUtil.isCadi;
660 * @return a random uuid
662 public static String generateUUID() {
663 String uuid = UUID.randomUUID().toString();
664 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
668 private static String checkPrefix(String prefix){
669 if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) {
677 * @return the transIdPrefix
679 public static String getTransIdPrefix() {
680 return transIdPrefix;
684 * @param transIdPrefix the transIdPrefix to set
686 public static void setTransIdPrefix(String transIdPrefix) {
687 MusicUtil.transIdPrefix = checkPrefix(transIdPrefix);
691 * @return the conversationIdPrefix
693 public static String getConversationIdPrefix() {
694 return conversationIdPrefix;
698 * @param conversationIdPrefix the conversationIdPrefix to set
700 public static void setConversationIdPrefix(String conversationIdPrefix) {
701 MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix);
705 * @return the clientIdPrefix
707 public static String getClientIdPrefix() {
708 return clientIdPrefix;
712 * @param clientIdPrefix the clientIdPrefix to set
714 public static void setClientIdPrefix(String clientIdPrefix) {
715 MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix);
719 * @return the messageIdPrefix
721 public static String getMessageIdPrefix() {
722 return messageIdPrefix;
726 * @param messageIdPrefix the messageIdPrefix to set
728 public static void setMessageIdPrefix(String messageIdPrefix) {
729 MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix);
733 * @return the transIdRequired
735 public static Boolean getTransIdRequired() {
736 return transIdRequired;
741 * @param transIdRequired the transIdRequired to set
743 public static void setTransIdRequired(Boolean transIdRequired) {
744 MusicUtil.transIdRequired = transIdRequired;
749 * @return the conversationIdRequired
751 public static Boolean getConversationIdRequired() {
752 return conversationIdRequired;
757 * @param conversationIdRequired the conversationIdRequired to set
759 public static void setConversationIdRequired(Boolean conversationIdRequired) {
760 MusicUtil.conversationIdRequired = conversationIdRequired;
765 * @return the clientIdRequired
767 public static Boolean getClientIdRequired() {
768 return clientIdRequired;
773 * @param clientIdRequired the clientIdRequired to set
775 public static void setClientIdRequired(Boolean clientIdRequired) {
776 MusicUtil.clientIdRequired = clientIdRequired;
781 * @return the messageIdRequired
783 public static Boolean getMessageIdRequired() {
784 return messageIdRequired;
788 * @param messageIdRequired the messageIdRequired to set
790 public static void setMessageIdRequired(Boolean messageIdRequired) {
791 MusicUtil.messageIdRequired = messageIdRequired;
795 public static String getCipherEncKey() {
796 return MusicUtil.cipherEncKey;
800 public static void setCipherEncKey(String cipherEncKey) {
801 MusicUtil.cipherEncKey = cipherEncKey;
802 if ( null == cipherEncKey || cipherEncKey.equals("") ||
803 cipherEncKey.equals("nothing to see here")) {
804 logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key.");
808 public static String getMusicAafNs() {
809 return MusicUtil.musicAafNs;
813 public static void setMusicAafNs(String musicAafNs) {
814 MusicUtil.musicAafNs = musicAafNs;