aboutsummaryrefslogtreecommitdiffstats
path: root/music-core/src/main/java/org/onap/music/main
diff options
context:
space:
mode:
Diffstat (limited to 'music-core/src/main/java/org/onap/music/main')
-rw-r--r--music-core/src/main/java/org/onap/music/main/CipherUtil.java279
-rw-r--r--music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java120
-rw-r--r--music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java152
-rw-r--r--music-core/src/main/java/org/onap/music/main/MusicCore.java264
-rw-r--r--music-core/src/main/java/org/onap/music/main/MusicUtil.java881
-rw-r--r--music-core/src/main/java/org/onap/music/main/ResultType.java42
-rw-r--r--music-core/src/main/java/org/onap/music/main/ReturnType.java75
7 files changed, 1813 insertions, 0 deletions
diff --git a/music-core/src/main/java/org/onap/music/main/CipherUtil.java b/music-core/src/main/java/org/onap/music/main/CipherUtil.java
new file mode 100644
index 00000000..9a8ff69d
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/CipherUtil.java
@@ -0,0 +1,279 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Modification Copyright (c) 2019 IBM
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Scanner;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.ArrayUtils;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+
+public class CipherUtil {
+
+
+ /**
+ * Default key.
+ */
+ private static String keyString = MusicUtil.getCipherEncKey();
+
+ private static final String ALGORITHM = "AES";
+ private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
+ private static final int BLOCK_SIZE = 128;
+ @SuppressWarnings("unused")
+ private static SecretKeySpec secretKeySpec;
+ private static IvParameterSpec ivspec;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CipherUtil.class);
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ *
+ * Encrypts the text using the specified secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @param secretKey
+ * Key to use for encryption
+ * @return encrypted version of plain text.
+ * @
+ * if any encryption step fails
+ *
+ */
+ @Deprecated
+ public static String encrypt(String plainText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] encryptText = plainText.getBytes("UTF-8");
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
+ encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ * Encrypts the text using the secret key in key.properties file.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String encrypt(String plainText) {
+ return CipherUtil.encrypt(plainText, keyString);
+ }
+
+ /**
+ * Encrypts the text using a secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ public static String encryptPKC(String plainText) {
+ return CipherUtil.encryptPKC(plainText, keyString);
+ }
+
+ /**
+ *
+ * @deprecated Please use {@link #decryptPKC(String)} to Decryption the text.
+ *
+ * Decrypts the text using the specified secret key.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @param secretKey
+ * Key to use for decryption
+ * @return plain text version of encrypted text
+ * @
+ * if any decryption step fails
+ *
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
+ encryptedString = new String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ private static SecretKeySpec getSecretKeySpec() {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ private static SecretKeySpec getSecretKeySpec(String keyString) {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ /**
+ * Encrypt the text using the secret key in key.properties file
+ *
+ * @param value
+ * @return The encrypted string
+ * @throws BadPaddingException
+ * @
+ * In case of issue with the encryption
+ */
+ public static String encryptPKC(String value, String skey) {
+ Cipher cipher = null;
+ byte[] iv = null;
+ byte[] finalByte = null;
+
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+
+ SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
+ iv = new byte[BLOCK_SIZE / 8];
+ r.nextBytes(iv);
+ ivspec = new IvParameterSpec(iv);
+ cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ finalByte = cipher.doFinal(value.getBytes());
+
+ } catch (Exception ex) {
+
+ }
+ return Base64.encodeBase64String(ArrayUtils.addAll(iv, finalByte));
+ }
+
+ /**
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param message
+ * The encrypted string that must be decrypted using the ecomp
+ * Encryption Key
+ * @return The String decrypted
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String message, String skey) {
+ byte[] encryptedMessage = Base64.decodeBase64(message);
+ Cipher cipher;
+ byte[] decrypted = null;
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+ ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE / 8));
+ byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE / 8, encryptedMessage.length);
+ cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ decrypted = cipher.doFinal(realData);
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error in decryptPKC", ex);
+
+ }
+
+ return new String(decrypted);
+ }
+
+ /**
+ * @deprecated Please use {@link #decryptPKC(String)} to Decrypt the text.
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText) {
+ return CipherUtil.decrypt(encryptedText, keyString);
+ }
+
+ /**
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String encryptedText) {
+ return CipherUtil.decryptPKC(encryptedText, keyString);
+ }
+
+
+ public static void readAndSetKeyString() {
+ try (Scanner in = new Scanner(new FileReader("/opt/app/music/etc/properties.txt"))) {
+
+ StringBuilder sb = new StringBuilder();
+ while(in.hasNext()) {
+ sb.append(in.next());
+ }
+ keyString = sb.toString();
+ } catch (FileNotFoundException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ }
+
+ public static void main(String[] args) {
+
+ if (args.length < 2) {
+ System.out.println("Usage: java -jar CipherUtil <key> <password>");
+ return;
+ }
+
+ keyString = args[0];
+ String password = args[1];
+
+ String enc = encryptPKC(password);
+ System.out.println("Encrypted password: " + enc);
+
+ System.out.println("Decrypted password (to verify): " + decryptPKC(enc));
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java b/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java
new file mode 100644
index 00000000..2e5ca689
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java
@@ -0,0 +1,120 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+import java.util.Properties;
+
+public class CorePropertiesLoader {
+
+ public static void loadProperties(Properties properties) {
+ if (properties.getProperty("cassandra.host")!=null) {
+ MusicUtil.setMyCassaHost(properties.getProperty("cassandra.host"));
+ }
+
+ if (properties.getProperty("cassandra.port")!=null) {
+ MusicUtil.setCassandraPort(Integer.parseInt(properties.getProperty("cassandra.port")));
+ }
+
+ if (properties.getProperty("cassandra.user")!=null) {
+ MusicUtil.setCassName(properties.getProperty("cassandra.user"));
+ }
+
+ if (properties.getProperty("cassandra.password")!=null) {
+ MusicUtil.setCassPwd(properties.getProperty("cassandra.password"));
+ }
+
+ if (properties.getProperty("music.properties")!=null) {
+ MusicUtil.setMusicPropertiesFilePath(properties.getProperty("music.properties"));
+ }
+
+ if (properties.getProperty("debug")!=null) {
+ MusicUtil.setDebug(Boolean.parseBoolean(properties.getProperty("debug")));
+ }
+
+ if (properties.getProperty("version")!=null) {
+ MusicUtil.setVersion(properties.getProperty("version"));
+ }
+
+ if (properties.getProperty("build")!=null) {
+ MusicUtil.setBuild(properties.getProperty("build"));
+ }
+
+ if (properties.getProperty("lock.lease.period")!=null) {
+ MusicUtil.setDefaultLockLeasePeriod(Long.parseLong(properties.getProperty("lock.lease.period")));
+ }
+
+ if (properties.getProperty("cadi")!=null) {
+ MusicUtil.setIsCadi(Boolean.parseBoolean(properties.getProperty("cadi")));
+ }
+
+ if (properties.getProperty("keyspace.active")!=null) {
+ MusicUtil.setKeyspaceActive(Boolean.parseBoolean(properties.getProperty("keyspace.active")));
+ }
+
+ if (properties.getProperty("retry.count")!=null) {
+ MusicUtil.setRetryCount(Integer.parseInt(properties.getProperty("retry.count")));
+ }
+
+ if (properties.getProperty("transId.header.prefix")!=null) {
+ MusicUtil.setTransIdPrefix(properties.getProperty("transId.header.prefix"));
+ }
+
+ if (properties.getProperty("conversation.header.prefix")!=null) {
+ MusicUtil.setConversationIdPrefix(properties.getProperty("conversation.header.prefix"));
+ }
+
+ if (properties.getProperty("clientId.header.prefix")!=null) {
+ MusicUtil.setClientIdPrefix(properties.getProperty("clientId.header.prefix"));
+ }
+
+ if (properties.getProperty("messageId.header.prefix")!=null) {
+ MusicUtil.setMessageIdPrefix(properties.getProperty("messageId.header.prefix"));
+ }
+
+ if (properties.getProperty("transId.header.required")!=null) {
+ MusicUtil.setTransIdRequired(Boolean.parseBoolean(properties.getProperty("transId.header.required")));
+ }
+
+ if (properties.getProperty("conversation.header.required")!=null) {
+ MusicUtil.setConversationIdRequired(Boolean.parseBoolean(properties.getProperty("conversation.header.required")));
+ }
+
+ if (properties.getProperty("clientId.header.required")!=null) {
+ MusicUtil.setClientIdRequired(Boolean.parseBoolean(properties.getProperty("clientId.header.required")));
+ }
+
+ if (properties.getProperty("messageId.header.required")!=null) {
+ MusicUtil.setMessageIdRequired(Boolean.parseBoolean(properties.getProperty("messageId.header.required")));
+ }
+
+ if (properties.getProperty("music.aaf.ns")!=null) {
+ MusicUtil.setMusicAafNs(properties.getProperty("music.aaf.ns"));
+ }
+
+ if (properties.getProperty("cipher.enc.key")!=null) {
+ MusicUtil.setCipherEncKey(properties.getProperty("cipher.enc.key"));
+ }
+
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java b/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java
new file mode 100644
index 00000000..004bd550
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java
@@ -0,0 +1,152 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2019 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+package org.onap.music.main;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DeadlockDetectionUtil {
+ private Map<String, Node> nodeList = null;
+ public enum OwnershipType {NONE, CREATED, ACQUIRED};
+
+ private class Node implements Comparable<Node> {
+ private String id;
+ private List<Node> links;
+ private boolean visited = false;
+ private boolean onStack = false;
+
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ for (Node link : links)
+ sb.append(link.id);
+ return "Node [id=" + id + ", links=" + sb.toString() + ", visited=" + visited + ", onStack=" + onStack + "]";
+ }
+
+ public Node(String id) {
+ super();
+ this.id = id;
+ this.links = new ArrayList<>();
+ }
+
+ public List<Node> getLinks() {
+ return links;
+ }
+
+ public void addLink(Node link) {
+ this.links.add(link);
+ }
+
+ public void removeLink(Node link) {
+ this.links.remove(link);
+ }
+
+ public boolean isVisited() {
+ return visited;
+ }
+
+ public boolean isOnStack() {
+ return onStack;
+ }
+
+ public void setVisited(boolean visited) {
+ this.visited = visited;
+ }
+
+ public void setOnStack(boolean onStack) {
+ this.onStack = onStack;
+ }
+
+ @Override
+ public int compareTo(Node arg0) {
+ return id.compareTo(arg0.id);
+ }
+ }
+
+ public DeadlockDetectionUtil() {
+ this.nodeList = new HashMap<>();
+ }
+
+ public void listAllNodes() {
+ System.out.println("In DeadlockDetectionUtil: ");
+ for (String key : nodeList.keySet()) {
+ System.out.println(" " + key + " : " + nodeList.get(key));
+ }
+ }
+
+ public boolean checkForDeadlock(String resource, String owner, OwnershipType operation) {
+ setExisting(resource, owner, operation);
+
+ Node currentNode = null;
+ if (operation.equals(OwnershipType.ACQUIRED)) {
+ currentNode = nodeList.get("r" + resource);
+ } else if (operation.equals(OwnershipType.CREATED)) {
+ currentNode = nodeList.get("o" + owner);
+ }
+
+ return findCycle(currentNode);
+ }
+
+ private boolean findCycle(Node currentNode) {
+ if (currentNode==null)
+ return false;
+ if (currentNode.isOnStack())
+ return true;
+ if (currentNode.isVisited())
+ return false;
+ currentNode.setOnStack(true);
+ currentNode.setVisited(true);
+ for (Node childNode : currentNode.getLinks()) {
+ if (findCycle(childNode))
+ return true;
+ }
+ currentNode.setOnStack(false);
+ return false;
+ }
+
+ public void setExisting(String resource, String owner, OwnershipType operation) {
+ String resourceKey = "r" + resource;
+ Node resourceNode = nodeList.get(resourceKey);
+ if (resourceNode==null) {
+ resourceNode = new Node(resourceKey);
+ nodeList.put(resourceKey, resourceNode);
+ }
+
+ String ownerKey = "o" + owner;
+ Node ownerNode = nodeList.get(ownerKey);
+ if (ownerNode==null) {
+ ownerNode = new Node(ownerKey);
+ nodeList.put(ownerKey, ownerNode);
+ }
+
+ if (operation.equals(OwnershipType.ACQUIRED)) {
+ resourceNode.addLink(ownerNode);
+ ownerNode.removeLink(resourceNode);
+ } else if (operation.equals(OwnershipType.CREATED)) {
+ ownerNode.addLink(resourceNode);
+ resourceNode.removeLink(ownerNode);
+ }
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/MusicCore.java b/music-core/src/main/java/org/onap/music/main/MusicCore.java
new file mode 100644
index 00000000..30d2bc47
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/MusicCore.java
@@ -0,0 +1,264 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.music.datastore.Condition;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.datastore.jsonobjects.JsonDelete;
+import org.onap.music.datastore.jsonobjects.JsonIndex;
+import org.onap.music.datastore.jsonobjects.JsonInsert;
+import org.onap.music.datastore.jsonobjects.JsonKeySpace;
+import org.onap.music.datastore.jsonobjects.JsonSelect;
+import org.onap.music.datastore.jsonobjects.JsonTable;
+import org.onap.music.datastore.jsonobjects.JsonUpdate;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.exceptions.MusicLockingException;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.lockingservice.cassandra.CassaLockStore;
+import org.onap.music.lockingservice.cassandra.LockType;
+import org.onap.music.lockingservice.cassandra.MusicLockState;
+import org.onap.music.service.MusicCoreService;
+
+import com.datastax.driver.core.ResultSet;
+
+public class MusicCore {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class);
+ private static MusicCoreService musicCore = MusicUtil.getMusicCoreService();
+ private static CassaLockStore mLockHandle;
+
+ public static CassaLockStore getmLockHandle() {
+ return mLockHandle;
+ }
+
+ public static void setmLockHandle(CassaLockStore mLockHandleIn) {
+ mLockHandle = mLockHandleIn;
+ }
+
+ /**
+ * Acquire lock
+ *
+ * @param fullyQualifiedKey DO NOT RELY ON THIS KEY WORKING. INCLUDE THE KEY IN THE LOCKID.
+ * @param lockId - the full lock id (key + lockRef)
+ * @return
+ * @throws MusicLockingException
+ * @throws MusicQueryException
+ * @throws MusicServiceException
+ */
+ public static ReturnType acquireLock(String fullyQualifiedKey, String lockId)
+ throws MusicLockingException, MusicQueryException, MusicServiceException {
+ return musicCore.acquireLock(fullyQualifiedKey, lockId);
+ }
+
+ public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod)
+ throws MusicLockingException, MusicQueryException, MusicServiceException {
+ return musicCore.acquireLockWithLease(key, lockId, leasePeriod);
+ }
+
+ public static String createLockReferenceAtomic(String fullyQualifiedKey) throws MusicLockingException {
+ return musicCore.createLockReferenceAtomic(fullyQualifiedKey);
+ }
+
+ public static String createLockReference(String fullyQualifiedKey, String owner) throws MusicLockingException {
+ return musicCore.createLockReference(fullyQualifiedKey, owner);
+ }
+
+ public static String createLockReferenceAtomic(String fullyQualifiedKey, LockType locktype) throws MusicLockingException {
+ return musicCore.createLockReferenceAtomic(fullyQualifiedKey, locktype);
+ }
+
+ public static String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException {
+ return musicCore.createLockReference(fullyQualifiedKey, locktype, owner);
+ }
+
+ public static ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject,
+ String consistency) throws MusicServiceException {
+ return musicCore.createTable(keyspace, table, tableQueryObject, consistency);
+ }
+
+ public static ResultSet quorumGet(PreparedQueryObject query) {
+ return musicCore.quorumGet(query);
+ }
+
+ /**
+ * Gets the top of queue for fullyQualifiedKey
+ *
+ * @param fullyQualifiedKey
+ * @return
+ */
+ public static String whoseTurnIsIt(String fullyQualifiedKey) {
+ return musicCore.whoseTurnIsIt(fullyQualifiedKey);
+ }
+
+ /**
+ * Gets the current lockholder(s) for fullyQualifiedKey
+ *
+ * @param fullyQualifiedKey
+ * @return
+ */
+ public static List<String> getCurrentLockHolders(String fullyQualifiedKey) {
+ return musicCore.getCurrentLockHolders(fullyQualifiedKey);
+ }
+
+ public static ReturnType promoteLock(String lockIdToPromote) throws MusicLockingException {
+ return musicCore.promoteLock(lockIdToPromote);
+ }
+
+ public static void destroyLockRef(String lockId) throws MusicLockingException {
+ musicCore.destroyLockRef(lockId);
+ }
+
+ public static ReturnType eventualPut(PreparedQueryObject queryObject) {
+ return musicCore.eventualPut(queryObject);
+ }
+
+ public static ReturnType eventualPut_nb(PreparedQueryObject queryObject, String keyspace, String tablename,
+ String primaryKey) {
+ return musicCore.eventualPut_nb(queryObject, keyspace, tablename, primaryKey);
+ }
+
+ public static ReturnType criticalPut(String keyspace, String table, String primaryKeyValue,
+ PreparedQueryObject queryObject, String lockReference, Condition conditionInfo) {
+ return musicCore.criticalPut(keyspace, table, primaryKeyValue, queryObject, lockReference, conditionInfo);
+ }
+
+ public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency)
+ throws MusicServiceException,MusicQueryException {
+ return musicCore.nonKeyRelatedPut(queryObject, consistency);
+ }
+
+ public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
+ return musicCore.get(queryObject);
+ }
+
+ public static ResultSet criticalGet(String keyspace, String table, String primaryKeyValue,
+ PreparedQueryObject queryObject, String lockReference) throws MusicServiceException {
+ return musicCore.criticalGet(keyspace, table, primaryKeyValue, queryObject, lockReference);
+ }
+
+ public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
+ PreparedQueryObject queryObject, Condition conditionInfo)
+ throws MusicLockingException, MusicQueryException, MusicServiceException {
+ return musicCore.atomicPut(keyspaceName, tableName, primaryKey, queryObject, conditionInfo);
+ }
+
+ public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
+ PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException {
+ return musicCore.atomicGet(keyspaceName, tableName, primaryKey, queryObject);
+ }
+
+ public static List<String> getLockQueue(String fullyQualifiedKey)
+ throws MusicServiceException, MusicQueryException, MusicLockingException {
+ return musicCore.getLockQueue(fullyQualifiedKey);
+ }
+
+ public static long getLockQueueSize(String fullyQualifiedKey)
+ throws MusicServiceException, MusicQueryException, MusicLockingException {
+ return musicCore.getLockQueueSize(fullyQualifiedKey);
+ }
+
+ public static void deleteLock(String lockName) throws MusicLockingException {
+ musicCore.deleteLock(lockName);
+ }
+
+ public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
+ PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
+ return musicCore.atomicPutWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject, conditionInfo);
+ }
+
+ public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
+ PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
+ return musicCore.atomicGetWithDeleteLock(keyspaceName, tableName, primaryKey, queryObject);
+ }
+
+ public static Map<String, Object> validateLock(String lockName) {
+ return musicCore.validateLock(lockName);
+ }
+
+ public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException {
+ return musicCore.releaseLock(lockId, voluntaryRelease);
+ }
+
+ public static List<String> releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException {
+ return musicCore.releaseAllLocksForOwner(ownerId, keyspace, table);
+ }
+
+ //Added changes for orm implementation.
+
+ public static ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo)
+ throws MusicServiceException, MusicQueryException {
+ return musicCore.createKeyspace(jsonKeySpaceObject,consistencyInfo);
+ }
+
+ public static ResultType dropKeyspace(JsonKeySpace josnKeyspaceObject, String consistencyInfo)
+ throws MusicServiceException,MusicQueryException {
+ return musicCore.dropKeyspace(josnKeyspaceObject, consistencyInfo);
+ }
+
+ public static ResultType createTable(JsonTable jsonTableObject,String consistencyInfo)
+ throws MusicServiceException,MusicQueryException {
+ return musicCore.createTable(jsonTableObject, consistencyInfo);
+ }
+
+ public static ResultType dropTable(JsonTable jsonTableObject, String consistencyInfo)
+ throws MusicServiceException, MusicQueryException {
+ return musicCore.dropTable(jsonTableObject, consistencyInfo);
+ }
+
+ public static ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo)
+ throws MusicServiceException,MusicQueryException {
+ return musicCore.createIndex(jsonIndexObject, consistencyInfo);
+ }
+
+ public static ResultSet select(JsonSelect jsonSelect, MultivaluedMap<String, String> rowParams)
+ throws MusicServiceException, MusicQueryException{
+ return musicCore.select(jsonSelect, rowParams);
+ }
+
+ public static ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException{
+ return musicCore.selectCritical(jsonInsertObj, rowParams);
+ }
+
+
+ public static ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException{
+ return musicCore.insertIntoTable(jsonInsert);
+ }
+
+ public static ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException{
+ return musicCore.updateTable(jsonUpdateObj, rowParams);
+ }
+
+ public static ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException{
+ return musicCore.deleteFromTable(jsonDeleteObj,rowParams);
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/MusicUtil.java b/music-core/src/main/java/org/onap/music/main/MusicUtil.java
new file mode 100644
index 00000000..4b8b1059
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/MusicUtil.java
@@ -0,0 +1,881 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Modifications Copyright (c) 2019 IBM.
+ * Modifications Copyright (c) 2019 Samsung.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+import com.datastax.driver.core.ColumnDefinitions;
+import com.datastax.driver.core.ColumnDefinitions.Definition;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.eelf.logging.format.AppMessages;
+import org.onap.music.eelf.logging.format.ErrorSeverity;
+import org.onap.music.eelf.logging.format.ErrorTypes;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.service.MusicCoreService;
+import org.onap.music.service.impl.MusicCassaCore;
+
+import com.datastax.driver.core.ConsistencyLevel;
+import com.datastax.driver.core.DataType;
+
+/**
+ * @author nelson24
+ *
+ * Properties This will take Properties and load them into MusicUtil.
+ * This is a hack for now. Eventually it would bebest to do this in
+ * another way.
+ *
+ */
+public class MusicUtil {
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
+
+ // Consistancy Constants
+ public static final String ATOMIC = "atomic";
+ public static final String EVENTUAL = "eventual";
+ public static final String CRITICAL = "critical";
+ public static final String EVENTUAL_NB = "eventual_nb";
+ public static final String ALL = "all";
+ public static final String QUORUM = "quorum";
+ public static final String LOCAL_QUORUM = "local_quorum";
+ public static final String ONE = "one";
+ public static final String ATOMICDELETELOCK = "atomic_delete_lock";
+
+ // Header Constants
+ private static final String XLATESTVERSION = "X-latestVersion";
+ private static final String XMINORVERSION = "X-minorVersion";
+ private static final String XPATCHVERSION = "X-patchVersion";
+ public static final String AUTHORIZATION = "Authorization";
+
+ // CQL Constants
+ public static final String SELECT = "select";
+ public static final String INSERT = "insert";
+ public static final String UPDATE = "update";
+ public static final String UPSERT = "upsert";
+ public static final String USERID = "userId";
+ public static final String PASSWORD = "";
+ public static final String CASSANDRA = "cassandra";
+
+ private static final String LOCALHOST = "localhost";
+ private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
+ public static final String DEFAULTKEYSPACENAME = "TBD";
+
+ private static long defaultLockLeasePeriod = 6000;
+ // Amount of times to retry to delete a lock in atomic.
+ private static int retryCount = 3;
+ private static String lockUsing = MusicUtil.CASSANDRA;
+ // Cadi OnOff
+ private static boolean isCadi = false;
+ // Keyspace Creation on/off
+ private static boolean isKeyspaceActive = false;
+ private static boolean debug = true;
+ private static String version = "0.0.0";
+ private static String build = "";
+ private static long lockDaemonSleepms = 1000;
+ private static Set<String> keyspacesToCleanLocks = new HashSet<>();
+
+ private static String musicPropertiesFilePath = PROPERTIES_FILE;
+ // private static final String[] propKeys = new String[] { MusicUtil.class.getDeclaredMethod(arg0, )"build","cassandra.host", "debug",
+ // "version", "music.properties", "lock.lease.period", "cassandra.user",
+ // "cassandra.password", "aaf.endpoint.url","admin.username","admin.password",
+ // "music.namespace","admin.aaf.role","cassandra.port","lock.using","retry.count",
+ // "transId.header.required","conversation.header.required","clientId.header.required",
+ // "messageId.header.required","transId.header.prefix","conversation.header.prefix",
+ // "clientId.header.prefix","messageId.header.prefix"};
+ // Consistency Constants and variables.
+ private static final String[] cosistencyLevel = new String[] {
+ "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO",
+ "THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
+ private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
+ static {
+ consistencyName.put("ONE",ConsistencyLevel.ONE);
+ consistencyName.put("TWO",ConsistencyLevel.TWO);
+ consistencyName.put("THREE",ConsistencyLevel.THREE);
+ consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
+ consistencyName.put("ALL",ConsistencyLevel.ALL);
+ consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
+ consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
+ consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
+ consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
+ consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
+ }
+
+ // Cassandra Values
+ private static String cassName = "cassandra";
+ private static String cassPwd;
+ private static String myCassaHost = LOCALHOST;
+ private static int cassandraPort = 9042;
+ private static int cassandraConnectTimeOutMS;
+ private static int cassandraReadTimeOutMS;
+
+ // AAF
+ private static String musicAafNs = "org.onap.music.cadi";
+
+ // Locking
+ public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
+ public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
+ public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
+
+ // Response/Request tracking headers
+ private static String transIdPrefix = "false";
+ private static String conversationIdPrefix = "false";
+ private static String clientIdPrefix = "false";
+ private static String messageIdPrefix = "false";
+ private static Boolean transIdRequired = false;
+ private static Boolean conversationIdRequired = false;
+ private static Boolean clientIdRequired = false;
+ private static Boolean messageIdRequired = false;
+ private static String cipherEncKey = "";
+
+ private static long createLockWaitPeriod = 300;
+ private static int createLockWaitIncrement = 50;
+
+ public static long getCreateLockWaitPeriod() {
+ return createLockWaitPeriod;
+ }
+
+ public static void setCreateLockWaitPeriod(long createLockWaitPeriod) {
+ MusicUtil.createLockWaitPeriod = createLockWaitPeriod;
+ }
+
+ public static int getCreateLockWaitIncrement() {
+ return createLockWaitIncrement;
+ }
+
+ public static void setCreateLockWaitIncrement(int createLockWaitIncrement) {
+ MusicUtil.createLockWaitIncrement = createLockWaitIncrement;
+ }
+
+ public MusicUtil() {
+ throw new IllegalStateException("Utility Class");
+ }
+
+ public static String getLockUsing() {
+ return lockUsing;
+ }
+
+ public static void setLockUsing(String lockUsing) {
+ MusicUtil.lockUsing = lockUsing;
+ }
+
+ /**
+ *
+ * @return cassandra port
+ */
+ public static int getCassandraPort() {
+ return cassandraPort;
+ }
+
+ /**
+ * set cassandra port
+ * @param cassandraPort
+ */
+ public static void setCassandraPort(int cassandraPort) {
+ MusicUtil.cassandraPort = cassandraPort;
+ }
+ /**
+ * @return the cassName
+ */
+ public static String getCassName() {
+ return cassName;
+ }
+
+ /**
+ * @return the cassPwd
+ */
+ public static String getCassPwd() {
+ return cassPwd;
+ }
+
+ public static int getCassandraConnectTimeOutMS() {
+ return cassandraConnectTimeOutMS;
+ }
+
+ public static void setCassandraConnectTimeOutMS(int cassandraConnectTimeOutMS) {
+ MusicUtil.cassandraConnectTimeOutMS = cassandraConnectTimeOutMS;
+ }
+
+ public static int getCassandraReadTimeOutMS() {
+ return cassandraReadTimeOutMS;
+ }
+
+ public static void setCassandraReadTimeOutMS(int cassandraReadTimeOutMS) {
+ MusicUtil.cassandraReadTimeOutMS = cassandraReadTimeOutMS;
+ }
+
+ /**
+ * Returns An array of property names that should be in the Properties
+ * files.
+ *
+// * @return
+// */
+ // public static String[] getPropkeys() {
+ // return propKeys.clone();
+ // }
+
+ /**
+ * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
+ * property file value - music.properties
+ *
+ * @return
+ */
+ public static String getMusicPropertiesFilePath() {
+ return musicPropertiesFilePath;
+ }
+
+ /**
+ * Set MusicPropertiesFilePath
+ *
+ * @param musicPropertiesFilePath
+ */
+ public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
+ MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
+ }
+
+ /**
+ * Get DefaultLockLeasePeriod - Default = 6000 property file value -
+ * lock.lease.period
+ *
+ * @return
+ */
+ public static long getDefaultLockLeasePeriod() {
+ return defaultLockLeasePeriod;
+ }
+
+ /**
+ * Set DefaultLockLeasePeriod
+ *
+ * @param defaultLockLeasePeriod
+ */
+ public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
+ MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
+ }
+
+ /**
+ * Set Debug
+ *
+ * @param debug
+ */
+ public static void setDebug(boolean debug) {
+ MusicUtil.debug = debug;
+ }
+
+ /**
+ * Is Debug - Default = true property file value - debug
+ *
+ * @return
+ */
+ public static boolean isDebug() {
+ return debug;
+ }
+
+ /**
+ * Set Version
+ *
+ * @param version
+ */
+ public static void setVersion(String version) {
+ MusicUtil.version = version;
+ }
+
+ /**
+ * Return the version property file value - version.
+ *
+ * @return
+ */
+ public static String getVersion() {
+ return version;
+ }
+
+ /**
+ * Set the build of project which is a combination of the
+ * version and the date.
+ *
+ * @param build - version-date.
+ */
+ public static void setBuild(String build) {
+ MusicUtil.build = build;
+ }
+
+ /**
+ * Return the build version-date.
+ */
+ public static String getBuild() {
+ return build;
+ }
+
+ /**
+ * Get MyCassHost - Cassandra Hostname - Default = localhost property file
+ * value - cassandra.host
+ *
+ * @return
+ */
+ public static String getMyCassaHost() {
+ return myCassaHost;
+ }
+
+ /**
+ * Set MyCassHost - Cassandra Hostname
+ *
+ * @param myCassaHost .
+ */
+ public static void setMyCassaHost(String myCassaHost) {
+ MusicUtil.myCassaHost = myCassaHost;
+ }
+
+ /**
+ * Gey default retry count
+ * @return
+ */
+ public static int getRetryCount() {
+ return retryCount;
+ }
+
+ /**
+ * Set retry count
+ * @param retryCount .
+ */
+ public static void setRetryCount(int retryCount) {
+ MusicUtil.retryCount = retryCount;
+ }
+
+
+ /**
+ * This is used to turn keyspace creation api on/off.
+ *
+ */
+ public static void setKeyspaceActive(Boolean keyspaceActive) {
+ MusicUtil.isKeyspaceActive = keyspaceActive;
+ }
+
+ /**
+ * This is used to turn keyspace creation api on/off.
+ * @return boolean isKeyspaceActive
+ */
+ public static boolean isKeyspaceActive() {
+ return isKeyspaceActive;
+ }
+
+ /**
+ * This method depricated as its not used or needed.
+ *
+ * @return String
+ */
+ @Deprecated
+ public static String getTestType() {
+ String testType = "";
+ try {
+ Scanner fileScanner = new Scanner(new File(""));
+ testType = fileScanner.next();// ignore the my id line
+ @SuppressWarnings("unused")
+ String batchSize = fileScanner.next();// ignore the my public ip line
+ fileScanner.close();
+ } catch (FileNotFoundException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
+ }
+ return testType;
+
+ }
+
+ /**
+ * Method to do a Thread Sleep.
+ * Used for adding a delay.
+ *
+ * @param time
+ */
+ public static void sleep(long time) {
+ try {
+ Thread.sleep(time);
+ } catch (InterruptedException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ /**
+ * Utility function to check if the query object is valid.
+ *
+ * @param withparams
+ * @param queryObject
+ * @return
+ */
+ public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
+ if (withparams) {
+ int noOfValues = queryObject.getValues().size();
+ int noOfParams = 0;
+ char[] temp = queryObject.getQuery().toCharArray();
+ for (int i = 0; i < temp.length; i++) {
+ if (temp[i] == '?')
+ noOfParams++;
+ }
+ return (noOfValues == noOfParams);
+ } else {
+ return !queryObject.getQuery().isEmpty();
+ }
+
+ }
+
+ public static void setCassName(String cassName) {
+ MusicUtil.cassName = cassName;
+ }
+
+ public static void setCassPwd(String cassPwd) {
+ MusicUtil.cassPwd = cassPwd;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
+
+ String value = "";
+ switch (type.getName()) {
+ case UUID:
+ value = valueObj + "";
+ break;
+ case TEXT:
+ case VARCHAR:
+ String valueString = valueObj + "";
+ valueString = valueString.replace("'", "''");
+ value = "'" + valueString + "'";
+ break;
+ case MAP: {
+ Map<String, Object> otMap = (Map<String, Object>) valueObj;
+ value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
+ break;
+ }
+ default:
+ value = valueObj + "";
+ break;
+ }
+ return value;
+ }
+
+ /**
+ *
+ * @param colType
+ * @param valueObj
+ * @return
+ * @throws MusicTypeConversionException
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
+ String valueObjString = valueObj + "";
+ switch (colType.getName()) {
+ case UUID:
+ return UUID.fromString(valueObjString);
+ case VARINT:
+ return BigInteger.valueOf(Long.parseLong(valueObjString));
+ case BIGINT:
+ return Long.parseLong(valueObjString);
+ case INT:
+ return Integer.parseInt(valueObjString);
+ case FLOAT:
+ return Float.parseFloat(valueObjString);
+ case DOUBLE:
+ return Double.parseDouble(valueObjString);
+ case BOOLEAN:
+ return Boolean.parseBoolean(valueObjString);
+ case MAP:
+ return (Map<String, Object>) valueObj;
+ case LIST:
+ return valueObj;
+ case BLOB:
+
+ default:
+ return valueObjString;
+ }
+ }
+
+ public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
+
+ return ByteBuffer.wrap(valueObj);
+ }
+
+ /**
+ *
+ * Utility function to parse json map into sql like string
+ *
+ * @param jMap
+ * @param lineDelimiter
+ * @return
+ */
+
+ public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
+ StringBuilder sqlString = new StringBuilder();
+ int counter = 0;
+ for (Map.Entry<String, Object> entry : jMap.entrySet()) {
+ Object ot = entry.getValue();
+ String value = ot + "";
+ if (ot instanceof String) {
+ value = "'" + value.replace("'", "''") + "'";
+ }
+ sqlString.append("'" + entry.getKey() + "':" + value);
+ if (counter != jMap.size() - 1)
+ sqlString.append(lineDelimiter);
+ counter = counter + 1;
+ }
+ return sqlString.toString();
+ }
+
+ @SuppressWarnings("unused")
+ public static String buildVersion(String major, String minor, String patch) {
+ if (minor != null) {
+ major += "." + minor;
+ if (patch != null) {
+ major += "." + patch;
+ }
+ }
+ return major;
+ }
+
+ /**
+ * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
+ * X-latestVerstion will be equal to the latest full version.
+ * X-minorVersion - will be equal to the latest minor version.
+ * X-pathVersion - will be equal to the latest patch version.
+ * Future plans will change this.
+ * @param response
+ * @param major
+ * @param minor
+ * @param patch
+ * @return
+ */
+ public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
+ ResponseBuilder response = Response.noContent();
+ String versionIn = buildVersion(major,minor,patch);
+ String version = MusicUtil.getVersion();
+ String[] verArray = version.split("\\.",3);
+ if ( minor != null ) {
+ response.header(XMINORVERSION,minor);
+ } else {
+ response.header(XMINORVERSION,verArray[1]);
+ }
+ if ( patch != null ) {
+ response.header(XPATCHVERSION,patch);
+ } else {
+ response.header(XPATCHVERSION,verArray[2]);
+ }
+ response.header(XLATESTVERSION,version);
+ logger.info(EELFLoggerDelegate.auditLogger,"Version In:" + versionIn);
+ return response;
+ }
+
+ public static boolean isValidConsistency(String consistency) {
+ for (String string : cosistencyLevel) {
+ if (string.equalsIgnoreCase(consistency))
+ return true;
+ }
+ return false;
+
+ }
+
+ public static ConsistencyLevel getConsistencyLevel(String consistency) {
+ return consistencyName.get(consistency.toUpperCase());
+ }
+
+ /**
+ * Given the time of write for an update in a critical section, this method provides a transformed timestamp
+ * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
+ * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
+ * @param the UUID lock reference associated with the write.
+ * @param the long timeOfWrite which is the actual time at which the write took place
+ * @throws MusicServiceException
+ * @throws MusicQueryException
+ */
+ public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException{
+ // TODO: use acquire time instead of music eternity epoch
+ return ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
+ }
+
+ public static MusicCoreService getMusicCoreService() {
+ if(getLockUsing().equals(MusicUtil.CASSANDRA))
+ return MusicCassaCore.getInstance();
+ else
+ return MusicCassaCore.getInstance();
+ }
+
+ /**
+ * @param lockName
+ * @return
+ */
+ public static Map<String, Object> validateLock(String lockName) {
+ Map<String, Object> resultMap = new HashMap<>();
+ String[] locks = lockName.split("\\.");
+ if(locks.length < 3) {
+ resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
+ return resultMap;
+ }
+ String keyspace= locks[0];
+ if(keyspace.startsWith("$"))
+ keyspace = keyspace.substring(1);
+ resultMap.put("keyspace",keyspace);
+ return resultMap;
+ }
+
+
+ public static void setIsCadi(boolean isCadi) {
+ MusicUtil.isCadi = isCadi;
+ }
+
+ public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
+ PreparedQueryObject updateQuery, String keyspace, String table,
+ Object cqlFormattedPrimaryKeyValue)
+ throws Exception {
+ try {
+ ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
+ // write it back to a quorum
+ Row row = results.one();
+ ColumnDefinitions colInfo = row.getColumnDefinitions();
+ int totalColumns = colInfo.size();
+ int counter = 1;
+ StringBuilder fieldValueString = new StringBuilder("");
+ for (Definition definition : colInfo) {
+ String colName = definition.getName();
+ if (colName.equals(primaryKeyName))
+ continue;
+ DataType colType = definition.getType();
+ Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
+ Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
+ fieldValueString.append(colName + " = ?");
+ updateQuery.addValue(valueString);
+ if (counter != (totalColumns - 1))
+ fieldValueString.append(",");
+ counter = counter + 1;
+ }
+ updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
+ + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
+ updateQuery.addValue(cqlFormattedPrimaryKeyValue);
+
+ MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
+ } catch (MusicServiceException | MusicQueryException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
+ ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR, e);
+ }
+ }
+
+ public static boolean getIsCadi() {
+ return MusicUtil.isCadi;
+ }
+
+
+ /**
+ * @return a random uuid
+ */
+ public static String generateUUID() {
+ String uuid = UUID.randomUUID().toString();
+ logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
+ return uuid;
+ }
+
+ private static String checkPrefix(String prefix){
+ if (prefix == null || "".equals(prefix) || prefix.endsWith("-")) {
+ return prefix;
+ } else {
+ return prefix + "-";
+ }
+ }
+
+ /**
+ * @return the transIdPrefix
+ */
+ public static String getTransIdPrefix() {
+ return transIdPrefix;
+ }
+
+ /**
+ * @param transIdPrefix the transIdPrefix to set
+ */
+ public static void setTransIdPrefix(String transIdPrefix) {
+ MusicUtil.transIdPrefix = checkPrefix(transIdPrefix);
+ }
+
+ /**
+ * @return the conversationIdPrefix
+ */
+ public static String getConversationIdPrefix() {
+ return conversationIdPrefix;
+ }
+
+ /**
+ * @param conversationIdPrefix the conversationIdPrefix to set
+ */
+ public static void setConversationIdPrefix(String conversationIdPrefix) {
+ MusicUtil.conversationIdPrefix = checkPrefix(conversationIdPrefix);
+ }
+
+ /**
+ * @return the clientIdPrefix
+ */
+ public static String getClientIdPrefix() {
+ return clientIdPrefix;
+ }
+
+ /**
+ * @param clientIdPrefix the clientIdPrefix to set
+ */
+ public static void setClientIdPrefix(String clientIdPrefix) {
+ MusicUtil.clientIdPrefix = checkPrefix(clientIdPrefix);
+ }
+
+ /**
+ * @return the messageIdPrefix
+ */
+ public static String getMessageIdPrefix() {
+ return messageIdPrefix;
+ }
+
+ /**
+ * @param messageIdPrefix the messageIdPrefix to set
+ */
+ public static void setMessageIdPrefix(String messageIdPrefix) {
+ MusicUtil.messageIdPrefix = checkPrefix(messageIdPrefix);
+ }
+
+ /**
+ * @return the transIdRequired
+ */
+ public static Boolean getTransIdRequired() {
+ return transIdRequired;
+ }
+
+
+ /**
+ * @param transIdRequired the transIdRequired to set
+ */
+ public static void setTransIdRequired(Boolean transIdRequired) {
+ MusicUtil.transIdRequired = transIdRequired;
+ }
+
+
+ /**
+ * @return the conversationIdRequired
+ */
+ public static Boolean getConversationIdRequired() {
+ return conversationIdRequired;
+ }
+
+
+ /**
+ * @param conversationIdRequired the conversationIdRequired to set
+ */
+ public static void setConversationIdRequired(Boolean conversationIdRequired) {
+ MusicUtil.conversationIdRequired = conversationIdRequired;
+ }
+
+
+ /**
+ * @return the clientIdRequired
+ */
+ public static Boolean getClientIdRequired() {
+ return clientIdRequired;
+ }
+
+
+ /**
+ * @param clientIdRequired the clientIdRequired to set
+ */
+ public static void setClientIdRequired(Boolean clientIdRequired) {
+ MusicUtil.clientIdRequired = clientIdRequired;
+ }
+
+
+ /**
+ * @return the messageIdRequired
+ */
+ public static Boolean getMessageIdRequired() {
+ return messageIdRequired;
+ }
+
+ /**
+ * @param messageIdRequired the messageIdRequired to set
+ */
+ public static void setMessageIdRequired(Boolean messageIdRequired) {
+ MusicUtil.messageIdRequired = messageIdRequired;
+ }
+
+ /**
+ * @return the sleep time, in milliseconds, for the lock cleanup daemon
+ */
+ public static long getLockDaemonSleepTimeMs() {
+ return lockDaemonSleepms;
+ }
+
+ /**
+ * set the sleep time, in milliseconds, for the lock cleanup daemon
+ */
+ public static void setLockDaemonSleepTimeMs(long timeoutms) {
+ MusicUtil.lockDaemonSleepms = timeoutms;
+ }
+
+ public static Set<String> getKeyspacesToCleanLocks() {
+ return keyspacesToCleanLocks;
+ }
+
+ public static void setKeyspacesToCleanLocks(Set<String> keyspaces) {
+ MusicUtil.keyspacesToCleanLocks = keyspaces;
+ }
+
+ public static String getCipherEncKey() {
+ return MusicUtil.cipherEncKey;
+ }
+
+
+ public static void setCipherEncKey(String cipherEncKey) {
+ MusicUtil.cipherEncKey = cipherEncKey;
+ if ( null == cipherEncKey || cipherEncKey.equals("") ||
+ cipherEncKey.equals("nothing to see here")) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Missing Cipher Encryption Key.");
+ }
+ }
+
+ public static String getMusicAafNs() {
+ return MusicUtil.musicAafNs;
+ }
+
+
+ public static void setMusicAafNs(String musicAafNs) {
+ MusicUtil.musicAafNs = musicAafNs;
+ }
+
+
+
+}
+
diff --git a/music-core/src/main/java/org/onap/music/main/ResultType.java b/music-core/src/main/java/org/onap/music/main/ResultType.java
new file mode 100644
index 00000000..f5ef2070
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/ResultType.java
@@ -0,0 +1,42 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+public enum ResultType {
+ SUCCESS("Success"), FAILURE("Failure"),
+ SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"),
+ BODYMISSING("Incomplete Request body. Please correct your input request and retry.");
+
+ private String result;
+
+ ResultType(String result) {
+ this.result = result;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+}
+
+
diff --git a/music-core/src/main/java/org/onap/music/main/ReturnType.java b/music-core/src/main/java/org/onap/music/main/ReturnType.java
new file mode 100644
index 00000000..f02dabbf
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/ReturnType.java
@@ -0,0 +1,75 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.main;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class ReturnType {
+ private ResultType result;
+ private String message;
+
+ private String timingInfo;
+
+ public ReturnType(ResultType result, String message) {
+ super();
+ this.result = result;
+ this.message = message;
+ }
+
+ public String getTimingInfo() {
+ return timingInfo;
+ }
+
+ public void setTimingInfo(String timingInfo) {
+ this.timingInfo = timingInfo;
+ }
+
+ public ResultType getResult() {
+ return result;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String toJson() {
+ return "{ \"result\":\"" + result.getResult() + "\", \"message\":\"" + message + "\"}";
+ }
+
+ public String toString() {
+ return result + " | " + message;
+ }
+
+ public Map<String, Object> toMap() {
+ Map<String, Object> newMap = new HashMap<>();
+ newMap.put("result", result.getResult());
+ newMap.put("message", message);
+ return newMap;
+ }
+
+}