aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorThomas Nelson <tn1381@att.com>2018-03-14 00:39:39 +0000
committerGerrit Code Review <gerrit@onap.org>2018-03-14 00:39:39 +0000
commited32276d7d097fb9b53c930133f86a99db6a35dc (patch)
tree0653a737c496a197d4e373245b5a490a40cdc3b0
parent0193eb29ad8bdbd4491afc7f32ce8362898e2ded (diff)
parent3c86680e532b959bd637b6c093b3916ae5bcee11 (diff)
Merge "Docker update and POM fix"
-rw-r--r--distribution/cassandra/docker-entrypoint.sh5
-rw-r--r--distribution/dockermusic/start.sh2
-rwxr-xr-xpom.xml166
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/AppMessages.java10
-rw-r--r--src/main/java/org/onap/music/lockingservice/MusicLockState.java10
-rw-r--r--src/main/java/org/onap/music/lockingservice/MusicLockingService.java2
-rw-r--r--src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java5
-rwxr-xr-xsrc/main/java/org/onap/music/main/CachingUtil.java40
-rw-r--r--src/main/java/org/onap/music/main/MusicCore.java52
-rwxr-xr-xsrc/main/java/org/onap/music/main/MusicUtil.java10
-rw-r--r--src/main/java/org/onap/music/main/ResultType.java5
-rw-r--r--src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java214
-rw-r--r--src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java242
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicAdminAPI.java42
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicDataAPI.java321
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicLocksAPI.java146
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicVersionAPI.java4
-rw-r--r--src/test/java/org/onap/music/unittests/JsonLockResponseTest.java186
-rw-r--r--src/test/java/org/onap/music/unittests/JsonResponseTest.java40
-rw-r--r--src/test/java/org/onap/music/unittests/MusicUtilTest.java10
-rw-r--r--src/test/java/org/onap/music/unittests/TestMusicCore.java20
-rw-r--r--src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java4
-rw-r--r--src/test/java/org/onap/music/unittests/TestRestMusicData.java37
-rw-r--r--version.properties2
24 files changed, 717 insertions, 858 deletions
diff --git a/distribution/cassandra/docker-entrypoint.sh b/distribution/cassandra/docker-entrypoint.sh
index cec4587b..2e2c657e 100644
--- a/distribution/cassandra/docker-entrypoint.sh
+++ b/distribution/cassandra/docker-entrypoint.sh
@@ -1,6 +1,11 @@
#!/bin/bash
set -e
+for f in /docker-entrypoint-initdb.d/*.cql; do
+ chown cassandra.root "$f"
+done
+
+
# first arg is `-f` or `--some-option`
# or there are no args
if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then
diff --git a/distribution/dockermusic/start.sh b/distribution/dockermusic/start.sh
index 57b05890..c3763c45 100644
--- a/distribution/dockermusic/start.sh
+++ b/distribution/dockermusic/start.sh
@@ -40,7 +40,7 @@ docker network create music-net;
# Start Cassandra
docker run -d --rm --name music-db --network music-net \
-p "7000:7000" -p "7001:7001" -p "7199:7199" -p "9042:9042" -p "9160:9160" \
--e CASSNAME=${CASS_USERNAME} \
+-e CASSUSER=${CASS_USERNAME} \
-e CASSPASS=${CASS_PASSWORD} \
${CASS_IMG};
diff --git a/pom.xml b/pom.xml
index 891c3a2b..b57733dd 100755
--- a/pom.xml
+++ b/pom.xml
@@ -1,24 +1,34 @@
-<!-- ============LICENSE_START==========================================
- org.onap.music ===================================================================
- Copyright (c) 2017 AT&T Intellectual Property ===================================================================
- Licensed under the Apache License, Version 2.0 (the "License"); you may not
- use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
- by applicable law or agreed to in writing, software distributed under the
- License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
- OF ANY KIND, either express or implied. See the License for the specific
- language governing permissions and limitations under the License. ============LICENSE_END=============================================
- ==================================================================== -->
+<!--
+ ============LICENSE_START==========================================
+ org.onap.music
+ ===================================================================
+ Copyright (c) 2017 AT&T Intellectual Property
+ ===================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ ============LICENSE_END=============================================
+ ====================================================================
+-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.onap.music</groupId>
<artifactId>MUSIC</artifactId>
<packaging>war</packaging>
- <version>2.4.15</version>
+ <version>2.4.18</version>
<description>
This is the MUSIC REST interface, packaged as a war file.
- </description>
+ </description>
<parent>
<groupId>org.onap.oparent</groupId>
@@ -29,8 +39,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <jersey1.version>1.17</jersey1.version>
- <jersey2.version>2.26</jersey2.version>
+ <jersey1.version>1.19</jersey1.version>
<jaxrs.version>2.0.1</jaxrs.version>
<cassandra.version>3.2.0</cassandra.version>
<zookeeper.version>3.4.6</zookeeper.version>
@@ -158,6 +167,21 @@
</build>
<dependencies>
+ <!-- Development -->
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.4</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ <version>3.0.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <!-- /Development -->
+
<!-- Logging -->
<dependency>
<groupId>ch.qos.logback</groupId>
@@ -187,13 +211,16 @@
<version>1.0.1-oss</version>
</dependency>
<!-- End Logging -->
-
+
+ <!-- Cassandra -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>${cassandra.version}</version>
</dependency>
-
+ <!-- /Cassandra -->
+
+ <!-- Zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
@@ -205,7 +232,9 @@
</exclusion>
</exclusions>
</dependency>
-
+ <!-- /Zookeeper -->
+
+ <!-- Jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
@@ -221,19 +250,13 @@
<artifactId>jersey-json</artifactId>
<version>${jersey1.version}</version>
</dependency>
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.4</version>
- <scope>provided</scope>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-servlet</artifactId>
+ <version>${jersey1.version}</version>
</dependency>
- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId>
- <version>3.0.1</version> <scope>provided</scope> </dependency>
- <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId>
- <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency>
- <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId>
- <version>3.3.9</version> </dependency> -->
+ <!-- /Jersey -->
+
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jcs-core</artifactId>
@@ -244,17 +267,14 @@
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
+
+ <!-- Testing -->
<dependency>
- <groupId>io.swagger</groupId>
- <artifactId>swagger-jersey-jaxrs</artifactId>
- <version>1.5.8</version>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>19.0</version>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
</dependency>
- <!-- Testing -->
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
@@ -262,18 +282,6 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.9.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>2.3.0</version>
@@ -289,13 +297,29 @@
</exclusions>
<scope>test</scope>
</dependency>
- <!-- Added to force update dependency jars that are not secure Cassandra-Unit
- depends on older version that is not secure -->
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.9.0</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- /Testing -->
+
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
+ <dependency>
+ <groupId>io.swagger</groupId>
+ <artifactId>swagger-jersey-jaxrs</artifactId>
+ <version>1.5.8</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>19.0</version>
+ </dependency>
</dependencies>
<reporting>
@@ -362,35 +386,15 @@
</build>
</image>
<!-- Zookeeper -->
- <!--
- <image>
- <name>onap/music/zookeeper_music</name>
- <alias>docker_zookeeper</alias>
- <build>
- <cleanup>true</cleanup>
- <tags>
- <tag>3.4-${timestamp}</tag>
- <tag>3.4-latest</tag>
- </tags>
- <dockerFileDir>${project.basedir}/distribution/zookeeper</dockerFileDir>
- </build>
- </image>
- -->
+ <!-- <image> <name>onap/music/zookeeper_music</name>
+ <alias>docker_zookeeper</alias> <build> <cleanup>true</cleanup> <tags> <tag>3.4-${timestamp}</tag>
+ <tag>3.4-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/zookeeper</dockerFileDir>
+ </build> </image> -->
<!-- tomcat 8.5 -->
- <!--
- <image>
- <name>onap/music/tomcat_music</name>
- <alias>docker_tomcat</alias>
- <build>
- <cleanup>true</cleanup>
- <tags>
- <tag>8.5-${timestamp}</tag>
- <tag>8.5-latest</tag>
- </tags>
- <dockerFileDir>${project.basedir}/distribution/tomcat</dockerFileDir>
- </build>
- </image>\
- -->
+ <!-- <image> <name>onap/music/tomcat_music</name>
+ <alias>docker_tomcat</alias> <build> <cleanup>true</cleanup> <tags> <tag>8.5-${timestamp}</tag>
+ <tag>8.5-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/tomcat</dockerFileDir>
+ </build> </image>\ -->
</images>
</configuration>
<executions>
diff --git a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java b/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
index f265eae3..2c7952b2 100644
--- a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
+++ b/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
@@ -45,7 +45,8 @@ public enum AppMessages {
* [ERR206E] Cache not authenticated
*
*
- * 300-399 Data Access/Integrity Related
+ * 300-399 Data Access/Integrity Related
+ * [ERR300E] Incorrect data
*
* 400-499 - Cassandra Query Related
* [ERR400E] Error while processing prepared query object
@@ -91,7 +92,7 @@ public enum AppMessages {
- MISSINGINFO("[ERR100E]", "Missing Information ","Details: NA", "Please check application credentials and headers"),
+ MISSINGINFO("[ERR100E]", "Missing Information ","Details: NA", "Please check application credentials and/or headers"),
AUTHENTICATIONERROR("[ERR101E]", "Authentication error occured ","Details: NA", "Please verify application credentials"),
CONNCECTIVITYERROR("[ERR200E]"," Connectivity error","Details: NA ","Please check connectivity to external resources"),
HOSTUNAVAILABLE("[ERR201E]","Host not available","Details: NA","Please verify the host details"),
@@ -101,6 +102,11 @@ public enum AppMessages {
SESSIONEXPIRED("[ERR205E]"," Session Expired","","Session has expired."),
CACHEAUTHENTICATION("[ERR206E]","Cache not authenticated",""," Cache not authenticated"),
+ INCORRECTDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"),
+ MULTIPLERECORDS("[ERR301E]"," Multiple records found",""," Please verify the request payload and try again"),
+ ALREADYEXIST("[ERR302E]"," Record already exist",""," Please verify the request payload and try again"),
+ MISSINGDATA("[ERR300E]"," Incorrect data",""," Please verify the request payload and try again"),
+
QUERYERROR("[ERR400E]","Error while processing prepared query object",""," Please verify the query"),
SESSIONFAILED("[ERR401E]","Executing Session Failure for Request","","Please verify the session and request"),
diff --git a/src/main/java/org/onap/music/lockingservice/MusicLockState.java b/src/main/java/org/onap/music/lockingservice/MusicLockState.java
index 5d051be4..6c31410f 100644
--- a/src/main/java/org/onap/music/lockingservice/MusicLockState.java
+++ b/src/main/java/org/onap/music/lockingservice/MusicLockState.java
@@ -45,6 +45,12 @@ public class MusicLockState implements Serializable {
boolean needToSyncQuorum = false;
String lockHolder;
long leasePeriod = Long.MAX_VALUE, leaseStartTime = -1;
+
+ private String errorMessage = null;
+
+ public MusicLockState(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
public MusicLockState(LockStatus lockStatus, String lockHolder) {
this.lockStatus = lockStatus;
@@ -100,6 +106,10 @@ public class MusicLockState implements Serializable {
this.lockHolder = lockHolder;
}
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
public byte[] serialize() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
diff --git a/src/main/java/org/onap/music/lockingservice/MusicLockingService.java b/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
index 2fc8a151..44a00bcf 100644
--- a/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
+++ b/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
@@ -128,7 +128,7 @@ public class MusicLockingService implements Watcher {
return false;
}
- public void unlockAndDeleteId(String lockIdWithDollar) {
+ public void unlockAndDeleteId(String lockIdWithDollar) throws KeeperException.NoNodeException {
String lockId = lockIdWithDollar.replace('$', '/');
zkLockHandle.unlock(lockId);
}
diff --git a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
index 51efafbf..e99df255 100644
--- a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
+++ b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
@@ -23,6 +23,7 @@ import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
@@ -157,8 +158,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
* your request in the queue for locking in case you do not already hold the lock.
*
* @throws RuntimeException throws a runtime exception if it cannot connect to zookeeper.
+ * @throws NoNodeException
*/
- public synchronized void unlock(String lockId) throws RuntimeException {
+ public synchronized void unlock(String lockId) throws RuntimeException, KeeperException.NoNodeException {
final String id = lockId;
if (!isClosed() && id != null) {
try {
@@ -175,6 +177,7 @@ public class ZkStatelessLockService extends ProtocolSupport {
Thread.currentThread().interrupt();
} catch (KeeperException.NoNodeException e) {
// do nothing
+ throw new KeeperException.NoNodeException("Lock doesn't exists. Release lock operation failed.");
} catch (KeeperException e) {
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java
index aee3abbf..16a02862 100755
--- a/src/main/java/org/onap/music/main/CachingUtil.java
+++ b/src/main/java/org/onap/music/main/CachingUtil.java
@@ -60,7 +60,6 @@ public class CachingUtil implements Runnable {
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
- private static CacheAccess<String, String> musicLockCache = JCS.getInstance("musicLockCache");
private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
private static Map<String, Number> userAttempts = new HashMap<>();
@@ -98,7 +97,6 @@ public class CachingUtil implements Runnable {
String userId = row.getString("username");
String password = row.getString("password");
String keySpace = row.getString("application_name");
- String uuid = row.getUUID("uuid").toString();
try {
userAttempts.put(nameSpace, 0);
AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
@@ -107,7 +105,6 @@ public class CachingUtil implements Runnable {
map.put(userId, password);
aafCache.put(nameSpace, map);
musicCache.put(nameSpace, keySpace);
- musicLockCache.put(nameSpace, uuid);
logger.debug("Cronjob: Cache Updated with AAF response for namespace "
+ nameSpace);
}
@@ -260,43 +257,6 @@ public class CachingUtil implements Runnable {
resultMap.put("aid", uuid);
return resultMap;
}
-
-
- public static Map<String, Object> authenticateAIDUserLock(String aid, String nameSpace)
- throws Exception {
- Map<String, Object> resultMap = new HashMap<>();
- String uuid = null;
-
- if (musicLockCache.get(nameSpace) == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT uuid from admin.keyspace_master where application_name = '"
- + nameSpace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- uuid = rs.getUUID("uuid").toString();
- musicLockCache.put(nameSpace, uuid);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- resultMap.put("Exception", "Unauthorized operation. Check AID and Namespace. ");
- return resultMap;
- }
- if (!musicLockCache.get(nameSpace).toString().equals(aid)) {
- resultMap.put("Exception Message",
- "Unauthorized operation. Invalid AID for the Namespace");
- return resultMap;
- }
- } else if (musicLockCache.get(nameSpace) != null
- && !musicLockCache.get(nameSpace).toString().equals(aid)) {
- resultMap.put("Exception Message",
- "Unauthorized operation. Invalid AID for the Namespace");
- return resultMap;
- }
- return resultMap;
- }
-
-
-
public static void updateMusicCache(String aid, String keyspace) {
logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with aid " + aid);
diff --git a/src/main/java/org/onap/music/main/MusicCore.java b/src/main/java/org/onap/music/main/MusicCore.java
index 73a6ee55..6ce6b0d3 100644
--- a/src/main/java/org/onap/music/main/MusicCore.java
+++ b/src/main/java/org/onap/music/main/MusicCore.java
@@ -27,6 +27,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.NoNodeException;
import org.onap.music.datastore.MusicDataStore;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.datastore.jsonobjects.JsonKeySpace;
@@ -244,7 +246,7 @@ public class MusicCore {
}
}
- public static ReturnType acquireLock(String key, String lockId) {
+ public static ReturnType acquireLock(String key, String lockId) throws MusicLockingException {
/*
* 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
@@ -255,6 +257,7 @@ public class MusicCore {
result = getLockingServiceHandle().isMyTurn(lockId);
} catch (MusicLockingException e2) {
logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId + " " + e2);
+ throw new MusicLockingException();
}
if (!result) {
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock");
@@ -265,6 +268,7 @@ public class MusicCore {
}
} catch (MusicLockingException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ throw new MusicLockingException();
}
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure");
return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock");
@@ -463,9 +467,9 @@ public class MusicCore {
long start = System.currentTimeMillis();
try {
getLockingServiceHandle().unlockAndDeleteId(lockId);
- } catch (MusicLockingException e) {
+ } catch (MusicLockingException | NoNodeException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
+ }
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
}
@@ -476,6 +480,10 @@ public class MusicCore {
getLockingServiceHandle().unlockAndDeleteId(lockId);
} catch (MusicLockingException e1) {
logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ } catch (KeeperException.NoNodeException nne) {
+ logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne);
+ MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed.");
+ return mls;
}
String lockName = getLockNameFromId(lockId);
MusicLockState mls;
@@ -500,7 +508,11 @@ public class MusicCore {
}
public static void voluntaryReleaseLock(String lockId) throws MusicLockingException{
- getLockingServiceHandle().unlockAndDeleteId(lockId);
+ try {
+ getLockingServiceHandle().unlockAndDeleteId(lockId);
+ } catch (KeeperException.NoNodeException e) {
+ // ??? No way
+ }
}
/**
@@ -601,6 +613,7 @@ public class MusicCore {
} catch (MusicServiceException | MusicQueryException ex) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
+ return new ReturnType(ResultType.FAILURE, ex.getMessage());
}
if (result) {
return new ReturnType(ResultType.SUCCESS, "Success");
@@ -663,7 +676,7 @@ public class MusicCore {
*
*
*/
- public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException {
+ public static ResultType 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;
@@ -673,7 +686,7 @@ public class MusicCore {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
throw new MusicServiceException(ex.getMessage());
}
- return result;
+ return result?ResultType.SUCCESS:ResultType.FAILURE;
}
/**
@@ -883,18 +896,13 @@ public class MusicCore {
resultMap.put("Exception", "Aid is mandatory for nonAAF applications ");
return resultMap;
}
- if(operation.contains("Lock")) {
- resultMap = CachingUtil.authenticateAIDUserLock(aid, nameSpace);
- }
- else {
- resultMap = CachingUtil.authenticateAIDUser(aid, keyspace);
- }
+ resultMap = CachingUtil.authenticateAIDUser(aid, keyspace);
if (!resultMap.isEmpty())
return resultMap;
}
if (aid == null && (userId == null || password == null)) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId
+ " :: password: " + password);
resultMap.put("Exception",
@@ -958,4 +966,22 @@ public class MusicCore {
return resultMap;
}
+
+ /**
+ * @param lockName
+ * @return
+ */
+ public static Map<String, Object> validateLock(String lockName) {
+ Map<String, Object> resultMap = new HashMap<>();
+ String[] locks = lockName.split("\\.");
+ if(locks.length < 3) {
+ resultMap.put("Exception", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
+ return resultMap;
+ }
+ String keyspace= locks[0];
+ if(keyspace.startsWith("$"))
+ keyspace = keyspace.substring(1);
+ resultMap.put("keyspace",keyspace);
+ return resultMap;
+ }
}
diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java
index 0f77614e..c0b968be 100755
--- a/src/main/java/org/onap/music/main/MusicUtil.java
+++ b/src/main/java/org/onap/music/main/MusicUtil.java
@@ -475,14 +475,4 @@ public class MusicUtil {
}
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/main/ResultType.java b/src/main/java/org/onap/music/main/ResultType.java
index 6b0c5252..61ba0295 100644
--- a/src/main/java/org/onap/music/main/ResultType.java
+++ b/src/main/java/org/onap/music/main/ResultType.java
@@ -23,8 +23,9 @@ package org.onap.music.main;
public enum ResultType {
SUCCESS("Success"), FAILURE("Failure"),
- SYNTAXERROR("SyntaxError"), EXCEPTION("Exception");
-
+ SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"),
+ BODYMISSING("Incomplete Request body. Please correct your input request and retry.");
+
private String result;
ResultType(String result) {
diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java
deleted file mode 100644
index 3e2f1557..00000000
--- a/src/main/java/org/onap/music/response/jsonobjects/JsonLockResponse.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ============LICENSE_END=============================================
- * ====================================================================
- */
-package org.onap.music.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 ResultType status;
- private String error;
- private String message;
- private String lock;
- private LockStatus lockStatus;
- private String lockHolder;
- private String lockLease;
-
-
- /**
- * Create a JSONLock Response
- * Use setters to provide more information as in
- * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname)
- * @param status
- */
- public JsonLockResponse(ResultType status) {
- this.status = status;
- }
-
-
-
- /**
- *
- * @return
- */
- public String getLock() {
- return lock;
- }
-
- /**
- *
- * @param lock
- */
- public JsonLockResponse setLock(String lock) {
- this.lock = lock;
- return this;
- }
-
- /**
- *
- * @return
- */
- @ApiModelProperty(value = "Overall status of the response.",
- allowableValues = "Success,Failure")
- public ResultType getStatus() {
- return status;
- }
-
- /**
- *
- * @param status
- */
- public JsonLockResponse setStatus(ResultType status) {
- this.status = status;
- return this;
- }
-
- /**
- *
- * @return the error
- */
- @ApiModelProperty(value = "Error value")
- public String getError() {
- return error;
- }
-
- /**
- *
- * @param error
- */
- public JsonLockResponse setError(String error) {
- this.error = error;
- return this;
- }
-
- /**
- *
- * @return the message
- */
- @ApiModelProperty(value = "Message if any need to be conveyed about the lock")
- public String getMessage() {
- return message;
- }
-
- /**
- *
- * @param message
- */
- public JsonLockResponse setMessage(String message) {
- this.message = message;
- return this;
- }
-
- /**
- *
- * @return the lockStatus
- */
- @ApiModelProperty(value = "Status of the lock")
- public LockStatus getLockStatus() {
- return lockStatus;
- }
-
- /**
- *
- * @param lockStatus
- */
- public JsonLockResponse setLockStatus(LockStatus lockStatus) {
- this.lockStatus = lockStatus;
- return this;
- }
-
- /**
- *
- *
- * @return the lockHolder
- */
- @ApiModelProperty(value = "Holder of the Lock")
- public String getLockHolder() {
- return lockHolder;
- }
-
- /**
- *
- * @param lockHolder
- */
- public JsonLockResponse setLockHolder(String lockHolder) {
- this.lockHolder = lockHolder;
- return this;
- }
-
-
-
- /**
- * @return the lockLease
- */
- public String getLockLease() {
- return lockLease;
- }
-
- /**
- * @param lockLease the lockLease to set
- */
- public JsonLockResponse setLockLease(String lockLease) {
- this.lockLease = lockLease;
- return this;
- }
-
- /**
- * Convert to Map
- *
- * @return
- */
- public Map<String, Object> toMap() {
- Map<String, Object> fullMap = new HashMap<>();
- Map<String, Object> lockMap = new HashMap<>();
- 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;
- }
-
- /**
- * Convert to String
- */
- @Override
- public String toString() {
- return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message
- + ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder="
- + lockHolder + "]";
- }
-
-}
diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
index d44f9fe7..a406afce 100644
--- a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
+++ b/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
@@ -21,75 +21,245 @@
*/
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 com.datastax.driver.core.ColumnDefinitions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.ColumnDefinitions.Definition;
+
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "JsonResponse", description = "General Response JSON")
public class JsonResponse {
- private Boolean status = false;
- private String error = "";
- private String version = "";
+ /* Status is required */
+ private ResultType status;
+
+ /* Standard informational fields */
+ private String error;
+ private String message;
+
+ /* versioning */
+ private String musicVersion;
+
+ /* Data Fields */
+ private Map<String, HashMap<String, Object>> dataResult;
+
+ /* Locking fields */
+ private String lock;
+ private LockStatus lockStatus;
+ private String lockHolder;
+ private String lockLease;
- public JsonResponse(Boolean status, String error, String version) {
- this.status = status;
- this.error = error;
- this.version = version;
- }
- public JsonResponse() {
- this.status = false;
- this.error = "";
- this.version = "";
+ /**
+ * Create a JSONLock Response
+ * Use setters to provide more information as in
+ * JsonLockResponse(ResultType.SUCCESS).setMessage("We did it").setLock(mylockname)
+ * @param status
+ */
+ public JsonResponse(ResultType status) {
+ this.status = status;
}
- @ApiModelProperty(value = "Status value")
- public Boolean getStatus() {
+ /**
+ *
+ * @return
+ */
+ @ApiModelProperty(value = "Overall status of the response.",
+ allowableValues = "Success,Failure")
+ public ResultType getStatus() {
return status;
}
/**
*
- * @param statusIn
- * @return
+ * @param status
*/
- private String fixStatus(String statusIn) {
- if (statusIn.equalsIgnoreCase("false")) {
- return "FAILURE";
- }
- return "SUCCESS";
- }
-
- public void setStatus(Boolean status) {
+ public JsonResponse setStatus(ResultType status) {
this.status = status;
+ return this;
}
+ /**
+ *
+ * @return the error
+ */
@ApiModelProperty(value = "Error value")
public String getError() {
return error;
}
- public void setError(String error) {
+ /**
+ *
+ * @param error
+ */
+ public JsonResponse setError(String error) {
this.error = error;
+ return this;
+ }
+
+ /**
+ *
+ * @return the message
+ */
+ @ApiModelProperty(value = "Message value")
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ *
+ * @param message
+ */
+ public JsonResponse setMessage(String message) {
+ this.message = message;
+ return this;
+ }
+
+
+ /**
+ *
+ * @return the music version
+ */
+ public String getMusicVersion() {
+ return this.musicVersion;
+ }
+
+ /**
+ *
+ * @param version of music
+ * @return
+ */
+ public JsonResponse setMusicVersion(String version) {
+ this.musicVersion = version;
+ return this;
+ }
+
+ public Map<String, HashMap<String, Object>> getDataResult() {
+ return this.dataResult;
+ }
+
+ public JsonResponse setDataResult(Map<String, HashMap<String, Object>> map) {
+ this.dataResult = map;
+ return this;
+ }
+
+ /**
+ *
+ * @return
+ */
+ public String getLock() {
+ return lock;
+ }
+
+ /**
+ *
+ * @param lock
+ */
+ public JsonResponse setLock(String lock) {
+ this.lock = lock;
+ return this;
+ }
+
+ /**
+ *
+ * @return the lockStatus
+ */
+ @ApiModelProperty(value = "Status of the lock")
+ public LockStatus getLockStatus() {
+ return lockStatus;
+ }
+
+ /**
+ *
+ * @param lockStatus
+ */
+ public JsonResponse setLockStatus(LockStatus lockStatus) {
+ this.lockStatus = lockStatus;
+ return this;
+ }
+
+ /**
+ *
+ *
+ * @return the lockHolder
+ */
+ @ApiModelProperty(value = "Holder of the Lock")
+ public String getLockHolder() {
+ return lockHolder;
}
- @ApiModelProperty(value = "Version value")
- public String getVersion() {
- return version;
+ /**
+ *
+ * @param lockHolder
+ */
+ public JsonResponse setLockHolder(String lockHolder) {
+ this.lockHolder = lockHolder;
+ return this;
+ }
+
+
+
+ /**
+ * @return the lockLease
+ */
+ public String getLockLease() {
+ return lockLease;
}
- public void setVersion(String version) {
- this.version = version;
+ /**
+ * @param lockLease the lockLease to set
+ */
+ public JsonResponse setLockLease(String lockLease) {
+ this.lockLease = lockLease;
+ return this;
}
+ /**
+ * Convert to Map
+ *
+ * @return
+ */
public Map<String, Object> toMap() {
- Map<String, Object> newMap = new HashMap<>();
- newMap.put("status", fixStatus(String.valueOf(status)));
- newMap.put("error", error);
- newMap.put("version", version);
- return newMap;
+ Map<String, Object> fullMap = new HashMap<>();
+ fullMap.put("status", status);
+ if (error!=null) {fullMap.put("error", error);}
+ if (message!=null) {fullMap.put("message", message);}
+
+ if (musicVersion!=null) {fullMap.put("version", musicVersion);}
+
+ if (dataResult!=null) {
+ fullMap.put("result", dataResult);
+ }
+
+ if (lock!=null) {
+ Map<String, Object> lockMap = new HashMap<>();
+ if (lock!=null) {lockMap.put("lock", lock);}
+ if (lockStatus!=null) {lockMap.put("lock-status", lockStatus);}
+ if (lockHolder!=null) {lockMap.put("lock-holder", lockHolder);}
+ if (lockLease!=null) {lockMap.put("lock-lease", lockLease);}
+ fullMap.put("lock", lockMap);
+ }
+
+ return fullMap;
}
+
+ /**
+ * Convert to String
+ */
+ @Override
+ public String toString() {
+ return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message
+ + ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder="
+ + lockHolder + "]";
+ }
+
}
diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
index cbe9ec9c..b8008791 100755
--- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
+++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
@@ -45,6 +45,8 @@ import org.onap.music.eelf.logging.format.ErrorTypes;
import org.onap.music.main.CachingUtil;
import org.onap.music.main.MusicCore;
import org.onap.music.main.MusicUtil;
+import org.onap.music.main.ResultType;
+
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
@@ -75,9 +77,10 @@ public class RestMusicAdminAPI {
String password = jsonObj.getPassword();
response.addHeader("X-latestVersion", MusicUtil.getVersion());
if (appName == null || userId == null || isAAF == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
resultMap.put("Exception",
- "Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
+ "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
+ response.setStatus(401);
return resultMap;
}
@@ -135,8 +138,10 @@ public class RestMusicAdminAPI {
String isAAF = jsonObj.getIsAAF();
if (appName == null && uuid == null && isAAF == null) {
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
resultMap.put("Exception",
- "Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
+ "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
+ response.setStatus(401);
return resultMap;
}
@@ -193,7 +198,9 @@ public class RestMusicAdminAPI {
PreparedQueryObject pQuery = new PreparedQueryObject();
String consistency = MusicUtil.EVENTUAL;;
if (appName == null && aid == null) {
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
+ response.setStatus(400);
return resultMap;
}
if (aid != null) {
@@ -213,12 +220,15 @@ public class RestMusicAdminAPI {
pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
UUID.fromString(aid)));
- boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- if (result) {
+ ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
+ if (result==ResultType.SUCCESS) {
resultMap.put("Success", "Your application has been deleted successfully");
} else {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded");
+ resultMap.put("Exception","Oops. Spomething went wrong. Please make sure Aid is correct or Application is onboarded");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
+ return resultMap;
+
}
return resultMap;
}
@@ -235,6 +245,8 @@ public class RestMusicAdminAPI {
if (rows.size() == 0) {
resultMap.put("Exception",
"Application not found. Please make sure Application exists.");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
return resultMap;
} else if (rows.size() == 1) {
uuid = rows.get(0).getUUID("uuid").toString();
@@ -259,6 +271,8 @@ public class RestMusicAdminAPI {
return resultMap;
} else {
resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid.");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MULTIPLERECORDS ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
}
return resultMap;
@@ -284,12 +298,16 @@ public class RestMusicAdminAPI {
if (aid == null) {
resultMap.put("Exception", "Please make sure Aid is present");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
return resultMap;
}
if (appName == null && userId == null && password == null && isAAF == null) {
resultMap.put("Exception",
"No parameters found to update. Please update atleast one parameter.");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
return resultMap;
}
@@ -302,6 +320,8 @@ public class RestMusicAdminAPI {
if (!rs.all().isEmpty()) {
resultMap.put("Exception", "Application " + appName
+ " has already been onboarded. Please contact admin.");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.ALREADYEXIST ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
return resultMap;
}
}
@@ -329,13 +349,15 @@ public class RestMusicAdminAPI {
pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
- boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
+ ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- if (result) {
+ if (result==ResultType.SUCCESS) {
resultMap.put("Success", "Your application has been updated successfully");
} else {
resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded");
+ "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded");
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+ response.setStatus(400);
}
return resultMap;
diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
index e7af8f9f..bcdb8dd2 100755
--- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
+++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
@@ -151,34 +151,37 @@ public class RestMusicDataAPI {
@ApiParam(value = "Keyspace Name",
required = true) @PathParam("name") String keyspaceName,
@Context HttpServletResponse response) {
- Map<String, Object> resultMap = CachingUtil.verifyOnboarding(ns, userId, password);
+ Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
+ if(kspObject == null || kspObject.getReplicationInfo() == null) {
+ authMap.put(ResultType.EXCEPTION.getResult(), ResultType.BODYMISSING.getResult());
+ return authMap;
+ }
try {
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
+ authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"createKeySpace");
} catch (Exception e) {
logger.error(EELFLoggerDelegate.applicationLogger,
"Exception while authenting the user.");
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap();
}
String newAid = null;
- if (!resultMap.isEmpty()) {
- if (resultMap.containsKey("aid")) {
- newAid = (String) resultMap.get("aid");
- } else
- return resultMap;
+ if (!authMap.isEmpty()) {
+ if (authMap.containsKey("aid")) {
+ newAid = (String) authMap.get("aid");
+ } else {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+ }
}
String consistency = MusicUtil.EVENTUAL;// for now this needs only
- // eventual
- // consistency
+ // eventual consistency
PreparedQueryObject queryObject = new PreparedQueryObject();
- boolean result = false;
long start = System.currentTimeMillis();
Map<String, Object> replicationInfo = kspObject.getReplicationInfo();
String repString = null;
@@ -199,34 +202,32 @@ public class RestMusicDataAPI {
logger.info(EELFLoggerDelegate.applicationLogger,
"Time taken for setting up query in create keyspace:" + (end - start));
+ ResultType result = ResultType.FAILURE;
try {
result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
logger.error(EELFLoggerDelegate.errorLogger, "resulta = " + result);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put("Exception", "Couldn't create keyspace. Please make sure all the information is correct.");
-
+ return new JsonResponse(ResultType.FAILURE)
+ .setError("Couldn't create keyspace. Please make sure all the information is correct.").toMap();
}
- logger.debug("result = " + result);
- if (!result) {
- resultMap.put("Status", String.valueOf(result));
- if(!resultMap.containsKey("Exception"))
- resultMap.put("Exception", "Keyspace already exists. Please contact admin.");
- if (resultMap.get("uuid").equals("new")) {
+
+ if (result==ResultType.FAILURE) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "Cannot create keyspace, cleaning up");
+ JsonResponse resultJson = new JsonResponse(ResultType.FAILURE);
+ resultJson.setError("Keyspace already exists. Please contact admin.");
+ if (authMap.get("uuid").equals("new")) {
queryObject = new PreparedQueryObject();
queryObject.appendQueryString(
"DELETE FROM admin.keyspace_master where uuid = " + newAid);
queryObject.appendQueryString(";");
try {
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
+ MusicCore.nonKeyRelatedPut(queryObject, consistency);
} catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put("Exception", e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Error cleaning up createKeyspace. Cannot DELETE uuid. " + e.getMessage());
}
- resultMap.remove("aid");
- resultMap.remove("uuid");
- return resultMap;
-
+ return resultJson.toMap();
} else {
queryObject = new PreparedQueryObject();
queryObject.appendQueryString(
@@ -236,50 +237,33 @@ public class RestMusicDataAPI {
MusicUtil.DEFAULTKEYSPACENAME));
queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid));
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put("Exception", "Unable to process input data. Invalid input data type. "
- + "Please check keyspace_name and aid.. ");
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Error cleaning up createKeyspace. Cannot get correct data types" + e.getMessage());
}
try {
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
+ MusicCore.nonKeyRelatedPut(queryObject, consistency);
} catch (MusicServiceException e) {
- e.printStackTrace();
logger.error(EELFLoggerDelegate.errorLogger, "Unable to process operation. Error: "+e.getMessage());
- resultMap.put("Exception", "Unable to process operation. Error: "+e.getMessage());
- return resultMap;
}
- resultMap.remove("aid");
- resultMap.remove("uuid");
- return resultMap;
+ return resultJson.toMap();
}
-
}
+
try {
queryObject = new PreparedQueryObject();
queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
+ "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
+ MusicCore.nonKeyRelatedPut(queryObject, consistency);
queryObject = new PreparedQueryObject();
queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
+ " to '" + userId + "'");
queryObject.appendQueryString(";");
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
+ MusicCore.nonKeyRelatedPut(queryObject, consistency);
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
}
- resultMap.remove("uuid");
- try {
- if (CachingUtil.isAAFApplication(ns))
- resultMap.remove("aid");
- } catch (MusicServiceException e) {
- e.printStackTrace();
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put("Exception", e.getMessage());
- return resultMap;
- }
- resultMap.put("Status", String.valueOf(result));
- return resultMap;
-
+
+ return new JsonResponse(ResultType.SUCCESS).toMap();
}
/**
@@ -312,13 +296,13 @@ public class RestMusicDataAPI {
@ApiParam(value = "Keyspace Name",
required = true) @PathParam("name") String keyspaceName,
@Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password,
+ Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password,
keyspaceName, aid, "dropKeySpace");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return authMap;
}
String consistency = MusicUtil.EVENTUAL;// for now this needs only
@@ -334,8 +318,7 @@ public class RestMusicDataAPI {
long count = row.getLong(0);
if (count == 0) {
- resultMap.put("Exception", "Keyspace not found. Please make sure keyspace exists.");
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap();
} else if (count == 1) {
pQuery = new PreparedQueryObject();
pQuery.appendQueryString(
@@ -353,8 +336,7 @@ public class RestMusicDataAPI {
PreparedQueryObject queryObject = new PreparedQueryObject();
queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
- return new JsonResponse(MusicCore.nonKeyRelatedPut(queryObject, consistency), "", "")
- .toMap();
+ return new JsonResponse(MusicCore.nonKeyRelatedPut(queryObject, consistency)).toMap();
}
/**
@@ -391,18 +373,17 @@ public class RestMusicDataAPI {
required = true) @PathParam("tablename") String tablename,
@Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "createTable");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
String consistency = MusicUtil.EVENTUAL;
// for now this needs only eventual consistency
PreparedQueryObject queryObject = new PreparedQueryObject();
- boolean result = false;
// first read the information about the table fields
Map<String, String> fields = tableObj.getFields();
StringBuilder fieldsString = new StringBuilder("(vector_ts text,");
@@ -457,13 +438,16 @@ public class RestMusicDataAPI {
queryObject.appendQueryString(" WITH " + propertiesString);
queryObject.appendQueryString(";");
+ ResultType result = ResultType.FAILURE;
+
try {
result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
} catch (MusicServiceException ex) {
- return new JsonResponse(false, ex.getMessage(), "").toMap();
+ response.setStatus(400);
+ return new JsonResponse(result).toMap();
}
- return new JsonResponse(result, "", "").toMap();
+ return new JsonResponse(result).toMap();
}
/**
@@ -499,13 +483,13 @@ public class RestMusicDataAPI {
@ApiParam(value = "Field Name",
required = true) @PathParam("field") String fieldName,
@Context UriInfo info, @Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "createIndex");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty())
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty())
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
MultivaluedMap<String, String> rowParams = info.getQueryParameters();
String indexName = "";
if (rowParams.getFirst("index_name") != null)
@@ -513,8 +497,15 @@ public class RestMusicDataAPI {
PreparedQueryObject query = new PreparedQueryObject();
query.appendQueryString("Create index " + indexName + " if not exists on " + keyspace + "."
+ tablename + " (" + fieldName + ");");
- return new JsonResponse(MusicCore.nonKeyRelatedPut(query, "eventual"), "", "").toMap();
+
+ ResultType result = ResultType.FAILURE;
+ try {
+ result = MusicCore.nonKeyRelatedPut(query, "eventual");
+ } catch (MusicServiceException ex) {
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+ }
+ return new JsonResponse(result).toMap();
}
/**
@@ -550,33 +541,33 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context HttpServletResponse response) {
- Map<String, Object> resultMap = null;
+ Map<String, Object> authMap = null;
try {
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "insertIntoTable");
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
- ReturnType result = null;
+
Map<String, Object> valuesMap = insObj.getValues();
PreparedQueryObject queryObject = new PreparedQueryObject();
TableMetadata tableInfo = null;
try {
tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
- if(tableInfo == null)
- throw new MusicServiceException("Table name doesn't exists. Please check the table name.");
+ if(tableInfo == null) {
+ return new JsonResponse(ResultType.FAILURE)
+ .setError("Table name doesn't exists. Please check the table name.").toMap();
+ }
} catch (MusicServiceException e) {
- e.printStackTrace();
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put(ResultType.SYNTAXERROR.getResult(), e.getMessage());
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
StringBuilder fieldsString = new StringBuilder("(vector_ts,");
@@ -602,7 +593,6 @@ public class RestMusicDataAPI {
formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- //return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
}
valueString.append("?");
queryObject.addValue(formattedValue);
@@ -616,6 +606,11 @@ public class RestMusicDataAPI {
}
counter = counter + 1;
}
+
+ if(primaryKey == null || primaryKey.length() <= 0) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
+ return new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap();
+ }
queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " "
+ fieldsString + " VALUES " + valueString);
@@ -644,6 +639,7 @@ public class RestMusicDataAPI {
queryObject.appendQueryString(";");
+ ReturnType result = null;
String consistency = insObj.getConsistencyInfo().get("type");
try {
if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
@@ -660,13 +656,15 @@ public class RestMusicDataAPI {
result = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, primaryKey, queryObject, null);
}
- return (result != null) ? result.toMap()
- : new ReturnType(ResultType.FAILURE,
- "Null result - Please Contact admin").toMap();
} catch (Exception ex) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+ }
+
+ if (result==null) {
+ return new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap();
}
+ return new JsonResponse(result.getResult()).toMap();
}
/**
@@ -703,19 +701,19 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context UriInfo info, @Context HttpServletResponse response) {
- Map<String, Object> resultMap;
+ Map<String, Object> authMap;
try {
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "updateTable");
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
long startTime = System.currentTimeMillis();
String operationId = UUID.randomUUID().toString();// just for infoging
@@ -732,14 +730,12 @@ public class RestMusicDataAPI {
try {
tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
} catch (MusicServiceException e) {
- e.printStackTrace();
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- resultMap.put("Exception", e.getMessage());
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
if (tableInfo == null) {
- return new ReturnType(ResultType.FAILURE,
- "Table information not found. Please check input for table name= "
+ return new JsonResponse(ResultType.FAILURE)
+ .setError("Table information not found. Please check input for table name= "
+ keyspace + "." + tablename).toMap();
}
String vectorTs =
@@ -755,7 +751,6 @@ public class RestMusicDataAPI {
valueString = MusicUtil.convertToActualDataType(colType, valueObj);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- //return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
}
fieldValueString.append(entry.getKey() + "= ?");
queryObject.addValue(valueString);
@@ -791,12 +786,13 @@ public class RestMusicDataAPI {
try {
rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
if(rowId == null || rowId.primarKeyValue.isEmpty()) {
- resultMap.put(ResultType.SYNTAXERROR.getResult(), "Mandatory WHERE clause is missing. Please check the input request.");
- return resultMap;
+
+ return new JsonResponse(ResultType.FAILURE)
+ .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap();
}
} catch (MusicServiceException ex) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage());
- return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
queryObject.appendQueryString(
@@ -831,7 +827,7 @@ public class RestMusicDataAPI {
rowId.primarKeyValue, queryObject, conditionInfo);
} catch (MusicLockingException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
} else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
try {
@@ -839,7 +835,7 @@ public class RestMusicDataAPI {
queryObject, conditionInfo);
} catch (MusicLockingException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
}
long actualUpdateCompletionTime = System.currentTimeMillis();
@@ -856,9 +852,11 @@ public class RestMusicDataAPI {
timingString = timingString + lockManagementTime;
}
logger.info(EELFLoggerDelegate.applicationLogger, timingString);
- return (operationResult != null) ? operationResult.toMap()
- : new ReturnType(ResultType.FAILURE, "Null result - Please Contact admin")
- .toMap();
+
+ if (operationResult==null) {
+ return new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap();
+ }
+ return new JsonResponse(operationResult.getResult()).toMap();
}
/**
@@ -895,23 +893,21 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context UriInfo info, @Context HttpServletResponse response) {
- Map<String, Object> resultMap = null;
+ Map<String, Object> authMap = null;
try {
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "deleteFromTable");
} catch (Exception e) {
- resultMap.put("Exception", e.getMessage());
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
}
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
if(delObj == null) {
- resultMap.put("Exception", "Request body is missing. Please check your input data and retry.");
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap();
}
PreparedQueryObject queryObject = new PreparedQueryObject();
StringBuilder columnString = new StringBuilder();
@@ -932,7 +928,7 @@ public class RestMusicDataAPI {
try {
rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
} catch (MusicServiceException ex) {
- return new ReturnType(ResultType.FAILURE, ex.getMessage()).toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
String rowSpec = rowId.rowIdString.toString();
@@ -983,14 +979,13 @@ public class RestMusicDataAPI {
queryObject, conditionInfo);
}
} catch (MusicLockingException e) {
- resultMap.put("Exception", "Unable to perform Delete operation. Exception from music: "+e.getMessage());
- return resultMap;
+ return new JsonResponse(ResultType.FAILURE)
+ .setError("Unable to perform Delete operation. Exception from music").toMap();
}
- try {
- return operationResult.toMap();
- } catch (NullPointerException e) {
- return new ReturnType(ResultType.FAILURE, e.getMessage()).toMap();
+ if (operationResult==null) {
+ return new JsonResponse(ResultType.FAILURE).toMap();
}
+ return new JsonResponse(operationResult.getResult()).toMap();
}
/**
@@ -1025,22 +1020,22 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap =
+ Map<String, Object> authMap =
MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "dropTable");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
String consistency = "eventual";// for now this needs only eventual
// consistency
PreparedQueryObject query = new PreparedQueryObject();
query.appendQueryString("DROP TABLE " + keyspace + "." + tablename + ";");
try {
- return new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency), "", "").toMap();
+ return new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap();
} catch (MusicServiceException ex) {
- return new JsonResponse(false, ex.getMessage(), "").toMap();
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
}
@@ -1058,7 +1053,7 @@ public class RestMusicDataAPI {
@ApiOperation(value = "Select Critical", response = Map.class)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- public Map<String, HashMap<String, Object>> selectCritical(
+ public Map<String, Object> selectCritical(
@ApiParam(value = "Major Version",
required = true) @PathParam("version") String version,
@ApiParam(value = "Minor Version",
@@ -1078,18 +1073,14 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context UriInfo info, @Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+ Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "selectCritical");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
logger.error("Error while authentication... ");
- HashMap<String, Object> tempMap = new HashMap<>();
- tempMap.putAll(resultMap);
- Map<String, HashMap<String, Object>> results = new HashMap<>();
- results.put("Result", tempMap);
- return results;
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
String lockId = selObj.getConsistencyInfo().get("lockId");
@@ -1099,7 +1090,7 @@ public class RestMusicDataAPI {
try {
rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
} catch (MusicServiceException ex) {
- return MusicUtil.setErrorResponse(ex);
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
queryObject.appendQueryString(
"SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";");
@@ -1119,7 +1110,7 @@ public class RestMusicDataAPI {
results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject);
}
- return MusicCore.marshallResults(results);
+ return new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap();
}
/**
@@ -1132,9 +1123,9 @@ public class RestMusicDataAPI {
*/
@GET
@Path("/{keyspace}/tables/{tablename}/rows")
- @ApiOperation(value = "Select All or Select Specivic", response = Map.class)
+ @ApiOperation(value = "Select All or Select Specific", response = Map.class)
@Produces(MediaType.APPLICATION_JSON)
- public Map<String, HashMap<String, Object>> select(
+ public Map<String, Object> select(
@ApiParam(value = "Major Version",
required = true) @PathParam("version") String version,
@ApiParam(value = "Minor Version",
@@ -1153,18 +1144,14 @@ public class RestMusicDataAPI {
@ApiParam(value = "Table Name",
required = true) @PathParam("tablename") String tablename,
@Context UriInfo info, @Context HttpServletResponse response) throws Exception {
- Map<String, Object> resultMap =
+ Map<String, Object> authMap =
MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "select");
response.addHeader(xLatestVersion, MusicUtil.getVersion());
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
+ if (authMap.containsKey("aid"))
+ authMap.remove("aid");
+ if (!authMap.isEmpty()) {
logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- HashMap<String, Object> tempMap = new HashMap<>();
- tempMap.putAll(resultMap);
- Map<String, HashMap<String, Object>> results = new HashMap<>();
- results.put("Result", tempMap);
- return results;
+ return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
}
PreparedQueryObject queryObject = new PreparedQueryObject();
@@ -1176,16 +1163,16 @@ public class RestMusicDataAPI {
queryObject = selectSpecificQuery(version, minorVersion, patchVersion, aid, ns,
userId, password, keyspace, tablename, info, limit);
} catch (MusicServiceException ex) {
- return MusicUtil.setErrorResponse(ex);
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
}
try {
ResultSet results = MusicCore.get(queryObject);
- return MusicCore.marshallResults(results);
+ return new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap();
} catch (MusicServiceException ex) {
logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
- return MusicUtil.setErrorResponse(ex);
+ return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
}
}
diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
index e565e829..d871a507 100644
--- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
+++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
@@ -37,12 +37,15 @@ import javax.ws.rs.core.MediaType;
import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.eelf.logging.format.AppMessages;
+import org.onap.music.eelf.logging.format.ErrorSeverity;
+import org.onap.music.eelf.logging.format.ErrorTypes;
import org.onap.music.lockingservice.MusicLockState;
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.onap.music.response.jsonobjects.JsonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -85,15 +88,27 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockName);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"createLockReference");
- if (!resultMap.isEmpty()) {
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
return resultMap;
}
ResultType status = ResultType.SUCCESS;
String lockId = MusicCore.createLockReference(lockName);
- if (lockId == null) { status = ResultType.FAILURE; }
- return new JsonLockResponse(status).setLock(lockId).toMap();
+
+ if (lockId == null) {
+ status = ResultType.FAILURE;
+ response.setStatus(400);
+ }
+ return new JsonResponse(status).setLock(lockId).toMap();
}
/**
@@ -121,15 +136,30 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockId);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"accquireLock");
- if (!resultMap.isEmpty()) {
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
return resultMap;
}
- String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
- ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
- return new JsonLockResponse(lockStatus.getResult()).setLock(lockId)
- .setMessage(lockStatus.getMessage()).toMap();
+ try {
+ String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
+ ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
+ return new JsonResponse(lockStatus.getResult()).setLock(lockId)
+ .setMessage(lockStatus.getMessage()).toMap();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ resultMap.put("Exception","Unable to aquire lock");
+ response.setStatus(400);
+ return new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap();
+ }
}
@@ -151,14 +181,24 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockId);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"accquireLockWithLease");
- if (!resultMap.isEmpty()) {
- return resultMap;
+
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
+ response.setStatus(400);
+ return resultMap;
}
String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod());
- return new JsonLockResponse(lockLeaseStatus.getResult()).setLock(lockName)
+ return new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName)
.setMessage(lockLeaseStatus.getMessage())
.setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap();
}
@@ -181,9 +221,17 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockName);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"currentLockHolder");
- if (!resultMap.isEmpty()) {
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
return resultMap;
}
String who = MusicCore.whoseTurnIsIt(lockName);
@@ -192,8 +240,9 @@ public class RestMusicLocksAPI {
if ( who == null ) {
status = ResultType.FAILURE;
error = "There was a problem getting the lock holder";
+ response.setStatus(400);
}
- return new JsonLockResponse(status).setError(error)
+ return new JsonResponse(status).setError(error)
.setLock(lockName).setLockHolder(who).toMap();
}
@@ -214,14 +263,25 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockName);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"currentLockState");
- if (!resultMap.isEmpty()) {
+
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
+ response.setStatus(400);
return resultMap;
}
- MusicLockState mls = MusicCore.getMusicLockState(lockName);
+
+ MusicLockState mls = MusicCore.getMusicLockState(lockName);
Map<String,Object> returnMap = null;
- JsonLockResponse jsonResponse = new JsonLockResponse(ResultType.FAILURE).setLock(lockName);
+ JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName);
if(mls == null) {
jsonResponse.setError("");
jsonResponse.setMessage("No lock object created yet..");
@@ -230,7 +290,7 @@ public class RestMusicLocksAPI {
jsonResponse.setLockStatus(mls.getLockStatus());
jsonResponse.setLockHolder(mls.getLockHolder());
}
- return returnMap;
+ return jsonResponse.toMap();
}
/**
@@ -256,20 +316,33 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockId);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"unLock");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
+ response.setStatus(400);
+ return resultMap;
}
boolean voluntaryRelease = true;
MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease);
+ if(mls.getErrorMessage() != null) {
+ resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage());
+ return resultMap;
+ }
Map<String,Object> returnMap = null;
if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) {
- returnMap = new JsonLockResponse(ResultType.SUCCESS).setLock(lockId)
+ returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId)
.setLockStatus(mls.getLockStatus()).toMap();
}
if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) {
- returnMap = new JsonLockResponse(ResultType.FAILURE).setLock(lockId)
+ returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId)
.setLockStatus(mls.getLockStatus()).toMap();
}
return returnMap;
@@ -294,13 +367,22 @@ public class RestMusicLocksAPI {
required = true) @HeaderParam("password") String password,
@Context HttpServletResponse response) throws Exception{
response.addHeader(xLatestVersion,MusicUtil.getVersion());
- Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
+ Map<String, Object> resultMap = MusicCore.validateLock(lockName);
+ if (resultMap.containsKey("Exception")) {
+ return resultMap;
+ }
+ String keyspaceName = (String) resultMap.get("keyspace");
+ resultMap.remove("keyspace");
+ resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
"deleteLock");
- if (!resultMap.isEmpty()) {
- return resultMap;
+ if (resultMap.containsKey("aid"))
+ resultMap.remove("aid");
+ if (!resultMap.isEmpty()) {
+ response.setStatus(400);
+ return resultMap;
}
MusicCore.deleteLock(lockName);
- return new JsonLockResponse(ResultType.SUCCESS).toMap();
+ return new JsonResponse(ResultType.SUCCESS).toMap();
}
}
diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
index f0a32b5c..a5f2ac49 100644
--- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
+++ b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
@@ -33,6 +33,7 @@ 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 org.onap.music.main.ResultType;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -56,8 +57,7 @@ public class RestMusicVersionAPI {
@Produces(MediaType.APPLICATION_JSON)
public Map<String,Object> version(@Context HttpServletResponse response) {
logger.info("Replying to request for MUSIC version with MUSIC:" + MusicUtil.getVersion());
- JsonResponse jResponse = new JsonResponse(true,"","MUSIC:" + MusicUtil.getVersion());
response.addHeader("X-latestVersion",MusicUtil.getVersion());
- return jResponse.toMap();
+ return new JsonResponse(ResultType.SUCCESS).setMusicVersion("MUSIC:" + MusicUtil.getVersion()).toMap();
}
} \ No newline at end of file
diff --git a/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java b/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java
deleted file mode 100644
index cd5773dc..00000000
--- a/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * org.onap.music
- * ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ============LICENSE_END=============================================
- * ====================================================================
- */
-package org.onap.music.unittests;
-
-import static org.junit.Assert.*;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.music.lockingservice.MusicLockState;
-import org.onap.music.lockingservice.MusicLockState.LockStatus;
-import org.onap.music.main.ResultType;
-import org.onap.music.response.jsonobjects.JsonLockResponse;
-
-public class JsonLockResponseTest {
-
- JsonLockResponse response = new JsonLockResponse(ResultType.SUCCESS);
-
- @Test
- public void error1() {
- Boolean result = false;
- response.setError("");
- result = response.getError().equals("error1");
- assertFalse("Success",result);
- }
-
- @Test
- public void error() {
- Boolean result = false;
- response.setError("error1");
- result = response.getError().equals("error1");
- assertTrue("Success",result);
- }
-
- @Test
- public void lock1() {
- Boolean result = false;
- response.setLock("");
- result = response.getLock().equals("lock1");
- assertFalse("Success",result);
- }
-
- @Test
- public void lock() {
- Boolean result = false;
- response.setLock("lock1");
- result = response.getLock().equals("lock1");
- assertTrue("Success",result);
- }
-
- @Test
- public void status1() {
- Boolean result = false;
- response.setStatus(null);
- result = response.getStatus() == ResultType.SUCCESS;
- assertFalse("Success",result);
- }
-
- @Test
- public void status() {
- Boolean result = false;
- response.setStatus(ResultType.SUCCESS);
- result = response.getStatus() == ResultType.SUCCESS;
- assertTrue("Success",result);
- }
-
-
-
- @Test
- public void lockHolder1() {
- Boolean result = false;
- response.setLockHolder("");
- result = response.getLockHolder().equals("LockHolder");
- assertFalse("Success",result);
- }
-
- @Test
- public void lockHolder() {
- Boolean result = false;
- response.setLockHolder("LockHolder");
- result = response.getLockHolder().equals("LockHolder");
- assertTrue("Success",result);
- }
-
- @Test
- public void lockLease1() {
- Boolean result = false;
- response.setLockLease("");
- result = response.getLockLease().equals("lockLease");
- assertFalse("Success",result);
- }
-
- @Test
- public void lockLease() {
- Boolean result = false;
- response.setLockLease("lockLease");
- result = response.getLockLease().equals("lockLease");
- assertTrue("Success",result);
- }
-
- @Test
- public void lockStatus1() {
- Boolean result = false;
- response.setLockStatus(null);
- result = response.getLockStatus() == MusicLockState.LockStatus.LOCKED;
- assertFalse("Success",result);
- }
-
- @Test
- public void lockStatus() {
- Boolean result = false;
- response.setLockStatus(MusicLockState.LockStatus.LOCKED);
- result = response.getLockStatus() == MusicLockState.LockStatus.LOCKED;
- assertTrue("Success",result);
- }
-
- @Test
- public void message1() {
- Boolean result = false;
- response.setMessage("");
- result = response.getMessage().equals("message");
- assertFalse("Success",result);
- }
-
- @Test
- public void message() {
- Boolean result = false;
- response.setMessage("message");
- result = response.getMessage().equals("message");
- assertTrue("Success",result);
- }
-
- @Test
- public void map() {
- Boolean result = false;
- response.setMessage("message");
- response.setLockStatus(MusicLockState.LockStatus.LOCKED);
- response.setLockHolder("LockHolder");
- response.setLockLease("lockLease");
- response.setStatus(ResultType.SUCCESS);
- response.setLock("lock1");
- response.setError("error1");
- Map<String,Object> myMap = response.toMap();
- result = myMap.containsKey("status");
- System.out.println(response.toString());
- assertTrue("Success",result);
- }
-
- @Test
- public void map1() {
- Boolean result = false;
- response.setMessage(null);
- response.setLockStatus(null);
- response.setLockHolder(null);
- response.setLockLease(null);
- response.setStatus(null);
- response.setLock(null);
- response.setError(null);
- Map<String,Object> myMap = response.toMap();
- result = myMap.containsKey("error");
- System.out.println(result);
- assertFalse("Success",result);
- }
-
-
-
-
-}
diff --git a/src/test/java/org/onap/music/unittests/JsonResponseTest.java b/src/test/java/org/onap/music/unittests/JsonResponseTest.java
index 55e5965e..9da10638 100644
--- a/src/test/java/org/onap/music/unittests/JsonResponseTest.java
+++ b/src/test/java/org/onap/music/unittests/JsonResponseTest.java
@@ -25,6 +25,7 @@ package org.onap.music.unittests;
import static org.junit.Assert.*;
import java.util.Map;
import org.junit.Test;
+import org.onap.music.main.ResultType;
import org.onap.music.response.jsonobjects.JsonResponse;
public class JsonResponseTest {
@@ -33,28 +34,22 @@ public class JsonResponseTest {
@Test
public void testJsonResponseBooleanStringString() {
- result = new JsonResponse(true,"error","version");
+ result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("version");
assertEquals("error",result.getError());
}
@Test
- public void testJsonResponse() {
- result = new JsonResponse();
- assertFalse(result.getStatus());
- }
-
- @Test
public void testStatus() {
- result = new JsonResponse();
- result.setStatus(true);
- assertTrue(result.getStatus());
- result = new JsonResponse(false,"error","version");
- assertFalse(result.getStatus());
+ result = new JsonResponse(ResultType.SUCCESS);
+ result.setStatus(ResultType.SUCCESS);
+ assertEquals(ResultType.SUCCESS, result.getStatus());
+ result = new JsonResponse(ResultType.FAILURE).setError("error").setMusicVersion("version");
+ assertEquals(ResultType.FAILURE, result.getStatus());
}
@Test
public void testError() {
- result = new JsonResponse();
+ result = new JsonResponse(ResultType.FAILURE);
result.setError("error");
assertTrue(result.getError().equals("error"));
result.setError("");
@@ -63,21 +58,26 @@ public class JsonResponseTest {
@Test
public void testVersion() {
- result = new JsonResponse();
- result.setVersion("version");
- assertTrue(result.getVersion().equals("version"));
- result.setVersion("");
- assertFalse(result.getVersion().equals("version"));
+ result = new JsonResponse(ResultType.SUCCESS);
+ result.setMusicVersion("version");
+ assertTrue(result.getMusicVersion().equals("version"));
+ result.setMusicVersion("");
+ assertFalse(result.getMusicVersion().equals("version"));
}
@Test
public void testToMap() {
- result = new JsonResponse(true,"error","version");
+ result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("1.0");
Map<String,Object> myMap = result.toMap();
assertTrue(myMap.containsKey("status"));
- result = new JsonResponse(false,"","");
+ assertEquals(ResultType.SUCCESS, myMap.get("status"));
+ assertEquals("error", myMap.get("error"));
+ assertEquals("1.0", myMap.get("version"));
+
+ result = new JsonResponse(ResultType.FAILURE);
myMap = result.toMap();
assertTrue(myMap.containsKey("status"));
+ assertEquals(ResultType.FAILURE, myMap.get("status"));
}
}
diff --git a/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/src/test/java/org/onap/music/unittests/MusicUtilTest.java
index 47edc1e3..b117c330 100644
--- a/src/test/java/org/onap/music/unittests/MusicUtilTest.java
+++ b/src/test/java/org/onap/music/unittests/MusicUtilTest.java
@@ -204,14 +204,4 @@ public class MusicUtilTest {
assertTrue(result.contains("value"));
}
- @Test
- public void testSetErrorResponse() {
- Map<String,Object> myMap = new HashMap<>();
- myMap.put("name","tom");
- Map<String,HashMap<String,Object>> result = MusicUtil.setErrorResponse(new MusicServiceException("This is the error"));
- Map<String,Object> testMap = (Map<String,Object>) result.get("result");
- Map<String,Object> error = (Map<String,Object>) testMap.get("error");
- assertTrue(error.containsKey("error-description"));
- }
-
}
diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java
index c571085a..876c78b1 100644
--- a/src/test/java/org/onap/music/unittests/TestMusicCore.java
+++ b/src/test/java/org/onap/music/unittests/TestMusicCore.java
@@ -24,6 +24,8 @@ package org.onap.music.unittests;
import static org.junit.Assert.*;
import static org.onap.music.main.MusicCore.mDstoreHandle;
import static org.onap.music.main.MusicCore.mLockHandle;
+
+import org.apache.zookeeper.KeeperException.NoNodeException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -97,7 +99,7 @@ public class TestMusicCore {
}
@Test
- public void testAcquireLockifisMyTurnTrue() {
+ public void testAcquireLockifisMyTurnTrue() throws MusicLockingException {
Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1");
assertEquals(lock.getResult(), ResultType.SUCCESS);
@@ -105,7 +107,7 @@ public class TestMusicCore {
}
@Test
- public void testAcquireLockifisMyTurnFalse() {
+ public void testAcquireLockifisMyTurnFalse() throws MusicLockingException {
Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
ReturnType lock = MusicCore.acquireLock("ks1.ts1", "id1");
assertEquals(lock.getResult(), ResultType.FAILURE);
@@ -113,7 +115,7 @@ public class TestMusicCore {
}
@Test
- public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() {
+ public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() throws MusicLockingException {
Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1");
assertEquals(lock.getResult(), ResultType.SUCCESS);
@@ -143,7 +145,7 @@ public class TestMusicCore {
}
@Test
- public void testAcquireLockifLockRefDoesntExist() {
+ public void testAcquireLockifLockRefDoesntExist() throws MusicLockingException {
Mockito.when(mLockHandle.lockIdExists("bs1")).thenReturn(false);
ReturnType lock = MusicCore.acquireLock("ks1.ts1", "bs1");
assertEquals(lock.getResult(), ResultType.FAILURE);
@@ -230,14 +232,14 @@ public class TestMusicCore {
}
@Test
- public void testDestroyLockRef() {
+ public void testDestroyLockRef() throws NoNodeException {
Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
MusicCore.destroyLockRef("id1");
Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1");
}
@Test
- public void testreleaseLockwithvoluntaryReleaseTrue() {
+ public void testreleaseLockwithvoluntaryReleaseTrue() throws NoNodeException {
MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
MusicLockState musicLockState1 = MusicCore.releaseLock("id1", true);
@@ -246,7 +248,7 @@ public class TestMusicCore {
}
@Test
- public void testreleaseLockwithvoluntaryReleaseFalse() {
+ public void testreleaseLockwithvoluntaryReleaseFalse() throws NoNodeException {
MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
MusicLockState musicLockState1 = MusicCore.releaseLock("id1", false);
@@ -355,8 +357,8 @@ public class TestMusicCore {
session = Mockito.mock(Session.class);
Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "consistency")).thenReturn(true);
- Boolean result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency");
- assertTrue(result);
+ ResultType result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency");
+ assertEquals(ResultType.SUCCESS, result);
Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "consistency");
}
diff --git a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
index 823badaa..d327d0f0 100644
--- a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
+++ b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
@@ -78,14 +78,14 @@ public class TestMusicCoreIntegration {
@Test
public void Test1_SetUp() throws MusicServiceException, MusicQueryException {
MusicCore.mLockHandle = new MusicLockingService();
- boolean result = false;
+ ResultType result = ResultType.FAILURE;
testObject = new PreparedQueryObject();
testObject.appendQueryString(CassandraCQL.createKeySpace);
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString(CassandraCQL.createTableEmployees);
result = MusicCore.nonKeyRelatedPut(testObject, MusicUtil.EVENTUAL);
- assertTrue(result);
+ assertEquals(ResultType.SUCCESS, result);
}
@Test
diff --git a/src/test/java/org/onap/music/unittests/TestRestMusicData.java b/src/test/java/org/onap/music/unittests/TestRestMusicData.java
index e4d06f70..435b196c 100644
--- a/src/test/java/org/onap/music/unittests/TestRestMusicData.java
+++ b/src/test/java/org/onap/music/unittests/TestRestMusicData.java
@@ -49,6 +49,7 @@ import org.onap.music.lockingservice.MusicLockingService;
import org.onap.music.main.CachingUtil;
import org.onap.music.main.MusicCore;
import org.onap.music.main.MusicUtil;
+import org.onap.music.main.ResultType;
import org.onap.music.rest.RestMusicAdminAPI;
import org.onap.music.rest.RestMusicDataAPI;
import org.onap.music.rest.RestMusicLocksAPI;
@@ -181,7 +182,7 @@ public class TestRestMusicData {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = data.createKeySpace("1", "1", "1", null, appName, userId,
password, jsonKeyspace, keyspaceName, http);
- assertEquals(uuid.toString(), resultMap.get("aid"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -201,7 +202,7 @@ public class TestRestMusicData {
"TestUser1", password, jsonKeyspace, keyspaceName, http);
System.out.println("#######status is " + resultMap.get("Exception"));
assertEquals("Couldn't create keyspace. Please make sure all the information is correct.",
- resultMap.get("Exception"));
+ resultMap.get("error"));
}
@Test
@@ -223,7 +224,7 @@ public class TestRestMusicData {
Map<String, Object> resultMap = data.createTable("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
jsonTable, keyspaceName, tableName, http);
- assertEquals("SUCCESS", resultMap.get("status"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -242,7 +243,7 @@ public class TestRestMusicData {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, userId, password, jsonInsert, keyspaceName, tableName, http);
- assertEquals("Success", resultMap.get("result"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -262,7 +263,7 @@ public class TestRestMusicData {
Map<String, Object> resultMap = data.insertIntoTable("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
jsonInsert, keyspaceName, tableName, http);
- assertEquals("Success", resultMap.get("result"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -282,7 +283,7 @@ public class TestRestMusicData {
Mockito.when(info.getQueryParameters()).thenReturn(row);
Map<String, Object> resultMap = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
userId, password, jsonUpdate, keyspaceName, tableName, info, http);
- assertEquals("Success", resultMap.get("result"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -295,9 +296,9 @@ public class TestRestMusicData {
jsonSelect.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
- Map<String, HashMap<String, Object>> resultMap = data.select("1", "1", "1",
+ Map<String, Object> resultMap = data.select("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, keyspaceName, tableName, info, http);
- assertEquals("2500", resultMap.get("row 0").get("emp_salary").toString());
+ assertEquals("2500", ((HashMap<String,HashMap<String,Object>>) resultMap.get("result")).get("row 0").get("emp_salary").toString());
}
@Test
@@ -310,10 +311,10 @@ public class TestRestMusicData {
jsonInsert.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
- Map<String, HashMap<String, Object>> resultMap = data.selectCritical("1", "1", "1",
+ Map<String, Object> resultMap = data.selectCritical("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, jsonInsert, keyspaceName, tableName,
info, http);
- assertEquals("2500", resultMap.get("row 0").get("emp_salary").toString());
+ assertEquals("2500", ((HashMap<String,HashMap<String,Object>>) resultMap.get("result")).get("row 0").get("emp_salary").toString());
}
@Test
@@ -329,7 +330,7 @@ public class TestRestMusicData {
Map<String, Object> resultMap = data.deleteFromTable("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
jsonDelete, keyspaceName, tableName, info, http);
- assertEquals("Success", resultMap.get("result"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -342,7 +343,7 @@ public class TestRestMusicData {
Map<String, Object> resultMap = data.dropTable("1", "1", "1",
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
jsonTable, keyspaceName, tableName, http);
- assertEquals("SUCCESS", resultMap.get("status"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -360,7 +361,7 @@ public class TestRestMusicData {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, userId, password, jsonKeyspace, keyspaceName, http);
- assertEquals("SUCCESS", resultMap.get("status"));
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
@@ -417,34 +418,34 @@ public class TestRestMusicData {
@SuppressWarnings("unchecked")
Map<String, Object> resultMap1 = (Map<String, Object>) resultMap.get("lock");
lockId = (String) resultMap1.get("lock");
- assertEquals("SUCCESS", resultMap.get("status").toString());
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
public void Test4_accquireLock() throws Exception {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = lock.accquireLock(lockId, uuid.toString(), appName, null, null, http);
- assertEquals("SUCCESS", resultMap.get("status").toString());
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
public void Test5_currentLockHolder() throws Exception {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = lock.currentLockHolder(lockName, uuid.toString(), appName, null, null, http);
- assertEquals("SUCCESS", resultMap.get("status").toString());
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
public void Test7_unLock() throws Exception {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = lock.unLock(lockId, uuid.toString(), appName, null, null, http);
- assertEquals("SUCCESS", resultMap.get("status").toString());
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
@Test
public void Test8_delete() throws Exception {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Map<String, Object> resultMap = lock.deleteLock(lockName, uuid.toString(), appName, null, null, http);
- assertEquals("SUCCESS", resultMap.get("status").toString());
+ assertEquals(ResultType.SUCCESS, resultMap.get("status"));
}
} \ No newline at end of file
diff --git a/version.properties b/version.properties
index 632fc91b..e1384772 100644
--- a/version.properties
+++ b/version.properties
@@ -4,7 +4,7 @@
major=2
minor=4
-patch=15
+patch=18
base_version=${major}.${minor}.${patch}