diff options
author | Thomas Nelson Jr (arthurdent3) <tn1381@att.com> | 2018-02-20 16:50:44 -0500 |
---|---|---|
committer | Thomas Nelson Jr (arthurdent3) <tn1381@att.com> | 2018-02-20 16:50:44 -0500 |
commit | 3acbae6bf3be04f352bfaac340b8303064a2f7c4 (patch) | |
tree | ed5df3391216742cb9bfd20dc798dd5a246bc962 /src | |
parent | dffae1c7c5cd1f50e2456948942cd7716837a7f2 (diff) |
Applying bug fixes
To many overlapping changes so including all of them.
When pushing individually build was breaking.
Issue-ID: MUSIC-33,MUSIC-34,MUSIC-35,MUSIC-36,MUSIC-37
Change-Id: I15b6f7c683d0d2eeadd99c2376dedd6c43a67a8c
Signed-off-by: Thomas Nelson Jr (arthurdent3) <tn1381@att.com>
Diffstat (limited to 'src')
22 files changed, 1090 insertions, 1020 deletions
diff --git a/src/main/java/org/onap/music/client/MusicClient.java b/src/main/java/org/onap/music/client/MusicClient.java index 2d29e236..e67c98a4 100644 --- a/src/main/java/org/onap/music/client/MusicClient.java +++ b/src/main/java/org/onap/music/client/MusicClient.java @@ -32,6 +32,7 @@ import java.util.Set; import org.onap.music.datastore.jsonobjects.JsonInsert; import org.onap.music.datastore.jsonobjects.JsonKeySpace; import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.lockingservice.MusicLockingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,7 +60,7 @@ import com.datastax.driver.core.querybuilder.Select; * @author Robert Eby */ public class MusicClient { - private static final Logger LOG = LoggerFactory.getLogger(MusicClient.class); + private EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(MusicClient.class); private final String[] music_hosts; // array of hosts in the music cluster private Cluster cluster; // MUSIC Cassandra cluster @@ -229,7 +230,7 @@ public class MusicClient { String query = String.format( "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { %s } %s;", keyspaceName, jsonMaptoSqlString(replicationInfo, ","), durability); - LOG.debug(query); + LOG.info(EELFLoggerDelegate.applicationLogger,query); executeCreateQuery(query, consistency); return true; } @@ -237,7 +238,7 @@ public class MusicClient { public boolean dropKeyspace(String keyspaceName, JsonKeySpace kspObject) throws Exception { String consistency = extractConsistencyInfo(keyspaceName, kspObject.getConsistencyInfo()); String query = String.format("DROP KEYSPACE %s;", keyspaceName); - LOG.debug(query); + LOG.info(EELFLoggerDelegate.applicationLogger,query); executeCreateQuery(query, consistency); return false; } @@ -263,33 +264,9 @@ public class MusicClient { prefix = ", "; } - // information about the name-value style properties - // Map<String,Object> propertiesMap = tableObj.getProperties(); - // String propertiesString=""; - // if(propertiesMap != null){ - // counter =0; - // for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) - // { - // Object ot = entry.getValue(); - // String value = ot+""; - // if(ot instanceof String){ - // value = "'"+value+"'"; - // }else if(ot instanceof Map){ - // Map<String,Object> otMap = (Map<String,Object>)ot; - // value = "{"+jsonMaptoSqlString(otMap, ",")+"}"; - // } - // propertiesString = propertiesString+entry.getKey()+"="+ value+""; - // if(counter!=propertiesMap.size()-1) - // propertiesString = propertiesString+" AND "; - // counter = counter +1; - // } - // } - String query = String.format("CREATE TABLE IF NOT EXISTS %s (%s);", tablename, fields.toString()); - // if (propertiesMap != null) - // query = query + " WITH "+ propertiesString; - + LOG.debug(query); String consistency = extractConsistencyInfo(tablename, tableObj.getConsistencyInfo()); executeCreateQuery(query, consistency); @@ -327,7 +304,7 @@ public class MusicClient { String suffix = getTTLSuffix(insObj); String query = String.format("INSERT INTO %s (%s) VALUES (%s)%s;", tablename, fields.toString(), values.toString(), suffix); - LOG.debug(query); + LOG.info(EELFLoggerDelegate.applicationLogger,query); String consistency = extractConsistencyInfo(tablename, consistencyInfo); executeCreateQuery(query, consistency); diff --git a/src/main/java/org/onap/music/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java index c67c72e1..6ced1e48 100644 --- a/src/main/java/org/onap/music/datastore/MusicDataStore.java +++ b/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -29,11 +29,10 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.main.MusicUtil; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; @@ -53,6 +52,7 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException; * */ public class MusicDataStore { + private Session session; private Cluster cluster; @@ -72,10 +72,9 @@ public class MusicDataStore { this.cluster = cluster; } - /** - * - */ - private static EELFLogger logger = EELFManager.getInstance().getLogger(MusicDataStore.class); + + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class); /** * @@ -103,7 +102,7 @@ public class MusicDataStore { try { connectToCassaCluster(remoteIp); } catch (MusicServiceException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } } @@ -124,7 +123,7 @@ public class MusicDataStore { } } } catch (SocketException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } return allPossibleIps; } @@ -136,22 +135,23 @@ public class MusicDataStore { private void connectToCassaCluster() { Iterator<String> it = getAllPossibleLocalIps().iterator(); String address = "localhost"; - logger.info("Connecting to cassa cluster: Iterating through possible ips:" - + getAllPossibleLocalIps()); + logger.info(EELFLoggerDelegate.applicationLogger, + "Connecting to cassa cluster: Iterating through possible ips:" + + getAllPossibleLocalIps()); while (it.hasNext()) { try { cluster = Cluster.builder().withPort(9042) .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd()) .addContactPoint(address).build(); Metadata metadata = cluster.getMetadata(); - logger.info("Connected to cassa cluster " + metadata.getClusterName() + " at " - + address); + logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster " + + metadata.getClusterName() + " at " + address); session = cluster.connect(); break; } catch (NoHostAvailableException e) { address = it.next(); - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } } } @@ -173,11 +173,12 @@ public class MusicDataStore { .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd()) .addContactPoint(address).build(); Metadata metadata = cluster.getMetadata(); - logger.info("Connected to cassa cluster " + metadata.getClusterName() + " at " + address); + logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster " + + metadata.getClusterName() + " at " + address); try { session = cluster.connect(); } catch (Exception ex) { - logger.error(ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); throw new MusicServiceException( "Error while connecting to Cassandra cluster.. " + ex.getMessage()); } @@ -299,27 +300,31 @@ public class MusicDataStore { boolean result = false; if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error("Error while processing prepared query object"); + logger.error(EELFLoggerDelegate.errorLogger, + "Error while processing prepared query object"); throw new MusicQueryException("Ill formed queryObject for the request = " + "[" + queryObject.getQuery() + "]"); } - logger.info("In preprared Execute Put: the actual insert query:" + queryObject.getQuery() - + "; the values" + queryObject.getValues()); + logger.info(EELFLoggerDelegate.applicationLogger, + "In preprared Execute Put: the actual insert query:" + + queryObject.getQuery() + "; the values" + + queryObject.getValues()); PreparedStatement preparedInsert = session.prepare(queryObject.getQuery()); try { if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { - logger.info("Executing critical put query"); + logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query"); preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM); } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { - logger.info("Executing simple put query"); + logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query"); preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE); } - session.execute(preparedInsert.bind(queryObject.getValues().toArray())); - result = true; + ResultSet rs = session.execute(preparedInsert.bind(queryObject.getValues().toArray())); + result = rs.wasApplied(); + } catch (Exception e) { - logger.error("Executing Session Failure for Request = " + "[" + queryObject.getQuery() - + "]" + " Reason = " + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Executing Session Failure for Request = " + + "[" + queryObject.getQuery() + "]" + " Reason = " + e.getMessage()); throw new MusicServiceException("Executing Session Failure for Request = " + "[" + queryObject.getQuery() + "]" + " Reason = " + e.getMessage()); } @@ -343,7 +348,8 @@ public class MusicDataStore { throw new MusicQueryException("Ill formed queryObject for the request = " + "[" + queryObject.getQuery() + "]"); } - logger.info("Executing Eventual get query:" + queryObject.getQuery()); + logger.info(EELFLoggerDelegate.applicationLogger, + "Executing Eventual get query:" + queryObject.getQuery()); PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery()); preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE); ResultSet results = null; @@ -351,7 +357,7 @@ public class MusicDataStore { results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); } catch (Exception ex) { - logger.error(ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); throw new MusicServiceException(ex.getMessage()); } return results; @@ -369,23 +375,23 @@ public class MusicDataStore { public ResultSet executeCriticalGet(PreparedQueryObject queryObject) throws MusicServiceException, MusicQueryException { if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) { - logger.error("Error processing Prepared Query Object"); + logger.error(EELFLoggerDelegate.errorLogger, "Error processing Prepared Query Object"); throw new MusicQueryException("Ill formed queryObject for the request = " + "[" + queryObject.getQuery() + "]"); } - logger.info("Executing Critical get query:" + queryObject.getQuery()); + logger.info(EELFLoggerDelegate.applicationLogger, + "Executing Critical get query:" + queryObject.getQuery()); PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery()); preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM); ResultSet results = null; try { results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray())); } catch (Exception ex) { - logger.error(ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); throw new MusicServiceException(ex.getMessage()); } return results; } - } diff --git a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java index 27ae4712..0c290b6f 100644 --- a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java +++ b/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java @@ -166,7 +166,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { * @param msg */ public void info(EELFLogger logger, String msg) { - logger.info(msg); + logger.info(className + " - "+msg); } /** @@ -230,7 +230,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { * @param msg */ public void error(EELFLogger logger, String msg) { - logger.error(msg); + logger.error(className+ " - " + msg); } /** diff --git a/src/main/java/org/onap/music/lockingservice/MusicLockState.java b/src/main/java/org/onap/music/lockingservice/MusicLockState.java index 23661ad4..10cdc0e7 100644 --- a/src/main/java/org/onap/music/lockingservice/MusicLockState.java +++ b/src/main/java/org/onap/music/lockingservice/MusicLockState.java @@ -29,9 +29,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.onap.music.main.MusicCore; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.onap.music.eelf.logging.EELFLoggerDelegate; // the state variable that will be stored in zookeeper, capturing the transitions of public class MusicLockState implements Serializable { @@ -39,7 +37,7 @@ public class MusicLockState implements Serializable { UNLOCKED, BEING_LOCKED, LOCKED };// captures the state of the lock - private static EELFLogger logger = EELFManager.getInstance().getLogger(MusicLockState.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicLockState.class); LockStatus lockStatus; boolean needToSyncQuorum = false; String lockHolder; @@ -106,7 +104,7 @@ public class MusicLockState implements Serializable { out = new ObjectOutputStream(bos); out.writeObject(this); } catch (IOException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return bos.toByteArray(); } @@ -119,7 +117,7 @@ public class MusicLockState implements Serializable { in = new ObjectInputStream(bis); o = in.readObject(); } catch (ClassNotFoundException | IOException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return (MusicLockState) o; } diff --git a/src/main/java/org/onap/music/lockingservice/MusicLockingService.java b/src/main/java/org/onap/music/lockingservice/MusicLockingService.java index 59b502ca..9b21f596 100644 --- a/src/main/java/org/onap/music/lockingservice/MusicLockingService.java +++ b/src/main/java/org/onap/music/lockingservice/MusicLockingService.java @@ -1,20 +1,16 @@ /* - * ============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 + * ============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 + * 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. + * 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============================================= * ==================================================================== @@ -25,28 +21,26 @@ package org.onap.music.lockingservice; import java.io.IOException; import java.util.StringTokenizer; import java.util.concurrent.CountDownLatch; + import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; -import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; import org.apache.zookeeper.ZooKeeper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.music.datastore.MusicDataStore; import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; + public class MusicLockingService implements Watcher { + private static final int SESSION_TIMEOUT = 180000; ZkStatelessLockService zkLockHandle = null; private CountDownLatch connectedSignal = new CountDownLatch(1); - private static EELFLogger logger = - EELFManager.getInstance().getLogger(MusicLockingService.class); - // private static EELFLoggerDelegate logger = - // EELFLoggerDelegate.getLogger(MusicLockingService.class); + private static EELFLoggerDelegate logger = + EELFLoggerDelegate.getLogger(MusicLockingService.class); public MusicLockingService() throws MusicServiceException { try { @@ -54,10 +48,10 @@ public class MusicLockingService implements Watcher { connectedSignal.await(); zkLockHandle = new ZkStatelessLockService(zk); } catch (IOException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); throw new MusicServiceException("IO Error has occured" + e.getMessage()); } catch (InterruptedException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); throw new MusicServiceException("Exception Occured " + e.getMessage()); } } @@ -72,7 +66,7 @@ public class MusicLockingService implements Watcher { connectedSignal.await(); zkLockHandle = new ZkStatelessLockService(zk); } catch (IOException | InterruptedException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } } @@ -90,10 +84,18 @@ public class MusicLockingService implements Watcher { zkLockHandle.setNodeData(lockName, data); } - public MusicLockState getLockState(String lockName) { + public MusicLockState getLockState(String lockName) throws MusicLockingException { - byte[] data = zkLockHandle.getNodeData(lockName); + byte[] data = null; + try{ + data = zkLockHandle.getNodeData(lockName); + }catch (Exception ex){ + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage()); + } + if(data !=null) return MusicLockState.deSerialize(data); + else + throw new MusicLockingException("Invalid lock or acquire failed"); } public String createLockId(String lockName) { @@ -108,7 +110,7 @@ public class MusicLockingService implements Watcher { try { return zkLockHandle.lock(lockName, lockId); } catch (KeeperException | InterruptedException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } return false; } @@ -139,4 +141,9 @@ public class MusicLockingService implements Watcher { zkLockHandle.close(); } + public boolean lockIdExists(String lockIdWithDollar) { + String lockId = lockIdWithDollar.replace('$', '/'); + return zkLockHandle.checkIfLockExists(lockId); + } + } diff --git a/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java b/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java index 37ae9e96..df4d6ad6 100644 --- a/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java +++ b/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java @@ -29,6 +29,7 @@ import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.lockingservice.ZooKeeperOperation; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -40,7 +41,7 @@ import java.util.concurrent.atomic.AtomicBoolean; * */ class ProtocolSupport { - private static final Logger LOG = LoggerFactory.getLogger(ProtocolSupport.class); + private EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ProtocolSupport.class); protected ZooKeeper zookeeper; private AtomicBoolean closed = new AtomicBoolean(false); @@ -128,7 +129,7 @@ class ProtocolSupport { try { return operation.execute(); } catch (KeeperException.SessionExpiredException e) { - LOG.warn("Session expired for: " + zookeeper + " so reconnecting due to: " + e, e); + LOG.debug("Session expired for: " + zookeeper + " so reconnecting due to: " + e, e); throw e; } catch (KeeperException.ConnectionLossException e) { if (exception == null) { @@ -173,9 +174,9 @@ class ProtocolSupport { } }); } catch (KeeperException e) { - LOG.warn("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger,"Caught: " + e, e); } catch (InterruptedException e) { - LOG.warn("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger,"Caught: " + e, e); } } @@ -198,7 +199,7 @@ class ProtocolSupport { try { Thread.sleep(attemptCount * retryDelay); } catch (InterruptedException e) { - LOG.debug("Failed to sleep: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger,"Failed to sleep: " + e, e); } } } diff --git a/src/main/java/org/onap/music/lockingservice/ZNodeName.java b/src/main/java/org/onap/music/lockingservice/ZNodeName.java index c8d14cba..eefc81a9 100644 --- a/src/main/java/org/onap/music/lockingservice/ZNodeName.java +++ b/src/main/java/org/onap/music/lockingservice/ZNodeName.java @@ -21,8 +21,7 @@ */ package org.onap.music.lockingservice; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.onap.music.eelf.logging.EELFLoggerDelegate; /** * Represents an ephemeral znode name which has an ordered sequence number and can be sorted in @@ -33,8 +32,8 @@ class ZNodeName implements Comparable<ZNodeName> { private final String name; private String prefix; private int sequence = -1; - private static EELFLogger LOG = EELFManager.getInstance().getLogger(ZNodeName.class); - + private EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ZNodeName.class); + public ZNodeName(String name) { if (name == null) { throw new NullPointerException("id cannot be null"); @@ -49,9 +48,9 @@ class ZNodeName implements Comparable<ZNodeName> { // If an exception occurred we misdetected a sequence suffix, // so return -1. } catch (NumberFormatException e) { - LOG.info("Number format exception for " + idx, e); + LOG.error(EELFLoggerDelegate.errorLogger,"Number format exception for " + idx, e); } catch (ArrayIndexOutOfBoundsException e) { - LOG.info("Array out of bounds for " + idx, e); + LOG.error(EELFLoggerDelegate.errorLogger,"Array out of bounds for " + idx, e); } } } diff --git a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java index 99ccd4db..bd8ddfe3 100644 --- a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java +++ b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java @@ -1,26 +1,23 @@ /* - * ============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 + * ============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 + * 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. + * 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.lockingservice; + import java.util.List; import java.util.SortedSet; import java.util.TreeSet; @@ -30,8 +27,7 @@ import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.onap.music.eelf.logging.EELFLoggerDelegate; /** * A <a href="package.html">protocol to implement an exclusive write lock or to elect a leader</a>. @@ -48,8 +44,8 @@ public class ZkStatelessLockService extends ProtocolSupport { zookeeper = zk; } - private static EELFLogger LOG = - EELFManager.getInstance().getLogger(ZkStatelessLockService.class); + private static EELFLoggerDelegate LOG = + EELFLoggerDelegate.getLogger(ZkStatelessLockService.class); protected void createLock(final String path, final byte[] data) { final List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE; @@ -61,9 +57,9 @@ public class ZkStatelessLockService extends ProtocolSupport { } }); } catch (KeeperException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); } } @@ -71,7 +67,7 @@ public class ZkStatelessLockService extends ProtocolSupport { try { zookeeper.close(); } catch (InterruptedException e) { - LOG.info(e.getMessage()); + LOG.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } } @@ -85,9 +81,9 @@ public class ZkStatelessLockService extends ProtocolSupport { } }); } catch (KeeperException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); } } @@ -99,10 +95,8 @@ public class ZkStatelessLockService extends ProtocolSupport { else return null; - } catch (KeeperException e) { - LOG.info("Caught: " + e, e); - } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + } catch (KeeperException | InterruptedException e) { + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); } return null; } @@ -114,10 +108,8 @@ public class ZkStatelessLockService extends ProtocolSupport { if (stat != null) { result = true; } - } catch (KeeperException e) { - LOG.info(e.getMessage()); - } catch (InterruptedException e) { - LOG.info(e.getMessage()); + } catch (KeeperException | InterruptedException e) { + LOG.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } return result; } @@ -129,13 +121,10 @@ public class ZkStatelessLockService extends ProtocolSupport { public String createLockId(String dir) { ensurePathExists(dir); LockZooKeeperOperation zop = new LockZooKeeperOperation(dir); - try { retryOperation(zop); - } catch (KeeperException e) { - LOG.info(e.getMessage()); - } catch (InterruptedException e) { - LOG.info(e.getMessage()); + } catch (KeeperException | InterruptedException e) { + LOG.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } return zop.getId(); } @@ -172,13 +161,13 @@ public class ZkStatelessLockService extends ProtocolSupport { }; zopdel.execute(); } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); // set that we have been interrupted. Thread.currentThread().interrupt(); } catch (KeeperException.NoNodeException e) { // do nothing } catch (KeeperException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e); } } @@ -198,13 +187,13 @@ public class ZkStatelessLockService extends ProtocolSupport { } return sortedNames.first().getName(); } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); // set that we have been interrupted. Thread.currentThread().interrupt(); } catch (KeeperException.NoNodeException e) { // do nothing } catch (KeeperException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e); } } @@ -227,13 +216,13 @@ public class ZkStatelessLockService extends ProtocolSupport { }; zopdel.execute(); } catch (InterruptedException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); // set that we have been interrupted. Thread.currentThread().interrupt(); } catch (KeeperException.NoNodeException e) { // do nothing } catch (KeeperException e) { - LOG.info("Caught: " + e, e); + LOG.error(EELFLoggerDelegate.errorLogger, "Caught: " + e, e); throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e); } } @@ -292,8 +281,8 @@ public class ZkStatelessLockService extends ProtocolSupport { if (id != null) { List<String> names = zookeeper.getChildren(dir, false); if (names.isEmpty()) { - LOG.info("No children in: " + dir + " when we've just " - + "created one! Lets recreate it..."); + LOG.info(EELFLoggerDelegate.applicationLogger, "No children in: " + dir + + " when we've just " + "created one! Lets recreate it..."); // lets force the recreation of the id id = null; } else { @@ -318,8 +307,9 @@ public class ZkStatelessLockService extends ProtocolSupport { if (stat != null) { return Boolean.FALSE; } else { - LOG.info("Could not find the" + " stats for less than me: " - + lastChildName.getName()); + LOG.info(EELFLoggerDelegate.applicationLogger, + "Could not find the" + " stats for less than me: " + + lastChildName.getName()); } } else return Boolean.TRUE; diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java index 0ab055df..cd1d565d 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/main/CachingUtil.java @@ -32,12 +32,13 @@ import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; import org.apache.commons.jcs.JCS; import org.apache.commons.jcs.access.CacheAccess; -import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; +import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.AAFResponse; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicServiceException; + import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -53,7 +54,7 @@ import com.sun.jersey.api.client.WebResource; */ public class CachingUtil implements Runnable { - private static EELFLogger logger = EELFManager.getInstance().getLogger(CachingUtil.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class); private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache"); private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache"); @@ -68,16 +69,13 @@ public class CachingUtil implements Runnable { } public void initializeMusicCache() { - logger.info("Initializing Music Cache..."); + logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache..."); musicCache.put("isInitialized", "true"); } - public void initializeAafCache() { - logger.info("Resetting and initializing AAF Cache..."); + public void initializeAafCache() throws MusicServiceException { + logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache..."); - // aafCache.clear(); - // loop through aafCache ns .. only the authenticated ns will be re cached. and non - // authenticated will wait for user to retry. String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering"; PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString(query); @@ -85,7 +83,7 @@ public class CachingUtil implements Runnable { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false)); } catch (Exception e1) { e1.printStackTrace(); - logger.error("Exception is " + e1.getMessage() + "during initalizeAafCache"); + logger.error(EELFLoggerDelegate.errorLogger,"Exception is "+ e1.getMessage() + "during initalizeAafCache"); } ResultSet rs = MusicCore.get(pQuery); Iterator<Row> it = rs.iterator(); @@ -121,7 +119,11 @@ public class CachingUtil implements Runnable { @Override public void run() { logger.debug("Scheduled task invoked. Refreshing Cache..."); - initializeAafCache(); + try { + initializeAafCache(); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + } } public static boolean authenticateAAFUser(String nameSpace, String userId, String password, @@ -140,22 +142,20 @@ public class CachingUtil implements Runnable { if (userAttempts.get(nameSpace) == null) userAttempts.put(nameSpace, 0); if ((Integer) userAttempts.get(nameSpace) >= 3) { - logger.info("Reached max attempts. Checking if time out.."); - logger.info("Failed time: " + lastFailedTime.get(nameSpace).getTime()); + logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out.."); + logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime()); Calendar calendar = Calendar.getInstance(); - long delayTime = (calendar.getTimeInMillis() - - lastFailedTime.get(nameSpace).getTimeInMillis()); - logger.info("Delayed time: " + delayTime); - if (delayTime > 120000) { - logger.info("Resetting failed attempt."); + long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis()); + logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime); + if( delayTime > 120000) { + logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt."); userAttempts.put(nameSpace, 0); } else { - throw new Exception( - "No more attempts allowed. Please wait for atleast 2 min."); + throw new Exception("No more attempts allowed. Please wait for atleast 2 min."); } } - logger.error("Cache not authenticated.."); - logger.info("Check AAF again..."); + logger.error(EELFLoggerDelegate.errorLogger,"Cache not authenticated.."); + logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again..."); } } @@ -165,7 +165,7 @@ public class CachingUtil implements Runnable { return true; } - logger.info("Invalid user. Cache not updated"); + logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated"); return false; } @@ -260,7 +260,7 @@ public class CachingUtil implements Runnable { appNameCache.put(namespace, isAAF); } - public static Boolean isAAFApplication(String namespace) { + public static Boolean isAAFApplication(String namespace) throws MusicServiceException { String isAAF = appNameCache.get(namespace); if (isAAF == null) { @@ -277,10 +277,12 @@ public class CachingUtil implements Runnable { e.printStackTrace(); } } + + return Boolean.valueOf(isAAF); } - public static String getUuidFromMusicCache(String keyspace) { + public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException { String uuid = musicCache.get(keyspace); if (uuid == null) { PreparedQueryObject pQuery = new PreparedQueryObject(); @@ -292,14 +294,14 @@ public class CachingUtil implements Runnable { uuid = rs.getUUID("uuid").toString(); musicCache.put(keyspace, uuid); } catch (Exception e) { - logger.error("Exception occured during uuid retrieval from DB." + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage()); e.printStackTrace(); } } return uuid; } - public static String getAppName(String keyspace) { + public static String getAppName(String keyspace) throws MusicServiceException { String appName = null; PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( @@ -309,7 +311,7 @@ public class CachingUtil implements Runnable { try { appName = rs.getString("application_name"); } catch (Exception e) { - logger.error("Exception occured during uuid retrieval from DB." + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage()); e.printStackTrace(); } return appName; @@ -317,7 +319,7 @@ public class CachingUtil implements Runnable { public static String generateUUID() { String uuid = UUID.randomUUID().toString(); - logger.info("New AID generated: " + uuid); + logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); return uuid; } @@ -337,8 +339,7 @@ public class CachingUtil implements Runnable { throws Exception { Map<String, Object> resultMap = new HashMap<>(); if (ns == null || userId == null || password == null) { - logger.error("One or more required headers is missing. userId: " + userId - + " :: password: " + password); + logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password); resultMap.put("Exception", "One or more required headers appName(ns), userId, password is missing. Please check."); return resultMap; @@ -350,16 +351,15 @@ public class CachingUtil implements Runnable { queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); Row rs = MusicCore.get(queryObject).one(); if (rs == null) { - logger.error("Namespace and UserId doesn't match. namespace: " + ns + " and userId: " - + userId); - resultMap.put("Exception", "Application " + ns - + " doesn't seem to be Onboarded. Please onboard your application with MUSIC. If already onboarded contact Admin"); + logger.error(EELFLoggerDelegate.errorLogger,"Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId); + + resultMap.put("Exception", "Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId); } else { boolean is_aaf = rs.getBool("is_aaf"); String keyspace = rs.getString("keyspace_name"); if (!is_aaf) { if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) { - logger.error("Non AAF applications are allowed to have only one keyspace per application."); + logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application."); resultMap.put("Exception", "Non AAF applications are allowed to have only one keyspace per application."); } diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java index 592bae92..96056160 100644 --- a/src/main/java/org/onap/music/main/MusicCore.java +++ b/src/main/java/org/onap/music/main/MusicCore.java @@ -26,9 +26,11 @@ import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; + import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.eelf.logging.EELFLoggerDelegate; // import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; @@ -36,8 +38,7 @@ import org.onap.music.exceptions.MusicServiceException; import org.onap.music.lockingservice.MusicLockState; import org.onap.music.lockingservice.MusicLockState.LockStatus; import org.onap.music.lockingservice.MusicLockingService; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; + import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; @@ -54,22 +55,20 @@ public class MusicCore { public static MusicLockingService mLockHandle = null; public static MusicDataStore mDstoreHandle = null; - private static EELFLogger logger = EELFManager.getInstance().getLogger(MusicCore.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class); public static class Condition { Map<String, Object> conditions; - String selectQueryForTheRow; + PreparedQueryObject selectQueryForTheRow; - public Condition(Map<String, Object> conditions, String selectQueryForTheRow) { + public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) { this.conditions = conditions; this.selectQueryForTheRow = selectQueryForTheRow; } public boolean testCondition() { // first generate the row - PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString(selectQueryForTheRow); - ResultSet results = quorumGet(query); + ResultSet results = quorumGet(selectQueryForTheRow); Row row = results.one(); return getDSHandle().doesRowSatisfyCondition(row, conditions); } @@ -77,19 +76,19 @@ public class MusicCore { public static MusicLockingService getLockingServiceHandle() throws MusicLockingException { - logger.info("Acquiring lock store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle"); long start = System.currentTimeMillis(); if (mLockHandle == null) { try { mLockHandle = new MusicLockingService(); } catch (Exception e) { - logger.error("Failed to aquire Locl store handle" + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquire Locl store handle" + e.getMessage()); throw new MusicLockingException("Failed to aquire Locl store handle " + e); } } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire lock store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms"); return mLockHandle; } @@ -99,13 +98,13 @@ public class MusicCore { * @return */ public static MusicDataStore getDSHandle(String remoteIp) { - logger.info("Acquiring data store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); long start = System.currentTimeMillis(); if (mDstoreHandle == null) { mDstoreHandle = new MusicDataStore(remoteIp); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire data store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); return mDstoreHandle; } @@ -114,27 +113,27 @@ public class MusicCore { * @return */ public static MusicDataStore getDSHandle() { - logger.info("Acquiring data store handle"); + logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle"); long start = System.currentTimeMillis(); if (mDstoreHandle == null) { mDstoreHandle = new MusicDataStore(); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire data store handle:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms"); return mDstoreHandle; } public static String createLockReference(String lockName) { - logger.info("Creating lock reference for lock name:" + lockName); + logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName); long start = System.currentTimeMillis(); String lockId = null; try { lockId = getLockingServiceHandle().createLockId("/" + lockName); } catch (MusicLockingException e) { - logger.error("Failed to create Lock Reference " + lockName); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to create Lock Reference " + lockName); } long end = System.currentTimeMillis(); - logger.info("Time taken to create lock reference:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms"); return lockId; } @@ -167,10 +166,10 @@ public class MusicCore { String lockName = keyspaceName + "." + tableName + "." + primaryKey; mls = getLockingServiceHandle().getLockState(lockName); long end = System.currentTimeMillis(); - logger.info("Time taken to get lock state:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms"); return mls; } catch (NullPointerException | MusicLockingException e) { - logger.error("No lock object exists as of now.." + e); + logger.error(EELFLoggerDelegate.errorLogger,"No lock object exists as of now.." + e); } return null; } @@ -182,12 +181,12 @@ public class MusicCore { MusicLockState mls = getMusicLockState(key); if (mls != null) { if (mls.getLockStatus().equals(LockStatus.LOCKED)) { - logger.info("The current lock holder for " + key + " is " + mls.getLockHolder() + logger.info(EELFLoggerDelegate.applicationLogger,"The current lock holder for " + key + " is " + mls.getLockHolder() + ". Checking if it has exceeded lease"); long currentLockPeriod = System.currentTimeMillis() - mls.getLeaseStartTime(); long currentLeasePeriod = mls.getLeasePeriod(); if (currentLockPeriod > currentLeasePeriod) { - logger.info("Lock period " + currentLockPeriod + logger.info(EELFLoggerDelegate.applicationLogger,"Lock period " + currentLockPeriod + " has exceeded lease period " + currentLeasePeriod); boolean voluntaryRelease = false; String currentLockHolder = mls.getLockHolder(); @@ -201,7 +200,7 @@ public class MusicCore { * call the traditional acquire lock now and if the result returned is true, set the * begin time-stamp and lease period */ - if (acquireLock(key, lockId) == true) { + if (acquireLock(key, lockId).getResult() == ResultType.SUCCESS) { mls = getMusicLockState(key);// get latest state if (mls.getLeaseStartTime() == -1) {// set it again only if it is not set already mls.setLeaseStartTime(System.currentTimeMillis()); @@ -209,23 +208,23 @@ public class MusicCore { getLockingServiceHandle().setLockState(key, mls); } long end = System.currentTimeMillis(); - logger.info("Time taken to acquire leased lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire leased lock:" + (end - start) + " ms"); return new ReturnType(ResultType.SUCCESS, "Accquired lock"); } else { long end = System.currentTimeMillis(); - logger.info("Time taken to fail to acquire leased lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to fail to acquire leased lock:" + (end - start) + " ms"); return new ReturnType(ResultType.FAILURE, "Could not acquire lock"); } } catch (Exception e) { StringWriter sw = new StringWriter(); - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); String exceptionAsString = sw.toString(); return new ReturnType(ResultType.FAILURE, "Exception thrown in acquireLockWithLease:\n" + exceptionAsString); } } - public static boolean acquireLock(String key, String lockId) { + public static ReturnType acquireLock(String key, String lockId) { /* * first check if I am on top. Since ids are not reusable there is no need to check * lockStatus If the status is unlocked, then the above call will automatically return @@ -235,19 +234,28 @@ public class MusicCore { try { result = getLockingServiceHandle().isMyTurn(lockId); } catch (MusicLockingException e2) { - logger.error("Failed to aquireLock lockId " + lockId + " " + e2); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquireLock lockId " + lockId + " " + e2); } if (result == false) { - logger.info("In acquire lock: Not your turn, someone else has the lock"); - return false; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock"); + try { + if (!getLockingServiceHandle().lockIdExists(lockId)) { + logger.info(EELFLoggerDelegate.applicationLogger, "In acquire lock: this lockId doesn't exist"); + return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist"); + } + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger,"Failed to check if lockid exists - lockId " + lockId + " " + e); + } + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure"); + return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock"); } // this is for backward compatibility where locks could also be acquired on just // keyspaces or tables. if (isTableOrKeySpaceLock(key) == true) { - logger.info("In acquire lock: A table or keyspace lock so no need to perform sync...so returning true"); - return true; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: A table or keyspace lock so no need to perform sync...so returning true"); + return new ReturnType(ResultType.SUCCESS, "A table or keyspace lock so no need to perform sync...so returning true"); } // read the lock name corresponding to the key and if the status is locked or being locked, @@ -258,11 +266,11 @@ public class MusicCore { currentMls = getMusicLockState(key); String currentLockHolder = currentMls.getLockHolder(); if (lockId.equals(currentLockHolder)) { - logger.info("In acquire lock: You already have the lock!"); - return true; + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: You already have the lock!"); + return new ReturnType(ResultType.SUCCESS, "You already have the lock!"); } } catch (NullPointerException e) { - logger.error("In acquire lock:No one has tried to acquire the lock yet.."); + logger.error(EELFLoggerDelegate.errorLogger,"In acquire lock:No one has tried to acquire the lock yet.."); } // change status to "being locked". This state transition is necessary to ensure syncing @@ -278,13 +286,13 @@ public class MusicCore { try { getLockingServiceHandle().setLockState(key, newMls); } catch (MusicLockingException e1) { - logger.error("Failed to set Lock state " + key + " " + e1); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e1); } - logger.info("In acquire lock: Set lock state to being_locked"); + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to being_locked"); // do syncing if this was a forced lock release if (needToSyncQuorum) { - logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!"); + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!"); syncQuorum(key); } @@ -295,11 +303,12 @@ public class MusicCore { try { getLockingServiceHandle().setLockState(key, newMls); } catch (MusicLockingException e) { - logger.error("Failed to set Lock state " + key + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e); } - logger.info("In acquire lock: Set lock state to locked and assigned current lock ref " + logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref " + lockId + " as holder"); - return result; + + return new ReturnType(result?ResultType.SUCCESS:ResultType.FAILURE, "Set lock state to locked and assigned a lock holder"); } @@ -317,7 +326,7 @@ public class MusicCore { private static void syncQuorum(String key) { - logger.info("Performing sync operation---"); + logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---"); String[] splitString = key.split("\\."); String keyspaceName = splitString[0]; String tableName = splitString[1]; @@ -330,8 +339,8 @@ public class MusicCore { String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();// we only support single // primary key DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType(); - String cqlFormattedPrimaryKeyValue = - MusicUtil.convertToCQLDataType(primaryKeyType, primaryKeyValue); + Object cqlFormattedPrimaryKeyValue = + MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue); // get the row of data from a quorum selectQuery.appendQueryString("SELECT * FROM " + keyspaceName + "." + tableName + " WHERE " @@ -355,7 +364,7 @@ public class MusicCore { continue; DataType colType = definition.getType(); Object valueObj = getDSHandle().getColValue(row, colName, colType); - String valueString = MusicUtil.convertToCQLDataType(colType, valueObj); + Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); // fieldValueString = fieldValueString+ colName+"="+valueString; fieldValueString.append(colName + " = ?"); updateQuery.addValue(valueString); @@ -371,7 +380,7 @@ public class MusicCore { getDSHandle().executePut(updateQuery, "critical"); } catch (MusicServiceException | MusicQueryException e) { - logger.error("Failed to execute update query " + updateQuery + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to execute update query " + updateQuery + " " + e); } } @@ -396,7 +405,7 @@ public class MusicCore { ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); long lockAcqTime = System.currentTimeMillis(); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockId, conditionInfo); long criticalPutTime = System.currentTimeMillis(); @@ -409,7 +418,7 @@ public class MusicCore { criticalPutResult.setTimingInfo(timingInfo); return criticalPutResult; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); deleteLock(key); return lockAcqResult; } @@ -425,7 +434,7 @@ public class MusicCore { try { results = getDSHandle().executeCriticalGet(query); } catch (MusicServiceException | MusicQueryException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return results; @@ -450,7 +459,7 @@ public class MusicCore { try { return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + ""; } catch (MusicLockingException e) { - logger.error("Failed whoseTurnIsIt " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed whoseTurnIsIt " + lockName + " " + e); } return null; @@ -472,10 +481,10 @@ public class MusicCore { try { getLockingServiceHandle().unlockAndDeleteId(lockId); } catch (MusicLockingException e) { - logger.error("Failed to Destroy Lock Ref " + lockId + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to Destroy Lock Ref " + lockId + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to destroy lock reference:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms"); } public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) { @@ -483,27 +492,27 @@ public class MusicCore { try { getLockingServiceHandle().unlockAndDeleteId(lockId); } catch (MusicLockingException e1) { - logger.error("Failed to release Lock " + lockId + " " + e1); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + e1); } String lockName = getLockNameFromId(lockId); MusicLockState mls; String lockHolder = null; if (voluntaryRelease) { mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder); - logger.info("In unlock: lock voluntarily released for " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock voluntarily released for " + lockId); } else { boolean needToSyncQuorum = true; mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder, needToSyncQuorum); - logger.info("In unlock: lock forcibly released for " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock forcibly released for " + lockId); } try { getLockingServiceHandle().setLockState(lockName, mls); } catch (MusicLockingException e) { - logger.error("Failed to release Lock " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockName + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to release lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms"); return mls; } @@ -513,14 +522,14 @@ public class MusicCore { */ public static void deleteLock(String lockName) { long start = System.currentTimeMillis(); - logger.info("Deleting lock for " + lockName); + logger.info(EELFLoggerDelegate.applicationLogger,"Deleting lock for " + lockName); try { getLockingServiceHandle().deleteLock("/" + lockName); } catch (MusicLockingException e) { - logger.error("Failed to Delete Lock " + lockName + " " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to Delete Lock " + lockName + " " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken to delete lock:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms"); } @@ -544,7 +553,7 @@ public class MusicCore { try { getLockingServiceHandle().getzkLockHandle().createNode(nodeName); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } } @@ -555,15 +564,15 @@ public class MusicCore { */ public static void pureZkWrite(String nodeName, byte[] data) { long start = System.currentTimeMillis(); - logger.info("Performing zookeeper write to " + nodeName); + logger.info(EELFLoggerDelegate.applicationLogger,"Performing zookeeper write to " + nodeName); try { getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } - logger.info("Performed zookeeper write to " + nodeName); + logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName); long end = System.currentTimeMillis(); - logger.info("Time taken for the actual zk put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); } /** @@ -577,10 +586,10 @@ public class MusicCore { try { data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName); } catch (MusicLockingException e) { - logger.error("Failed to get ZK Lock Handle " + e); + logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e); } long end = System.currentTimeMillis(); - logger.info("Time taken for the actual zk put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms"); return data; } @@ -602,7 +611,7 @@ public class MusicCore { try { result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL); } catch (MusicServiceException | MusicQueryException ex) { - logger.error(ex.getMessage() + " " + ex.getCause() + " " + ex); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); } if (result) { return new ReturnType(ResultType.SUCCESS, "Success"); @@ -634,16 +643,18 @@ public class MusicCore { "Lock acquired but the condition is not true"); getDSHandle().executePut(queryObject, MusicUtil.CRITICAL); long end = System.currentTimeMillis(); - logger.info("Time taken for the critical put:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms"); return new ReturnType(ResultType.SUCCESS, "Update performed"); } else return new ReturnType(ResultType.FAILURE, "Cannot perform operation since you are the not the lock holder"); - } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(e.getMessage()); + } catch (MusicQueryException | MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); return new ReturnType(ResultType.FAILURE, "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n" + e.getMessage()); + }catch(MusicLockingException ex){ + return new ReturnType(ResultType.FAILURE,ex.getMessage()); } } @@ -653,17 +664,19 @@ public class MusicCore { * @param queryObject * @param consistency * @return Boolean Indicates success or failure + * @throws MusicServiceException * * */ - public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) { + public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException { // this is mainly for some functions like keyspace creation etc which does not // really need the bells and whistles of Music locking. boolean result = false; try { result = getDSHandle().executePut(queryObject, consistency); } catch (MusicQueryException | MusicServiceException ex) { - logger.error(ex.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage()); + throw new MusicServiceException(ex.getMessage()); } return result; } @@ -673,13 +686,15 @@ public class MusicCore { * * @param queryObject query object containing prepared query and values * @return ResultSet + * @throws MusicServiceException */ - public static ResultSet get(PreparedQueryObject queryObject) { + public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException { ResultSet results = null; try { - results = getDSHandle().executeEventualGet(queryObject); + results = getDSHandle().executeEventualGet(queryObject); } catch (MusicQueryException | MusicServiceException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + throw new MusicServiceException(e.getMessage()); } return results; } @@ -706,7 +721,7 @@ public class MusicCore { } else throw new MusicServiceException("YOU DO NOT HAVE THE LOCK"); } catch (MusicQueryException | MusicServiceException | MusicLockingException e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } return results; } @@ -730,7 +745,7 @@ public class MusicCore { ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); long lockAcqTime = System.currentTimeMillis(); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockId, conditionInfo); long criticalPutTime = System.currentTimeMillis(); @@ -744,7 +759,7 @@ public class MusicCore { criticalPutResult.setTimingInfo(timingInfo); return criticalPutResult; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); destroyLockRef(lockId); return lockAcqResult; } @@ -768,14 +783,14 @@ public class MusicCore { long leasePeriod = MusicUtil.getDefaultLockLeasePeriod(); ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId); boolean voluntaryRelease = true; releaseLock(lockId, voluntaryRelease); return result; } else { - logger.info("unable to acquire lock, id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId); return null; } } @@ -801,32 +816,35 @@ public class MusicCore { operation); if (!resultMap.isEmpty()) return resultMap; + boolean isAAF = CachingUtil.isAAFApplication(nameSpace); + if (!isAAF && !(operation.equals("createKeySpace"))) { + if(aid == null) { + resultMap.put("Exception", "Aid is mandatory for nonAAF applications "); + return resultMap; + } + resultMap = CachingUtil.authenticateAIDUser(aid, keyspace); + if (!resultMap.isEmpty()) + return resultMap; + } if (aid == null && (userId == null || password == null)) { - logger.error("One or more required headers is missing. userId: " + userId + logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId + " :: password: " + password); resultMap.put("Exception", "UserId and Password are mandatory for the operation " + operation); return resultMap; } - boolean isAAF = CachingUtil.isAAFApplication(nameSpace); - if (!isAAF && aid != null && aid.length() > 0) { // Non AAF app - resultMap = CachingUtil.authenticateAIDUser(aid, keyspace); - if (!resultMap.isEmpty()) - return resultMap; - } + if (isAAF && nameSpace != null && userId != null && password != null) { boolean isValid = true; try { isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace); } catch (Exception e) { - logger.error("Got exception while AAF authentication for namespace " + nameSpace); + logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace); resultMap.put("Exception", e.getMessage()); - // return resultMap; } if (!isValid) { - logger.error("User not authenticated with AAF."); + logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated with AAF."); resultMap.put("Exception", "User not authenticated..."); - // return resultMap; } if (!resultMap.isEmpty()) return resultMap; @@ -834,7 +852,7 @@ public class MusicCore { } if (operation.equals("createKeySpace")) { - logger.info("AID is not provided. Creating new UUID for keyspace."); + logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace."); PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering"); @@ -848,7 +866,7 @@ public class MusicCore { uuid = rs.getUUID("uuid").toString(); resultMap.put("uuid", "existing"); } catch (Exception e) { - logger.info("No UUID found in DB. So creating new UUID."); + logger.info(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID."); uuid = CachingUtil.generateUUID(); resultMap.put("uuid", "new"); } diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index 61d428d1..47e23973 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -21,445 +21,458 @@ */ package org.onap.music.main; - import java.io.File; import java.io.FileNotFoundException; import java.math.BigInteger; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.UUID; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicServiceException; + 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. + * 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); - - private static int myId = 0; - private static ArrayList<String> allIds = new ArrayList<String>(); - private static String publicIp = ""; - private static ArrayList<String> allPublicIps = new ArrayList<String>(); - private static String myZkHost = "localhost"; - private static String myCassaHost = "localhost"; - private static String defaultMusicIp = "localhost"; - private static boolean debug = true; - private static String version = "2.3.0"; - public static String musicRestIp = "localhost"; - private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties"; - private static long defaultLockLeasePeriod = 6000; - private static final String[] propKeys = new String[] {"zookeeper.host", "cassandra.host", - "music.ip", "debug", "version", "music.rest.ip", "music.properties", - "lock.lease.period", "id", "all.ids", "public.ip", "all.pubic.ips", - "cassandra.user", "cassandra.password", "aaf.endpoint.url"}; - - public static final String ATOMIC = "atomic"; - public static final String EVENTUAL = "eventual"; - public static final String CRITICAL = "critical"; - public static final String DEFAULTKEYSPACENAME = "TBD"; - private static String cassName = "cassandra"; - private static String cassPwd = "cassandra"; - private static String aafEndpointUrl = null; - - /** - * @return the cassName - */ - public static String getCassName() { - return cassName; - } - - /** - * @return the cassPwd - */ - public static String getCassPwd() { - return cassPwd; - } - - /** - * @return the aafEndpointUrl - */ - public static String getAafEndpointUrl() { - return aafEndpointUrl; - } - - /** - * - * @param aafEndpointUrl - */ - public static void setAafEndpointUrl(String aafEndpointUrl) { - MusicUtil.aafEndpointUrl = aafEndpointUrl; - } - - /** - * - * @return - */ - public static int getMyId() { - return myId; - } - - /** - * - * @param myId - */ - public static void setMyId(int myId) { - MusicUtil.myId = myId; - } - - - /** - * - * @return - */ - public static ArrayList<String> getAllIds() { - return allIds; - } - - /** - * - * @param allIds - */ - public static void setAllIds(List<String> allIds) { - MusicUtil.allIds = (ArrayList<String>) allIds; - } - - /** - * - * @return - */ - public static String getPublicIp() { - return publicIp; - } - - /** - * - * @param publicIp - */ - public static void setPublicIp(String publicIp) { - MusicUtil.publicIp = publicIp; - } - - /** - * - * @return - */ - public static ArrayList<String> getAllPublicIps() { - return allPublicIps; - } - - /** - * - * @param allPublicIps - */ - public static void setAllPublicIps(List<String> allPublicIps) { - MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps; - } - - /** - * Returns An array of property names that should be in the Properties files. - * - * @return - */ - public static String[] getPropkeys() { - return propKeys; - } - - /** - * Get MusicRestIp - default = localhost property file value - music.rest.ip - * - * @return - */ - public static String getMusicRestIp() { - return musicRestIp; - } - - /** - * Set MusicRestIp - * - * @param musicRestIp - */ - public static void setMusicRestIp(String musicRestIp) { - MusicUtil.musicRestIp = musicRestIp; - } - - /** - * 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; - } - - /** - * Get MyZkHost - Zookeeper Hostname - Default = localhost property file value - zookeeper.host - * - * @return - */ - public static String getMyZkHost() { - return myZkHost; - } - - /** - * Set MyZkHost - Zookeeper Hostname - * - * @param myZkHost - */ - public static void setMyZkHost(String myZkHost) { - MusicUtil.myZkHost = myZkHost; - } - - /** - * 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; - } - - /** - * Get DefaultMusicIp - Default = localhost property file value - music.ip - * - * @return - */ - public static String getDefaultMusicIp() { - return defaultMusicIp; - } - - /** - * Set DefaultMusicIp - * - * @param defaultMusicIp - */ - public static void setDefaultMusicIp(String defaultMusicIp) { - MusicUtil.defaultMusicIp = defaultMusicIp; - } - - /** - * - * @return - */ - public static String getTestType() { - String testType = ""; - try { - Scanner fileScanner = new Scanner(new File("")); - testType = fileScanner.next();// ignore the my id line - String batchSize = fileScanner.next();// ignore the my public ip line - fileScanner.close(); - } catch (FileNotFoundException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - return testType; - - } - - /** - * - * @param time - */ - public static void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - } - - /** - * 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; - } - - public static String convertToCQLDataType(DataType type, Object valueObj) { - - 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 Exception - */ - public static Object convertToActualDataType(DataType colType, Object valueObj) { - 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; - default: - return valueObjString; - } - } - - - /** - * - * 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) { - 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(); - } + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + private static int myId = 0; + private static ArrayList<String> allIds = new ArrayList<String>(); + private static String publicIp = ""; + private static ArrayList<String> allPublicIps = new ArrayList<String>(); + private static String myZkHost = "localhost"; + private static String myCassaHost = "localhost"; + private static String defaultMusicIp = "localhost"; + private static boolean debug = true; + private static String version = "2.3.0"; + public static String musicRestIp = "localhost"; + private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties"; + private static long defaultLockLeasePeriod = 6000; + private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug", + "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip", + "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" }; + + public static final String ATOMIC = "atomic"; + public static final String EVENTUAL = "eventual"; + public static final String CRITICAL = "critical"; + public static final String DEFAULTKEYSPACENAME = "TBD"; + private static String cassName = "cassandra"; + private static String cassPwd = "cassandra"; + private static String aafEndpointUrl = null; + + /** + * @return the cassName + */ + public static String getCassName() { + return cassName; + } + + /** + * @return the cassPwd + */ + public static String getCassPwd() { + return cassPwd; + } + + /** + * @return the aafEndpointUrl + */ + public static String getAafEndpointUrl() { + return aafEndpointUrl; + } + + /** + * + * @param aafEndpointUrl + */ + public static void setAafEndpointUrl(String aafEndpointUrl) { + MusicUtil.aafEndpointUrl = aafEndpointUrl; + } + + /** + * + * @return + */ + public static int getMyId() { + return myId; + } + + /** + * + * @param myId + */ + public static void setMyId(int myId) { + MusicUtil.myId = myId; + } + + /** + * + * @return + */ + public static ArrayList<String> getAllIds() { + return allIds; + } + + /** + * + * @param allIds + */ + public static void setAllIds(List<String> allIds) { + MusicUtil.allIds = (ArrayList<String>) allIds; + } + + /** + * + * @return + */ + public static String getPublicIp() { + return publicIp; + } + + /** + * + * @param publicIp + */ + public static void setPublicIp(String publicIp) { + MusicUtil.publicIp = publicIp; + } + + /** + * + * @return + */ + public static ArrayList<String> getAllPublicIps() { + return allPublicIps; + } + + /** + * + * @param allPublicIps + */ + public static void setAllPublicIps(List<String> allPublicIps) { + MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps; + } + + /** + * Returns An array of property names that should be in the Properties + * files. + * + * @return + */ + public static String[] getPropkeys() { + return propKeys; + } + + /** + * Get MusicRestIp - default = localhost property file value - music.rest.ip + * + * @return + */ + public static String getMusicRestIp() { + return musicRestIp; + } + + /** + * Set MusicRestIp + * + * @param musicRestIp + */ + public static void setMusicRestIp(String musicRestIp) { + MusicUtil.musicRestIp = musicRestIp; + } + + /** + * 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; + } + + /** + * Get MyZkHost - Zookeeper Hostname - Default = localhost property file + * value - zookeeper.host + * + * @return + */ + public static String getMyZkHost() { + return myZkHost; + } + + /** + * Set MyZkHost - Zookeeper Hostname + * + * @param myZkHost + */ + public static void setMyZkHost(String myZkHost) { + MusicUtil.myZkHost = myZkHost; + } + + /** + * 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; + } + + /** + * Get DefaultMusicIp - Default = localhost property file value - music.ip + * + * @return + */ + public static String getDefaultMusicIp() { + return defaultMusicIp; + } + + /** + * Set DefaultMusicIp + * + * @param defaultMusicIp + */ + public static void setDefaultMusicIp(String defaultMusicIp) { + MusicUtil.defaultMusicIp = defaultMusicIp; + } + + /** + * + * @return + */ + public static String getTestType() { + String testType = ""; + try { + Scanner fileScanner = new Scanner(new File("")); + testType = fileScanner.next();// ignore the my id line + String batchSize = fileScanner.next();// ignore the my public ip + // line + fileScanner.close(); + } catch (FileNotFoundException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + return testType; + + } + + /** + * + * @param time + */ + public static void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + } + + /** + * 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; + } + + public static String convertToCQLDataType(DataType type, Object valueObj) { + + 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 Exception + */ + public static Object convertToActualDataType(DataType colType, Object valueObj) { + 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; + default: + return valueObjString; + } + } + + /** + * + * 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) { + 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(); + } + + public static Map<String, HashMap<String, Object>> setErrorResponse(MusicServiceException ex) { + Map<String, HashMap<String, Object>> results = new HashMap<>(); + HashMap<String, Object> tempMap = new HashMap<>(); + Map<String, Object> result = new HashMap<>(); + result.put("Error Description", ex.getMessage()); + tempMap.put("Error", result); + results.put("Result", tempMap); + return results; + } } diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java index 875fbbba..3e2f1557 100644 --- a/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java +++ b/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java @@ -23,70 +23,39 @@ package org.onap.music.response.jsonobjects; import java.util.HashMap; import java.util.Map; + +import org.onap.music.lockingservice.MusicLockState.LockStatus; +import org.onap.music.main.ResultType; +import org.powermock.core.spi.testresult.Result; + import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "JsonResponse", description = "General Response JSON") public class JsonLockResponse { - private String status = ""; - private String error = ""; - private String message = ""; - private String lock = ""; - private String lockStatus = ""; - private String lockHolder = ""; - private String lockLease = ""; - - /** - * - * @param status - * @param error - * @param lock - */ - public JsonLockResponse(String status, String error, String lock) { - this.status = fixStatus(status); - this.error = error; - this.lock = lock; - } + private ResultType status; + private String error; + private String message; + private String lock; + private LockStatus lockStatus; + private String lockHolder; + private String lockLease; - /** - * - * @param status - * @param error - * @param lock - * @param lockStatus - * @param lockHolder - */ - public JsonLockResponse(String status, String error, String lock, String lockStatus, - String lockHolder) { - this.status = fixStatus(status); - this.error = error; - this.lock = lock; - this.lockStatus = lockStatus; - this.lockHolder = lockHolder; - } /** - * + * Create a JSONLock Response + * Use setters to provide more information as in + * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname) * @param status - * @param error - * @param lock - * @param lockStatus - * @param lockHolder - * @param lockLease */ - public JsonLockResponse(String status, String error, String lock, String lockStatus, - String lockHolder, String lockLease) { - this.status = fixStatus(status); - this.error = error; - this.lock = lock; - this.lockStatus = lockStatus; - this.lockHolder = lockHolder; + public JsonLockResponse(ResultType status) { + this.status = status; } + - /** - * Lock + /** * * @return */ @@ -98,28 +67,9 @@ public class JsonLockResponse { * * @param lock */ - public void setLock(String lock) { + public JsonLockResponse setLock(String lock) { this.lock = lock; - } - - /** - * - */ - public JsonLockResponse() { - this.status = ""; - this.error = ""; - } - - /** - * - * @param statusIn - * @return - */ - private String fixStatus(String statusIn) { - if (statusIn.equalsIgnoreCase("false")) { - return "FAILURE"; - } - return "SUCCESS"; + return this; } /** @@ -128,7 +78,7 @@ public class JsonLockResponse { */ @ApiModelProperty(value = "Overall status of the response.", allowableValues = "Success,Failure") - public String getStatus() { + public ResultType getStatus() { return status; } @@ -136,8 +86,9 @@ public class JsonLockResponse { * * @param status */ - public void setStatus(String status) { - this.status = fixStatus(status); + public JsonLockResponse setStatus(ResultType status) { + this.status = status; + return this; } /** @@ -153,8 +104,9 @@ public class JsonLockResponse { * * @param error */ - public void setError(String error) { + public JsonLockResponse setError(String error) { this.error = error; + return this; } /** @@ -170,17 +122,17 @@ public class JsonLockResponse { * * @param message */ - public void setMessage(String message) { + public JsonLockResponse setMessage(String message) { this.message = message; + return this; } /** * * @return the lockStatus */ - @ApiModelProperty(value = "Status of the lock", - allowableValues = "UNLOCKED,BEING_LOCKED,LOCKED") - public String getLockStatus() { + @ApiModelProperty(value = "Status of the lock") + public LockStatus getLockStatus() { return lockStatus; } @@ -188,8 +140,9 @@ public class JsonLockResponse { * * @param lockStatus */ - public void setLockStatus(String lockStatus) { + public JsonLockResponse setLockStatus(LockStatus lockStatus) { this.lockStatus = lockStatus; + return this; } /** @@ -206,8 +159,9 @@ public class JsonLockResponse { * * @param lockHolder */ - public void setLockHolder(String lockHolder) { + public JsonLockResponse setLockHolder(String lockHolder) { this.lockHolder = lockHolder; + return this; } @@ -222,8 +176,9 @@ public class JsonLockResponse { /** * @param lockLease the lockLease to set */ - public void setLockLease(String lockLease) { + public JsonLockResponse setLockLease(String lockLease) { this.lockLease = lockLease; + return this; } /** @@ -232,17 +187,18 @@ public class JsonLockResponse { * @return */ public Map<String, Object> toMap() { - Map<String, Object> newMap = new HashMap<>(); + Map<String, Object> fullMap = new HashMap<>(); Map<String, Object> lockMap = new HashMap<>(); - lockMap.put("lock-status", lockStatus); - lockMap.put("lock", lock); - lockMap.put("message", message); - lockMap.put("lock-holder", lockHolder); - lockMap.put("lock-lease", lockLease); - newMap.put("status", status); - newMap.put("error", error); - newMap.put("lock", lockMap); - return newMap; + if (lockStatus!=null) {lockMap.put("lock-status", lockStatus); } + if (lock!=null) {lockMap.put("lock", lock);} + if (message!=null) {lockMap.put("message", message);} + if (lockHolder!=null) {lockMap.put("lock-holder", lockHolder);} + if (lockLease!=null) {lockMap.put("lock-lease", lockLease);} + + fullMap.put("status", status); + fullMap.put("lock", lockMap); + if (error!=null) {fullMap.put("error", error);} + return fullMap; } /** diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 87a3a1ba..0265d039 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -21,6 +21,7 @@ */ package org.onap.music.rest; + import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -29,8 +30,6 @@ import java.util.UUID; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; @@ -39,23 +38,21 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; @Path("/v{version: [0-9]+}/admin") // @Path("/admin") @Api(value = "Admin Api", hidden = true) public class RestMusicAdminAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicAdminAPI.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); /* * API to onboard an application with MUSIC. This is the mandatory first step. @@ -86,7 +83,7 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); ResultSet rs = MusicCore.get(pQuery); if (!rs.all().isEmpty()) { - resultMap.put("Exception", "Your application " + appName + resultMap.put("Exception", "Application " + appName + " has already been onboarded. Please contact admin."); return resultMap; } @@ -116,50 +113,55 @@ public class RestMusicAdminAPI { resultMap.put("Generated AID", uuid); return resultMap; } - - - /* - * API to onboard an application with MUSIC. This is the mandatory first step. - * - */ - @GET - @Path("/onboardAppWithMusic") - @ApiOperation(value = "Onboard application", response = String.class) + + + @POST + @Path("/search") + @ApiOperation(value = "Search Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Map<String, Object> getOnboardedInfo( - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String uuid, - @ApiParam(value = "Application namespace", - required = true) @HeaderParam("ns") String appName, + public Map<String, Object> getOnboardedInfoSearch( + JsonOnboard jsonObj, @Context HttpServletResponse response) throws Exception { Map<String, Object> resultMap = new HashMap<>(); response.addHeader("X-latestVersion", MusicUtil.getVersion()); - if (appName == null && uuid == null) { + String appName = jsonObj.getAppname(); + String uuid = jsonObj.getAid(); + String isAAF = jsonObj.getIsAAF(); + + if (appName == null && uuid == null && isAAF == null) { resultMap.put("Exception", - "Please check the request parameters. Some of the required values appName(ns), aid are missing."); + "Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."); return resultMap; } PreparedQueryObject pQuery = new PreparedQueryObject(); - String cql = "select uuid, keyspace_name from admin.keyspace_master where "; if (appName != null) - cql = cql + "application_name = ?"; - else if (uuid != null) - cql = cql + "uuid = ?"; + cql = cql + "application_name = ? AND "; + if (uuid != null) + cql = cql + "uuid = ? AND "; + if(isAAF != null) + cql = cql + "is_aaf = ?"; + + if(cql.endsWith("AND ")) + cql = cql.trim().substring(0, cql.length()-4); + System.out.println("Query is: "+cql); cql = cql + " allow filtering"; System.out.println("Get OnboardingInfo CQL: " + cql); pQuery.appendQueryString(cql); if (appName != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - else if (uuid != null) + if (uuid != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + if (isAAF != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), Boolean.parseBoolean(isAAF))); ResultSet rs = MusicCore.get(pQuery); Iterator<Row> it = rs.iterator(); while (it.hasNext()) { Row row = (Row) it.next(); - resultMap.put(row.getString("keyspace_name"), row.getUUID("uuid")); + resultMap.put( row.getUUID("uuid").toString(),row.getString("keyspace_name")); } if (resultMap.isEmpty()) resultMap.put("ERROR", "Application is not onboarded. Please contact admin."); @@ -173,46 +175,47 @@ public class RestMusicAdminAPI { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> deleteOnboardApp(JsonOnboard jsonObj, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @Context HttpServletResponse response) throws Exception { Map<String, Object> resultMap = new HashMap<>(); response.addHeader("X-latestVersion", MusicUtil.getVersion()); String appName = jsonObj.getAppname(); + String aid = jsonObj.getAid(); PreparedQueryObject pQuery = new PreparedQueryObject(); - long count = 0; + String consistency = MusicUtil.EVENTUAL;; if (appName == null && aid == null) { resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present"); return resultMap; } if (aid != null) { - pQuery.appendQueryString( - "select count(*) as count from admin.keyspace_master where uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString(aid))); - Row row = MusicCore.get(pQuery).one(); - if (row != null) { - count = row.getLong(0); - } - - if (count == 0) { - resultMap.put("Failure", "Please verify your AID."); - return resultMap; - } else { - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); + pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), + UUID.fromString(aid))); + Row row = MusicCore.get(pQuery).one(); + if(row!=null) { + String ks = row.getString("keyspace_name"); + if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("DROP KEYSPACE " + ks + ";"); + MusicCore.nonKeyRelatedPut(queryObject, consistency); + } + } + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - String result = MusicCore.eventualPut(pQuery).toString(); - if (result.toLowerCase().contains("success")) { - resultMap.put("Success", "Your application has been deleted."); - return resultMap; - } else { - resultMap.put("Failure", "Please verify your AID."); - return resultMap; - } - } - + boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + if (result) { + resultMap.put("Success", "Your application has been deleted successfully"); + } else { + resultMap.put("Exception", + "Oops. Spomething went wrong. Please make sure Aid is correct or Application is onboarded"); + } + return resultMap; } + + + + pQuery.appendQueryString( "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); @@ -226,6 +229,18 @@ public class RestMusicAdminAPI { } else if (rows.size() == 1) { uuid = rows.get(0).getUUID("uuid").toString(); pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), + UUID.fromString(uuid))); + Row row = MusicCore.get(pQuery).one(); + String ks = row.getString("keyspace_name"); + if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("DROP KEYSPACE " + ks + ";"); + MusicCore.nonKeyRelatedPut(queryObject, consistency); + } + + pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(uuid))); @@ -233,7 +248,7 @@ public class RestMusicAdminAPI { resultMap.put("Success", "Your application " + appName + " has been deleted."); return resultMap; } else { - resultMap.put("Failure", "Please provide UUID for the application."); + resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid."); } return resultMap; @@ -246,16 +261,16 @@ public class RestMusicAdminAPI { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> updateOnboardApp(JsonOnboard jsonObj, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @Context HttpServletResponse response) throws Exception { Map<String, Object> resultMap = new HashMap<>(); response.addHeader("X-latestVersion", MusicUtil.getVersion()); + String aid = jsonObj.getAid(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); String isAAF = jsonObj.getIsAAF(); String password = jsonObj.getPassword(); String consistency = "eventual"; - PreparedQueryObject pQuery = new PreparedQueryObject(); + PreparedQueryObject pQuery; if (aid == null) { resultMap.put("Exception", "Please make sure Aid is present"); @@ -267,39 +282,52 @@ public class RestMusicAdminAPI { "No parameters found to update. Please update atleast one parameter."); return resultMap; } - - StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET "); - if (appName != null) - preCql.append(" application_name = ?,"); - if (userId != null) - preCql.append(" username = ?,"); - if (password != null) - preCql.append(" password = ?,"); - if (isAAF != null) - preCql.append(" is_aaf = ?,"); - preCql.deleteCharAt(preCql.length() - 1); - preCql.append(" WHERE uuid = ?"); - pQuery.appendQueryString(preCql.toString()); - if (appName != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - if (userId != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - if (password != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); - if (isAAF != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - - - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - Boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency); - - if (result) { - resultMap.put("Success", "Your application has been updated successfully"); - } else { - resultMap.put("Exception", - "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded"); + + if(appName!=null) { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "select uuid from admin.keyspace_master where application_name = ? allow filtering"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + ResultSet rs = MusicCore.get(pQuery); + if (!rs.all().isEmpty()) { + resultMap.put("Exception", "Application " + appName + + " has already been onboarded. Please contact admin."); + return resultMap; + } } - + + pQuery = new PreparedQueryObject(); + StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET "); + if (appName != null) + preCql.append(" application_name = ?,"); + if (userId != null) + preCql.append(" username = ?,"); + if (password != null) + preCql.append(" password = ?,"); + if (isAAF != null) + preCql.append(" is_aaf = ?,"); + preCql.deleteCharAt(preCql.length() - 1); + preCql.append(" WHERE uuid = ? IF EXISTS"); + pQuery.appendQueryString(preCql.toString()); + if (appName != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + if (userId != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + if (password != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); + if (isAAF != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); + boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency); + + if (result) { + resultMap.put("Success", "Your application has been updated successfully"); + } else { + resultMap.put("Exception", + "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded"); + } + return resultMap; } } diff --git a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java index 90b82229..8f62f9c1 100644 --- a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java @@ -35,6 +35,7 @@ import org.apache.log4j.Logger; import org.onap.music.datastore.jsonobjects.JsonInsert; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; @@ -58,7 +59,8 @@ import io.swagger.annotations.ApiParam; @Path("/v{version: [0-9]+}/benchmarks/") @Api(value = "Benchmark API", hidden = true) public class RestMusicBmAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicBmAPI.class); + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicBmAPI.class); // pure zk calls... @@ -86,11 +88,11 @@ public class RestMusicBmAPI { @Consumes(MediaType.APPLICATION_JSON) public void pureZkUpdate(JsonInsert insObj, @PathParam("name") String nodeName) throws Exception { - logger.info("--------------Zk normal update-------------------------"); + logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zk normal update-------------------------"); long start = System.currentTimeMillis(); MusicCore.pureZkWrite(nodeName, insObj.serialize()); long end = System.currentTimeMillis(); - logger.info("Total time taken for Zk normal update:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk normal update:" + (end - start) + " ms"); } /** @@ -122,7 +124,7 @@ public class RestMusicBmAPI { String operationId = UUID.randomUUID().toString();// just for debugging purposes. String consistency = updateObj.getConsistencyInfo().get("type"); - logger.info("--------------Zookeeper " + consistency + " update-" + operationId + logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zookeeper " + consistency + " update-" + operationId + "-------------------------"); byte[] data = updateObj.serialize(); @@ -138,7 +140,7 @@ public class RestMusicBmAPI { long zkPutTime = 0, lockReleaseTime = 0; if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { - logger.info("acquired lock with id " + lockId); + logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); MusicCore.pureZkWrite(lockname, data); zkPutTime = System.currentTimeMillis(); boolean voluntaryRelease = true; @@ -171,7 +173,7 @@ public class RestMusicBmAPI { + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) + lockingInfo; - logger.info(timingString); + logger.info(EELFLoggerDelegate.applicationLogger,timingString); } /** @@ -201,7 +203,7 @@ public class RestMusicBmAPI { } long end = System.currentTimeMillis(); - logger.info("Total time taken for Zk atomic read:" + (end - start) + " ms"); + logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk atomic read:" + (end - start) + " ms"); } /** @@ -225,7 +227,7 @@ public class RestMusicBmAPI { long startTime = System.currentTimeMillis(); String operationId = UUID.randomUUID().toString();// just for debugging purposes. String consistency = insObj.getConsistencyInfo().get("type"); - logger.info("--------------Cassandra " + consistency + " update-" + operationId + logger.info(EELFLoggerDelegate.applicationLogger,"--------------Cassandra " + consistency + " update-" + operationId + "-------------------------"); PreparedQueryObject queryObject = new PreparedQueryObject(); Map<String, Object> valuesMap = insObj.getValues(); @@ -272,20 +274,20 @@ public class RestMusicBmAPI { if ((ttl != null) && (timestamp != null)) { - logger.info("both there"); + logger.info(EELFLoggerDelegate.applicationLogger,"both there"); queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); queryObject.addValue(Integer.parseInt(ttl)); queryObject.addValue(Long.parseLong(timestamp)); } if ((ttl != null) && (timestamp == null)) { - logger.info("ONLY TTL there"); + logger.info(EELFLoggerDelegate.applicationLogger,"ONLY TTL there"); queryObject.appendQueryString(" USING TTL ?"); queryObject.addValue(Integer.parseInt(ttl)); } if ((ttl == null) && (timestamp != null)) { - logger.info("ONLY timestamp there"); + logger.info(EELFLoggerDelegate.applicationLogger,"ONLY timestamp there"); queryObject.appendQueryString(" USING TIMESTAMP ?"); queryObject.addValue(Long.parseLong(timestamp)); } @@ -305,9 +307,8 @@ public class RestMusicBmAPI { + "|json parsing time:" + (jsonParseCompletionTime - startTime) + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime) + "|"; - logger.info(timingString); + logger.info(EELFLoggerDelegate.applicationLogger,timingString); return operationResult; } - } diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index ba0f1a3b..e16cc373 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -1,20 +1,16 @@ /* - * ============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 + * ============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 + * 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. + * 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============================================= * ==================================================================== @@ -26,7 +22,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; -// import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -47,15 +42,17 @@ import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.response.jsonobjects.JsonResponse; 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.MusicServiceException; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicCore.Condition; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; -import org.onap.music.main.MusicCore.Condition; +import org.onap.music.response.jsonobjects.JsonResponse; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; @@ -90,8 +87,7 @@ public class RestMusicDataAPI { * */ - - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicDataAPI.class); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); private static String xLatestVersion = "X-latestVersion"; private class RowIdentifier { @@ -165,8 +161,9 @@ public class RestMusicDataAPI { return resultMap; } - String consistency = MusicUtil.EVENTUAL;// for now this needs only eventual - // consistency + String consistency = MusicUtil.EVENTUAL;// for now this needs only + // eventual + // consistency PreparedQueryObject queryObject = new PreparedQueryObject(); boolean result = false; @@ -182,13 +179,14 @@ public class RestMusicDataAPI { queryObject.appendQueryString(";"); long end = System.currentTimeMillis(); - logger.info("Time taken for setting up query in create keyspace:" + (end - start)); + logger.info(EELFLoggerDelegate.applicationLogger, + "Time taken for setting up query in create keyspace:" + (end - start)); try { result = MusicCore.nonKeyRelatedPut(queryObject, consistency); - logger.debug("resulta = " + result); + logger.error(EELFLoggerDelegate.errorLogger, "resulta = " + result); } catch (Exception e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } logger.debug("result = " + result); @@ -237,7 +235,7 @@ public class RestMusicDataAPI { return resultMap; } } catch (Exception e) { - logger.error(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); } resultMap.remove("uuid"); if (CachingUtil.isAAFApplication(ns)) @@ -286,8 +284,9 @@ public class RestMusicDataAPI { return resultMap; } - String consistency = MusicUtil.EVENTUAL;// for now this needs only eventual - // consistency + String consistency = MusicUtil.EVENTUAL;// for now this needs only + // eventual + // consistency String appName = CachingUtil.getAppName(keyspaceName); String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName); PreparedQueryObject pQuery = new PreparedQueryObject(); @@ -303,10 +302,9 @@ public class RestMusicDataAPI { } else if (count == 1) { pQuery = new PreparedQueryObject(); pQuery.appendQueryString( - "UPDATE admin.keyspace_master SET keyspace_name=?,password=?,is_api=null where uuid = ?;"); + "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), null)); + MusicUtil.DEFAULTKEYSPACENAME)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); MusicCore.nonKeyRelatedPut(pQuery, consistency); } else { @@ -407,14 +405,18 @@ public class RestMusicDataAPI { } } - queryObject.appendQueryString("CREATE TABLE IF NOT EXISTS " + keyspace + "." + tablename - + " " + fieldsString); + queryObject.appendQueryString( + "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); if (propertiesMap != null) queryObject.appendQueryString(" WITH " + propertiesString); queryObject.appendQueryString(";"); - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + try { + result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + } catch (MusicServiceException ex) { + return new JsonResponse(false, ex.getMessage(), "").toMap(); + } return new JsonResponse(result, "", "").toMap(); } @@ -555,20 +557,20 @@ public class RestMusicDataAPI { String timestamp = insObj.getTimestamp(); if ((ttl != null) && (timestamp != null)) { - logger.info("both there"); + logger.info(EELFLoggerDelegate.applicationLogger, "both there"); queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); queryObject.addValue(Integer.parseInt(ttl)); queryObject.addValue(Long.parseLong(timestamp)); } if ((ttl != null) && (timestamp == null)) { - logger.info("ONLY TTL there"); + logger.info(EELFLoggerDelegate.applicationLogger, "ONLY TTL there"); queryObject.appendQueryString(" USING TTL ?"); queryObject.addValue(Integer.parseInt(ttl)); } if ((ttl == null) && (timestamp != null)) { - logger.info("ONLY timestamp there"); + logger.info(EELFLoggerDelegate.applicationLogger, "ONLY timestamp there"); queryObject.appendQueryString(" USING TIMESTAMP ?"); queryObject.addValue(Long.parseLong(timestamp)); } @@ -591,7 +593,7 @@ public class RestMusicDataAPI { : new ReturnType(ResultType.FAILURE, "Null result - Please Contact admin").toMap(); } catch (Exception ex) { - logger.error(ex.getMessage()); + logger.info(EELFLoggerDelegate.applicationLogger, ex.getMessage()); return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap(); } } @@ -642,14 +644,19 @@ public class RestMusicDataAPI { String operationId = UUID.randomUUID().toString();// just for infoging // purposes. String consistency = updateObj.getConsistencyInfo().get("type"); - logger.info("--------------Music " + consistency + " update-" + operationId - + "-------------------------"); + logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency + + " update-" + operationId + "-------------------------"); // obtain the field value pairs of the update PreparedQueryObject queryObject = new PreparedQueryObject(); Map<String, Object> valuesMap = updateObj.getValues(); TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + return new ReturnType(ResultType.FAILURE, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename).toMap(); + } String vectorTs = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); StringBuilder fieldValueString = new StringBuilder("vector_ts=?,"); @@ -689,8 +696,12 @@ public class RestMusicDataAPI { queryObject.addValue(Long.parseLong(timestamp)); } // get the row specifier - RowIdentifier rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), - queryObject); + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); + } catch (MusicServiceException ex) { + return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap(); + } queryObject.appendQueryString( " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";"); @@ -701,8 +712,10 @@ public class RestMusicDataAPI { conditionInfo = null; else {// to avoid parsing repeatedly, just send the select query to // obtain row - String selectQuery = "SELECT * FROM " + keyspace + "." + tablename + " WHERE " - + rowId.rowIdString + ";"; + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + + rowId.rowIdString + ";"); + selectQuery.addValue(rowId.primarKeyValue); conditionInfo = new MusicCore.Condition(updateObj.getConditions(), selectQuery); } @@ -715,8 +728,7 @@ public class RestMusicDataAPI { String lockId = updateObj.getConsistencyInfo().get("lockId"); operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue, queryObject, lockId, conditionInfo); - } - else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { + } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { // this function is mainly for the benchmarks operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); @@ -737,7 +749,7 @@ public class RestMusicDataAPI { String lockManagementTime = operationResult.getTimingInfo(); timingString = timingString + lockManagementTime; } - logger.info(timingString); + logger.info(EELFLoggerDelegate.applicationLogger, timingString); return (operationResult != null) ? operationResult.toMap() : new ReturnType(ResultType.FAILURE, "Null result - Please Contact admin") .toMap(); @@ -800,8 +812,12 @@ public class RestMusicDataAPI { } // get the row specifier - RowIdentifier rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), - queryObject); + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); + } catch (MusicServiceException ex) { + return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap(); + } String rowSpec = rowId.rowIdString.toString(); if ((columnList != null) && (!rowSpec.isEmpty())) { @@ -825,8 +841,10 @@ public class RestMusicDataAPI { conditionInfo = null; else {// to avoid parsing repeatedly, just send the select query to // obtain row - String selectQuery = "SELECT * FROM " + keyspace + "." + tablename + " WHERE " - + rowId.rowIdString + ";"; + PreparedQueryObject selectQuery = new PreparedQueryObject(); + selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + + rowId.rowIdString + ";"); + selectQuery.addValue(rowId.primarKeyValue); conditionInfo = new MusicCore.Condition(delObj.getConditions(), selectQuery); } @@ -861,7 +879,8 @@ public class RestMusicDataAPI { @DELETE @Path("/{keyspace}/tables/{tablename}") @ApiOperation(value = "Drop Table", response = String.class) - + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> dropTable( @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, @@ -893,8 +912,13 @@ public class RestMusicDataAPI { String consistency = "eventual";// for now this needs only eventual // consistency PreparedQueryObject query = new PreparedQueryObject(); - query.appendQueryString("DROP TABLE IF EXISTS " + keyspace + "." + tablename + ";"); - return new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency), "", "").toMap(); + query.appendQueryString("DROP TABLE " + keyspace + "." + tablename + ";"); + try { + return new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency), "", "").toMap(); + } catch (MusicServiceException ex) { + return new JsonResponse(false, ex.getMessage(), "").toMap(); + } + } /** @@ -948,9 +972,12 @@ public class RestMusicDataAPI { PreparedQueryObject queryObject = new PreparedQueryObject(); StringBuilder rowSpec = new StringBuilder(); - RowIdentifier rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), - queryObject); - + RowIdentifier rowId = null; + try { + rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); + } catch (MusicServiceException ex) { + return MusicUtil.setErrorResponse(ex); + } queryObject.appendQueryString( "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowSpec + ";"); @@ -1018,11 +1045,21 @@ public class RestMusicDataAPI { queryObject.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + ";"); else { int limit = -1; // do not limit the number of results - queryObject = selectSpecificQuery(version, minorVersion, patchVersion, aid, ns, userId, - password, keyspace, tablename, info, limit); + try { + queryObject = selectSpecificQuery(version, minorVersion, patchVersion, aid, ns, + userId, password, keyspace, tablename, info, limit); + } catch (MusicServiceException ex) { + return MusicUtil.setErrorResponse(ex); + } } - ResultSet results = MusicCore.get(queryObject); - return MusicCore.marshallResults(results); + + try { + ResultSet results = MusicCore.get(queryObject); + return MusicCore.marshallResults(results); + } catch (MusicServiceException ex) { + return MusicUtil.setErrorResponse(ex); + } + } /** @@ -1032,11 +1069,13 @@ public class RestMusicDataAPI { * @param info * @param limit * @return + * @throws MusicServiceException * @throws Exception */ public PreparedQueryObject selectSpecificQuery(String version, String minorVersion, String patchVersion, String aid, String ns, String userId, String password, - String keyspace, String tablename, UriInfo info, int limit) { + String keyspace, String tablename, UriInfo info, int limit) + throws MusicServiceException { PreparedQueryObject queryObject = new PreparedQueryObject(); StringBuilder rowIdString = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), @@ -1061,13 +1100,23 @@ public class RestMusicDataAPI { * @param rowParams * @param queryObject * @return + * @throws MusicServiceException * @throws Exception */ private RowIdentifier getRowIdentifier(String keyspace, String tablename, - MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject) { + MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject) + throws MusicServiceException { StringBuilder rowSpec = new StringBuilder(); int counter = 0; TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + if (tableInfo == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + throw new MusicServiceException( + "Table information not found. Please check input for table name= " + + keyspace + "." + tablename); + } StringBuilder primaryKey = new StringBuilder(); for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) { String keyName = entry.getKey(); @@ -1084,5 +1133,4 @@ public class RestMusicDataAPI { } return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject); } - } diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 8612b1fa..5f28f447 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -35,10 +35,15 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.onap.music.datastore.jsonobjects.JsonLeasedLock; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.lockingservice.MusicLockState.LockStatus; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonLockResponse; +import org.powermock.core.spi.testresult.Result; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -52,8 +57,9 @@ import io.swagger.annotations.ApiParam; @Api(value="Lock Api") public class RestMusicLocksAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicLocksAPI.class); + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class); private static String xLatestVersion = "X-latestVersion"; + /** * Puts the requesting process in the q for this lock. The corresponding * node will be created in zookeeper if it did not already exist @@ -74,10 +80,10 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, @Context HttpServletResponse response){ response.addHeader(xLatestVersion,MusicUtil.getVersion()); - Boolean status = true; + ResultType status = ResultType.SUCCESS; String lockId = MusicCore.createLockReference(lockName); - if ( lockId == null ) { status = false; } - return new JsonLockResponse(status.toString(),"",lockId).toMap(); + if (lockId == null) { status = ResultType.FAILURE; } + return new JsonLockResponse(status).setLock(lockId).toMap(); } /** @@ -98,8 +104,9 @@ public class RestMusicLocksAPI { @Context HttpServletResponse response){ response.addHeader(xLatestVersion,MusicUtil.getVersion()); String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - Boolean lockStatus = MusicCore.acquireLock(lockName,lockId); - return new JsonLockResponse(lockStatus.toString(),"",lockId,lockStatus.toString(),"").toMap(); + ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId); + return new JsonLockResponse(lockStatus.getResult()).setLock(lockId) + .setMessage(lockStatus.getMessage()).toMap(); } @@ -115,8 +122,10 @@ public class RestMusicLocksAPI { @Context HttpServletResponse response){ response.addHeader(xLatestVersion,MusicUtil.getVersion()); String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); - String lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()).toString(); - return new JsonLockResponse(lockLeaseStatus,"",lockName,lockLeaseStatus,"",String.valueOf(lockObj.getLeasePeriod())).toMap(); + ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); + return new JsonLockResponse(lockLeaseStatus.getResult()).setLock(lockName) + .setMessage(lockLeaseStatus.getMessage()) + .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap(); } @@ -131,13 +140,14 @@ public class RestMusicLocksAPI { @Context HttpServletResponse response){ response.addHeader(xLatestVersion,MusicUtil.getVersion()); String who = MusicCore.whoseTurnIsIt(lockName); - String status = "true"; + ResultType status = ResultType.SUCCESS; String error = ""; if ( who == null ) { - status = "false"; + status = ResultType.FAILURE; error = "There was a problem getting the lock holder"; } - return new JsonLockResponse(status,error,lockName,"",who).toMap(); + return new JsonLockResponse(status).setError(error) + .setLock(lockName).setLockHolder(who).toMap(); } @GET @@ -152,13 +162,13 @@ public class RestMusicLocksAPI { response.addHeader(xLatestVersion,MusicUtil.getVersion()); MusicLockState mls = MusicCore.getMusicLockState(lockName); Map<String,Object> returnMap = null; - JsonLockResponse jsonResponse = new JsonLockResponse("false","",lockName); + JsonLockResponse jsonResponse = new JsonLockResponse(ResultType.FAILURE).setLock(lockName); if(mls == null) { jsonResponse.setError(""); jsonResponse.setMessage("No lock object created yet.."); } else { - jsonResponse.setStatus("true"); - jsonResponse.setLockStatus(mls.getLockStatus().toString()); + jsonResponse.setStatus(ResultType.SUCCESS); + jsonResponse.setLockStatus(mls.getLockStatus()); jsonResponse.setLockHolder(mls.getLockHolder()); } return returnMap; @@ -182,11 +192,13 @@ public class RestMusicLocksAPI { boolean voluntaryRelease = true; MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); Map<String,Object> returnMap = null; - if ( mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED ) { - returnMap = new JsonLockResponse("Unlocked","","").toMap(); + if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) { + returnMap = new JsonLockResponse(ResultType.SUCCESS).setLock(lockId) + .setLockStatus(mls.getLockStatus()).toMap(); } - if ( mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) { - returnMap = new JsonLockResponse("Locked","","").toMap(); + if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) { + returnMap = new JsonLockResponse(ResultType.FAILURE).setLock(lockId) + .setLockStatus(mls.getLockStatus()).toMap(); } return returnMap; } @@ -203,7 +215,7 @@ public class RestMusicLocksAPI { @Context HttpServletResponse response){ response.addHeader(xLatestVersion,MusicUtil.getVersion()); MusicCore.deleteLock(lockName); - return new JsonLockResponse("true","","").toMap(); + return new JsonLockResponse(ResultType.SUCCESS).toMap(); } } diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index 3e92461c..9a4f6c6b 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -44,6 +44,7 @@ import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; 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.main.MusicCore; import com.att.eelf.configuration.EELFLogger; @@ -60,7 +61,7 @@ import io.swagger.annotations.ApiParam; @Api(value="Q Api") public class RestMusicQAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicQAPI.class); + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); /** diff --git a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java index 6b6bc101..f606eb8d 100644 --- a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java @@ -31,6 +31,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.MusicUtil; import com.att.eelf.configuration.EELFLogger; @@ -43,7 +44,8 @@ import io.swagger.annotations.ApiOperation; @Path("/v{version: [0-9]+}/test") @Api(value="Test Api") public class RestMusicTestAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicTestAPI.class); + + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class); /** * Returns a test JSON. This will confirm that REST is working. diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java index 924b0289..f0a32b5c 100644 --- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java @@ -31,6 +31,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.MusicUtil; import com.att.eelf.configuration.EELFLogger; @@ -44,7 +45,8 @@ import io.swagger.annotations.ApiOperation; @Api(value="Version Api") public class RestMusicVersionAPI { - private static EELFLogger logger = EELFManager.getInstance().getLogger(RestMusicVersionAPI.class); + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); + /** * Get the version of MUSIC * @return diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index 5378ebaf..fe7f54ae 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -38,10 +38,11 @@ <property name="metricsLogName" value="metrics" /> <property name="auditLogName" value="audit" /> <property name="debugLogName" value="debug" /> - <property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n " /> + <property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" /> + <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" /> <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" /> <property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" /> - <property name="errorLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDescription}| %msg%n" /> + <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " /> <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property> <property name="logDirectory" value="${logDir}/${componentName}" /> <property name="debugLogDirectory" value="${debugDir}/${componentName}" /> @@ -75,7 +76,7 @@ <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> - <pattern>${defaultPattern}</pattern> + <pattern>${applicationLoggerPattern}</pattern> </encoder> </appender> @@ -189,7 +190,7 @@ <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> - <pattern>${defaultPattern}</pattern> + <pattern>${errorLoggerPattern}</pattern> </encoder> </appender> @@ -213,7 +214,7 @@ <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> - <pattern>${defaultPattern}</pattern> + <pattern>${debugLoggerPattern}</pattern> </encoder> </appender> diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/src/test/java/org/onap/music/unittests/CassandraCQL.java index f40db7b9..cbca37b2 100644 --- a/src/test/java/org/onap/music/unittests/CassandraCQL.java +++ b/src/test/java/org/onap/music/unittests/CassandraCQL.java @@ -108,8 +108,8 @@ public class CassandraCQL { preparedInsertValues2.add(emp_id); preparedInsertValues2.add(emp_name); preparedInsertValues2.add(emp_salary); - address.put("Street", "1 att way"); - address.put("City", "Bedmister"); + address.put("Street", "1 some way"); + address.put("City", "Some town"); preparedInsertValues2.add(address); return preparedInsertValues2; } diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java index 17f911ce..ed328c26 100644 --- a/src/test/java/org/onap/music/unittests/TestMusicCore.java +++ b/src/test/java/org/onap/music/unittests/TestMusicCore.java @@ -30,6 +30,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.lockingservice.MusicLockState; @@ -82,7 +83,7 @@ public class TestMusicCore { } @Test - public void testGetMusicLockState() { + public void testGetMusicLockState() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); Mockito.when(mLockHandle.getLockState("ks1.tb1.pk1")).thenReturn(musicLockState); MusicLockState mls = MusicCore.getMusicLockState("ks1.tb1.pk1"); @@ -93,51 +94,60 @@ public class TestMusicCore { @Test public void testAcquireLockifisMyTurnTrue() { Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Boolean lock = MusicCore.acquireLock("ks1.tn1", "id1"); - assertTrue(lock); + ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); + assertEquals(lock.getResult(), ResultType.SUCCESS); Mockito.verify(mLockHandle).isMyTurn("id1"); } @Test public void testAcquireLockifisMyTurnFalse() { Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); - Boolean lock = MusicCore.acquireLock("ks1.ts1", "id1"); - assertFalse(lock); + ReturnType lock = MusicCore.acquireLock("ks1.ts1", "id1"); + assertEquals(lock.getResult(), ResultType.FAILURE); Mockito.verify(mLockHandle).isMyTurn("id1"); } @Test public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() { Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); - Boolean lock = MusicCore.acquireLock("ks1.tn1", "id1"); - assertTrue(lock); + ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1"); + assertEquals(lock.getResult(), ResultType.SUCCESS); Mockito.verify(mLockHandle).isMyTurn("id1"); } @Test - public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() { + public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Boolean lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); - assertTrue(lock); + ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); + assertEquals(lock.getResult(), ResultType.SUCCESS); Mockito.verify(mLockHandle).isMyTurn("id1"); Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); } @Test - public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() { + public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id2"); Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); - Boolean lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); - assertTrue(lock); + ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); + assertEquals(lock.getResult(), ResultType.SUCCESS); Mockito.verify(mLockHandle).isMyTurn("id1"); Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); } + + @Test + public void testAcquireLockifLockRefDoesntExist() { + Mockito.when(mLockHandle.lockIdExists("bs1")).thenReturn(false); + ReturnType lock = MusicCore.acquireLock("ks1.ts1", "bs1"); + assertEquals(lock.getResult(), ResultType.FAILURE); + assertEquals(lock.getMessage(), "Lockid doesn't exist"); + Mockito.verify(mLockHandle).lockIdExists("bs1"); + } @Test - public void testAcquireLockWithLeasewithLockStatusLOCKED() { + public void testAcquireLockWithLeasewithLockStatusLOCKED() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); @@ -149,7 +159,7 @@ public class TestMusicCore { } @Test - public void testAcquireLockWithLeasewithLockStatusUNLOCKED() { + public void testAcquireLockWithLeasewithLockStatusUNLOCKED() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); @@ -162,7 +172,7 @@ public class TestMusicCore { } @Test - public void testAcquireLockWithLeaseIfNotMyTurn() { + public void testAcquireLockWithLeaseIfNotMyTurn() throws MusicLockingException { MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); @@ -254,7 +264,7 @@ public class TestMusicCore { @Test public void testCriticalPutPreparedQuerywithValidLockId() - throws MusicServiceException, MusicQueryException { + throws MusicServiceException, MusicQueryException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); @@ -272,7 +282,7 @@ public class TestMusicCore { } @Test - public void testCriticalPutPreparedQuerywithInvalidLockId() { + public void testCriticalPutPreparedQuerywithInvalidLockId() throws MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); @@ -286,7 +296,7 @@ public class TestMusicCore { } @Test - public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() { + public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() throws MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); @@ -312,7 +322,7 @@ public class TestMusicCore { } @Test - public void testAtomicPutPreparedQuery() throws MusicServiceException, MusicQueryException { + public void testAtomicPutPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); @@ -337,7 +347,7 @@ public class TestMusicCore { } @Test - public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() { + public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() throws MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); @@ -358,7 +368,7 @@ public class TestMusicCore { } @Test - public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException { + public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); rs = Mockito.mock(ResultSet.class); @@ -381,7 +391,7 @@ public class TestMusicCore { @Test public void testAtomicGetPreparedQuerywithAcquireLockWithLeaseFalse() - throws MusicServiceException { + throws MusicServiceException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); rs = Mockito.mock(ResultSet.class); @@ -414,7 +424,7 @@ public class TestMusicCore { } @Test - public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException { + public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); @@ -430,7 +440,7 @@ public class TestMusicCore { } @Test - public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException { + public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException, MusicLockingException { mDstoreHandle = Mockito.mock(MusicDataStore.class); preparedQueryObject = Mockito.mock(PreparedQueryObject.class); MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); |