aboutsummaryrefslogtreecommitdiffstats
path: root/src/main
diff options
context:
space:
mode:
authorThomas Nelson Jr (arthurdent3) tn1381@att.com <tn1381@att.com>2018-03-13 20:10:04 -0400
committerThomas Nelson Jr (arthurdent3) tn1381@att.com <tn1381@att.com>2018-03-13 20:10:04 -0400
commit3c86680e532b959bd637b6c093b3916ae5bcee11 (patch)
tree4e4f5eaed5f15c063a84b55f76ad629de95ea8ef /src/main
parented47d0c5d004b1ce099090100dda6dc1d963782c (diff)
Docker update and POM fix
Update the docker for cassandra to change ownership of imported files. Update the POM to fix bug Numerous bug fixes fro Logging and Error reporting. Change-Id: I518807f9796734134341ebefd109219050a84b51 Issue-ID: MUSIC-56, MUSIC-57, MUSIC-58 Signed-off-by: Thomas Nelson Jr (arthurdent3) tn1381@att.com <tn1381@att.com>
Diffstat (limited to 'src/main')
-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
14 files changed, 573 insertions, 530 deletions
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