Changes Listed below:
[music.git] / src / main / java / org / onap / music / rest / RestMusicDataAPI.java
index 3065635..5fa955e 100755 (executable)
@@ -4,30 +4,31 @@
  * ===================================================================
  *  Copyright (c) 2017 AT&T Intellectual Property
  * ===================================================================
+ *  Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
  *  You may obtain a copy of the License at
- * 
+ *
  *     http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
- * 
+ *
  * ============LICENSE_END=============================================
  * ====================================================================
  */
+
 package org.onap.music.rest;
 
 import java.nio.ByteBuffer;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
-import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
@@ -38,7 +39,6 @@ import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
@@ -48,6 +48,10 @@ import javax.ws.rs.core.UriInfo;
 
 import org.apache.commons.lang3.StringUtils;
 import org.mindrot.jbcrypt.BCrypt;
+import org.onap.music.authentication.CachingUtil;
+import org.onap.music.authentication.MusicAAFAuthentication;
+import org.onap.music.authentication.MusicAuthenticator;
+import org.onap.music.authentication.MusicAuthenticator.Operation;
 import org.onap.music.datastore.PreparedQueryObject;
 import org.onap.music.datastore.jsonobjects.JsonDelete;
 import org.onap.music.datastore.jsonobjects.JsonInsert;
@@ -56,13 +60,14 @@ import org.onap.music.datastore.jsonobjects.JsonTable;
 import org.onap.music.datastore.jsonobjects.JsonUpdate;
 import org.onap.music.eelf.logging.EELFLoggerDelegate;
 import org.onap.music.exceptions.MusicLockingException;
+import org.onap.music.exceptions.MusicQueryException;
 import org.onap.music.eelf.logging.format.AppMessages;
 import org.onap.music.eelf.logging.format.ErrorSeverity;
 import org.onap.music.eelf.logging.format.ErrorTypes;
 import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.CachingUtil;
 import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicCore.Condition;
+import org.onap.music.datastore.Condition;
+import org.onap.music.datastore.MusicDataStoreHandle;
 import org.onap.music.main.MusicUtil;
 import org.onap.music.main.ResultType;
 import org.onap.music.main.ReturnType;
@@ -76,6 +81,8 @@ import com.datastax.driver.core.TableMetadata;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponses;
+import io.swagger.annotations.ApiResponse;
 
 /* Version 2 Class */
 //@Path("/v{version: [0-9]+}/keyspaces")
@@ -90,7 +97,7 @@ public class RestMusicDataAPI {
      * (e.g. if the full version is 1.24.5, X-minorVersion = "24") - Is optional for the client on
      * request; however, this header should be provided if the client needs to take advantage of
      * MINOR incremented version functionality - Is mandatory for the server on response
-     * 
+     *
      *** X-patchVersion *** - Used only to communicate a PATCH version in a response for
      * troubleshooting purposes only, and will not be provided by the client on request - This will
      * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version
@@ -110,13 +117,16 @@ public class RestMusicDataAPI {
     private static final String XPATCHVERSION = "X-patchVersion";
     private static final String NS = "ns";
     private static final String VERSION = "v2";
-    
+    private MusicAuthenticator authenticator = new MusicAAFAuthentication();
+    // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist.    
+    private static final boolean KEYSPACE_ACTIVE = false;
+
     private class RowIdentifier {
         public String primarKeyValue;
         public StringBuilder rowIdString;
         @SuppressWarnings("unused")
-        public PreparedQueryObject queryObject;// the string with all the row
-                                               // identifiers separated by AND
+        public PreparedQueryObject queryObject; // the string with all the row
+                                                // identifiers separated by AND
 
         public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString,
                         PreparedQueryObject queryObject) {
@@ -129,7 +139,7 @@ public class RestMusicDataAPI {
 
     /**
      * Create Keyspace REST
-     * 
+     *
      * @param kspObject
      * @param keyspaceName
      * @return
@@ -137,131 +147,142 @@ public class RestMusicDataAPI {
      */
     @POST
     @Path("/{name}")
-    @ApiOperation(value = "Create Keyspace", response = String.class)
+    @ApiOperation(value = "Create Keyspace", response = String.class,hidden = true)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    //public Map<String, Object> createKeySpace(
     public Response createKeySpace(
-                    @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
-                    @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
-                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
-                    @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
-                    JsonKeySpace kspObject,
-                    @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-        
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-            response.status(Status.UNAUTHORIZED);
-            return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
-        }
-        if(kspObject == null || kspObject.getReplicationInfo() == null) {
-            authMap.put(ResultType.EXCEPTION.getResult(), ResultType.BODYMISSING.getResult());
-            response.status(Status.BAD_REQUEST);
-            return response.entity(authMap).build();
-        }
-
-
-        try {
-            authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
-                            "createKeySpace");
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-            response.status(Status.BAD_REQUEST);
-            return response.entity(new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap()).build();
-        }
-        String newAid = null;
-        if (!authMap.isEmpty()) {
-            if (authMap.containsKey("aid")) {
-                newAid = (String) authMap.get("aid");
-            } else {
-                logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-                response.status(Status.UNAUTHORIZED);
-                return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
-            }
-        }
-
-        String consistency = MusicUtil.EVENTUAL;// for now this needs only
-                                                // eventual consistency
-
-        PreparedQueryObject queryObject = new PreparedQueryObject();
-        long start = System.currentTimeMillis();
-        Map<String, Object> replicationInfo = kspObject.getReplicationInfo();
-        String repString = null;
+        @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
+        @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
+        @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
+        @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
+        @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
+        @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
+        JsonKeySpace kspObject,
+        @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) {
         try {
-            repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}";
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-            
-        }
-        queryObject.appendQueryString(
-                        "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString);
-        if (kspObject.getDurabilityOfWrites() != null) {
-            queryObject.appendQueryString(
-                            " AND durable_writes = " + kspObject.getDurabilityOfWrites());
-        }
-
-        queryObject.appendQueryString(";");
-        long end = System.currentTimeMillis();
-        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.info(EELFLoggerDelegate.applicationLogger, "result = " + result);
-        } catch ( MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
-            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build();
-        }
+            ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+            EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) ");
+            logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName);
+            if ( MusicUtil.isKeyspaceActive() ) {
+                logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName);
+                Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
+                String userId = userCredentials.get(MusicUtil.USERID);
+                String password = userCredentials.get(MusicUtil.PASSWORD);
+                Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
+                if (!authMap.isEmpty()) {
+                    logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
+                    response.status(Status.UNAUTHORIZED);
+                    return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+                }
         
-        try {
-            queryObject = new PreparedQueryObject();
-            queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
-                            + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
-            MusicCore.nonKeyRelatedPut(queryObject, consistency);
-            queryObject = new PreparedQueryObject();
-            queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
-                                + " to '" + userId + "'");
-            queryObject.appendQueryString(";");
-            MusicCore.nonKeyRelatedPut(queryObject, consistency);
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
-        }
+                if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_KEYSPACE)) {
+                    return response.status(Status.UNAUTHORIZED)
+                            .entity(new JsonResponse(ResultType.FAILURE)
+                                    .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                                    .toMap()).build();
+                }  
         
-        try {
-            boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns));
-            String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
-            queryObject = new PreparedQueryObject();
-            queryObject.appendQueryString(
-                        "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
-                                        + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
-            queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-            CachingUtil.updateMusicCache(keyspaceName, ns);
-            CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd);
-            MusicCore.eventualPut(queryObject);
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
-            return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
+                String consistency = MusicUtil.EVENTUAL;// for now this needs only
+                                                        // eventual consistency
+        
+                if(kspObject == null || kspObject.getReplicationInfo() == null) {
+                    response.status(Status.BAD_REQUEST);
+                    return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build();
+                }
+                PreparedQueryObject queryObject = new PreparedQueryObject();
+                if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && kspObject.getConsistencyInfo().get("consistency") != null) {
+                    if (MusicUtil.isValidConsistency(kspObject.getConsistencyInfo().get("consistency"))) { 
+                        queryObject.setConsistency(kspObject.getConsistencyInfo().get("consistency")); 
+                    } else {
+                        return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR)
+                            .setError("Invalid Consistency type").toMap()).build();
+                    }
+                }
+                long start = System.currentTimeMillis();
+                Map<String, Object> replicationInfo = kspObject.getReplicationInfo();
+                String repString = null;
+                try {
+                    repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}";
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA  ,ErrorSeverity
+                        .CRITICAL, ErrorTypes.DATAERROR, e);
+        
+                }
+                queryObject.appendQueryString(
+                                "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString);
+                if (kspObject.getDurabilityOfWrites() != null) {
+                    queryObject.appendQueryString(
+                                    " AND durable_writes = " + kspObject.getDurabilityOfWrites());
+                }
+        
+                queryObject.appendQueryString(";");
+                long end = System.currentTimeMillis();
+                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.info(EELFLoggerDelegate.applicationLogger, "result = " + result);
+                } catch ( MusicServiceException ex) {
+                    logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
+                        .WARN, ErrorTypes.MUSICSERVICEERROR, ex);
+                    return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build();
+                }
+        
+                try {
+                    queryObject = new PreparedQueryObject();
+                    queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
+                                    + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
+                    MusicCore.nonKeyRelatedPut(queryObject, consistency);
+                    queryObject = new PreparedQueryObject();
+                    queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
+                                        + " to '" + userId + "'");
+                    queryObject.appendQueryString(";");
+                    MusicCore.nonKeyRelatedPut(queryObject, consistency);
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity
+                        .WARN, ErrorTypes.MUSICSERVICEERROR, e);
+                }
+        
+                try {
+                    boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns));
+                    String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
+                    queryObject = new PreparedQueryObject();
+                    queryObject.appendQueryString(
+                                "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+                                                + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), aid));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
+                    queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
+                    CachingUtil.updateMusicCache(keyspaceName, ns);
+                    CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd);
+                    MusicCore.eventualPut(queryObject);
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity
+                        .WARN, ErrorTypes.MUSICSERVICEERROR, e);
+                    return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
+                }
+        
+                return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
+            } else {
+                String vError = "Keyspace Creation has been turned off. Contact DBA to create the keyspace or set keyspace.active to true.";
+                logger.info(EELFLoggerDelegate.applicationLogger,vError);
+                logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+                return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build();
+            }
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
         }
         
-        return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
     }
 
     /**
-     * 
+     *
      * @param kspObject
      * @param keyspaceName
      * @return
@@ -269,299 +290,312 @@ public class RestMusicDataAPI {
      */
     @DELETE
     @Path("/{name}")
-    @ApiOperation(value = "Delete Keyspace", response = String.class)
+    @ApiOperation(value = "Delete Keyspace", response = String.class,hidden=true)
     @Produces(MediaType.APPLICATION_JSON)
-    //public Map<String, Object> dropKeySpace(
     public Response dropKeySpace(
-                    @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
-                    @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
-                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
-                    @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
-                    @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            return response.status(Status.UNAUTHORIZED).entity(authMap).build();
-        }
-
-        String consistency = MusicUtil.EVENTUAL;// for now this needs only
-                                                // eventual
-        // consistency
-        String appName = CachingUtil.getAppName(keyspaceName);
-        String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName);
-        PreparedQueryObject pQuery = new PreparedQueryObject();
-        pQuery.appendQueryString(
-                        "select  count(*) as count from admin.keyspace_master where application_name=? allow filtering;");
-        pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
-        Row row = MusicCore.get(pQuery).one();
-        long count = row.getLong(0);
-
-        if (count == 0) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build();
-        // Admin Functions:
-        } else if (count == 1) {
-            pQuery = new PreparedQueryObject();
-            pQuery.appendQueryString(
-                    "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;");
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
-                    MusicUtil.DEFAULTKEYSPACENAME));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
-            MusicCore.nonKeyRelatedPut(pQuery, consistency);
-        } else {
-            pQuery = new PreparedQueryObject();
-            pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
-            MusicCore.nonKeyRelatedPut(pQuery, consistency);
-        }
-
-        PreparedQueryObject queryObject = new PreparedQueryObject();
-        queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
-        ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
-        if ( result.equals(ResultType.FAILURE) ) {
-            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build();
+        @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
+        @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
+        @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
+        @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
+        @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
+        @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
+        @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception {
+        try {
+            ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+            EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) ");
+            logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName);
+            if (MusicUtil.isKeyspaceActive()) {
+                if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DROP_KEYSPACE)) {
+                    return response.status(Status.UNAUTHORIZED)
+                        .entity(new JsonResponse(ResultType.FAILURE)
+                        .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                        .toMap()).build();
+                }
+                String consistency = MusicUtil.EVENTUAL;// for now this needs only
+                                                        // eventual
+                // consistency
+                String appName = CachingUtil.getAppName(keyspaceName);
+                String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName);
+                PreparedQueryObject pQuery = new PreparedQueryObject();
+                pQuery.appendQueryString(
+                                "select  count(*) as count from admin.keyspace_master where application_name=? allow filtering;");
+                pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
+                Row row = MusicCore.get(pQuery).one();
+                long count = row.getLong(0);
+        
+                if (count == 0) {
+                    logger.error(EELFLoggerDelegate.errorLogger,"Keyspace not found. Please make sure keyspace exists.", AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+                    return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build();
+                // Admin Functions:
+                } else if (count == 1) {
+                    pQuery = new PreparedQueryObject();
+                    pQuery.appendQueryString(
+                            "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;");
+                    pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
+                            MusicUtil.DEFAULTKEYSPACENAME));
+                    pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
+                    MusicCore.nonKeyRelatedPut(pQuery, consistency);
+                } else {
+                    pQuery = new PreparedQueryObject();
+                    pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
+                    pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
+                    MusicCore.nonKeyRelatedPut(pQuery, consistency);
+                }
+        
+                PreparedQueryObject queryObject = new PreparedQueryObject();
+                queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
+                ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
+                if ( result.equals(ResultType.FAILURE) ) {
+                    return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build();
+                }
+                return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build();
+            } else {
+                String vError = "Keyspace deletion has been turned off. Contact DBA to delete the keyspace or set keyspace.active to true.";
+                logger.info(EELFLoggerDelegate.applicationLogger,vError);
+                logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+                return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build();
+            }
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
         }
-        return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build();
     }
 
     /**
-     * 
+     *
      * @param tableObj
      * @param version
      * @param keyspace
      * @param tablename
      * @param headers
      * @return
-     * @throws Exception
+     * @throws Exception -
      */
     @POST
-    @Path("/{keyspace}/tables/{tablename}")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}")
     @ApiOperation(value = "Create Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    //public Map<String, Object> createTable(
+    @ApiResponses(value={
+        @ApiResponse(code= 400, message = "Will return JSON response with message"),
+        @ApiResponse(code= 401, message = "Unautorized User")
+    })
     public Response createTable(
-                    @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
-                    @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
-                    @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
-                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
-                     JsonTable tableObj,
-                    @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
-                    @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                        aid, "createTable");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-            return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
-        }
-        String consistency = MusicUtil.EVENTUAL;
-        // for now this needs only eventual consistency
-
-        String primaryKey = null;
-        String partitionKey = tableObj.getPartitionKey();
-        String clusterKey = tableObj.getClusteringKey();
-        String filteringKey = tableObj.getFilteringKey();
-        if(filteringKey != null) {
-            clusterKey = clusterKey + "," + filteringKey;
-        }
-        primaryKey = tableObj.getPrimaryKey(); // get primaryKey if available
+        @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
+        @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
+        @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
+        @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
+        @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
+        @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
+        JsonTable tableObj,
+        @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
+        @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception {
+        try {
+            ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+            if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                        .setError("One or more path parameters are not set, please check and try again."
+                            + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'")
+                            .toMap()).build();
+            }
+            EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+            if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_TABLE)) {
+                return response.status(Status.UNAUTHORIZED)
+                        .entity(new JsonResponse(ResultType.FAILURE)
+                                .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                                .toMap()).build();
+            }       
+            String consistency = MusicUtil.EVENTUAL;
+            // for now this needs only eventual consistency
+            String primaryKey = null;
+            String partitionKey = tableObj.getPartitionKey();
+            String clusterKey = tableObj.getClusteringKey();
+            String filteringKey = tableObj.getFilteringKey();
+            if(filteringKey != null) {
+                clusterKey = clusterKey + "," + filteringKey;
+            }
+            primaryKey = tableObj.getPrimaryKey(); // get primaryKey if available
 
-        PreparedQueryObject queryObject = new PreparedQueryObject();
-        // first read the information about the table fields
-        Map<String, String> fields = tableObj.getFields();
-        StringBuilder fieldsString = new StringBuilder("(vector_ts text,");
-        int counter = 0;
-        for (Map.Entry<String, String> entry : fields.entrySet()) {
-            if (entry.getKey().equals("PRIMARY KEY")) {
-                primaryKey = entry.getValue(); // replaces primaryKey
-                primaryKey.trim();
-            } else {
-                  if (counter == 0 )  fieldsString.append("" + entry.getKey() + " " + entry.getValue() + "");
-                  else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + "");             
+            PreparedQueryObject queryObject = new PreparedQueryObject();
+            // first read the information about the table fields
+            Map<String, String> fields = tableObj.getFields();
+            if (fields == null) {
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                        .setError("Create Table Error: No fields in request").toMap()).build();
             }
 
-          if (counter != (fields.size() - 1) ) {
-                 
-                 //logger.info("cjc2 field="+entry.getValue()+"counter=" + counter+"fieldsize-1="+(fields.size() -1) + ",");
-                 counter = counter + 1; 
-          } else {
-         //logger.info("cjc3 field="+entry.getValue()+"counter=" + counter+"fieldsize="+fields.size() + ",");
-               if((primaryKey != null) && (partitionKey == null)) {
-                  primaryKey.trim();
-                  int count1 = StringUtils.countMatches(primaryKey, ')');
-                  int count2 = StringUtils.countMatches(primaryKey, '(');
-                  if (count1 != count2) {
-                        return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
-                             .setError("Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey)
-                                   .toMap()).build();
-                  }
-
-                if ( primaryKey.indexOf('(') == -1  || ( count2 == 1 && (primaryKey.lastIndexOf(")") +1) ==  primaryKey.length() ) )
-                  {
-                             if (primaryKey.contains(",") ) {
-                             partitionKey= primaryKey.substring(0,primaryKey.indexOf(","));
-                             partitionKey=partitionKey.replaceAll("[\\(]+","");
-                             clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1);  // make sure index
-                             clusterKey=clusterKey.replaceAll("[)]+", "");
-                             } else {
-                         partitionKey=primaryKey;
-                         partitionKey=partitionKey.replaceAll("[\\)]+","");
-                             partitionKey=partitionKey.replaceAll("[\\(]+","");
-                         clusterKey="";
-                    }
-                } else {   // not null and has ) before the last char
-                           partitionKey= primaryKey.substring(0,primaryKey.indexOf(')'));
-                               partitionKey=partitionKey.replaceAll("[\\(]+","");
-                               partitionKey.trim();
-                               clusterKey= primaryKey.substring(primaryKey.indexOf(')'));
-                               clusterKey=clusterKey.replaceAll("[\\(]+","");
-                               clusterKey=clusterKey.replaceAll("[\\)]+","");
-                               clusterKey.trim();
-                               if (clusterKey.indexOf(",") == 0) clusterKey=clusterKey.substring(1);
-                                  clusterKey.trim();
-                               if (clusterKey.equals(",") ) clusterKey=""; // print error if needed    ( ... ),)
-
-              } 
-
-              if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
-                    && (partitionKey.equalsIgnoreCase(clusterKey) ||
-                      clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) )
-               {
-               logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey );
-                       return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
-                            "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")  of"
-                                    + " primary key=" + primaryKey)
-                               .toMap()).build();
-
-               }
-
-            if (partitionKey.isEmpty() )  primaryKey="";
-            else  if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey  + ")";
-            else  primaryKey=" (" + partitionKey + ")," + clusterKey;
-
-            //if (primaryKey != null) fieldsString.append("" + entry.getKey() + " (" + primaryKey + " )");
-            if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
-
-      } // end of length > 0
-              else {
-                 if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
-                        && (partitionKey.equalsIgnoreCase(clusterKey) ||
-                          clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) )
-                   {
-                     logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey);
-                     return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
+            StringBuilder fieldsString = new StringBuilder("(vector_ts text,");
+            int counter = 0;
+            for (Map.Entry<String, String> entry : fields.entrySet()) {
+                if (entry.getKey().equals("PRIMARY KEY")) {
+                    primaryKey = entry.getValue(); // replaces primaryKey
+                    primaryKey = primaryKey.trim();
+                } else {
+                    if (counter == 0 )  fieldsString.append("" + entry.getKey() + " " + entry.getValue() + "");
+                    else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + "");
+                }
+
+                if (counter != (fields.size() - 1) ) {
+                    counter = counter + 1; 
+                } else {
+            
+                    if((primaryKey != null) && (partitionKey == null)) {
+                        primaryKey = primaryKey.trim();
+                        int count1 = StringUtils.countMatches(primaryKey, ')');
+                        int count2 = StringUtils.countMatches(primaryKey, '(');
+                        if (count1 != count2) {
+                            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                                .setError("Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey)
+                                .toMap()).build();
+                        }
+
+                        if ( primaryKey.indexOf('(') == -1  || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) ==  primaryKey.length() ) ) {
+                            if (primaryKey.contains(",") ) {
+                                partitionKey= primaryKey.substring(0,primaryKey.indexOf(','));
+                                partitionKey=partitionKey.replaceAll("[\\(]+","");
+                                clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1);  // make sure index
+                                clusterKey=clusterKey.replaceAll("[)]+", "");
+                            } else {
+                                partitionKey=primaryKey;
+                                partitionKey=partitionKey.replaceAll("[\\)]+","");
+                                partitionKey=partitionKey.replaceAll("[\\(]+","");
+                                clusterKey="";
+                            }
+                        } else {   // not null and has ) before the last char
+                            partitionKey= primaryKey.substring(0,primaryKey.indexOf(')'));
+                            partitionKey=partitionKey.replaceAll("[\\(]+","");
+                            partitionKey = partitionKey.trim();
+                            clusterKey= primaryKey.substring(primaryKey.indexOf(')'));
+                            clusterKey=clusterKey.replaceAll("[\\(]+","");
+                            clusterKey=clusterKey.replaceAll("[\\)]+","");
+                            clusterKey = clusterKey.trim();
+                            if (clusterKey.indexOf(',') == 0) {
+                                clusterKey=clusterKey.substring(1);
+                            }
+                            clusterKey = clusterKey.trim();
+                            if (clusterKey.equals(",") ) clusterKey=""; // print error if needed    ( ... ),)
+                        }
+
+                        if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
+                            && (partitionKey.equalsIgnoreCase(clusterKey) ||
+                            clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) {
+                            logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey );
+                            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
+                                "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")  of"
+                                + " primary key=" + primaryKey)
+                                .toMap()).build();
+
+                        }
+
+                        if (partitionKey.isEmpty() )  primaryKey="";
+                        else  if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey  + ")";
+                        else  primaryKey=" (" + partitionKey + ")," + clusterKey;
+
+                
+                        if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
+
+                    } else { // end of length > 0
+                    
+                        if (!(partitionKey.isEmpty() || clusterKey.isEmpty())
+                            && (partitionKey.equalsIgnoreCase(clusterKey) ||
+                            clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) {
+                            logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey);
+                            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(
                                 "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")")
                                 .toMap()).build();
-                }
+                        }
 
-                if (partitionKey.isEmpty() )  primaryKey="";
-                else  if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey  + ")";
-                else  primaryKey=" (" + partitionKey + ")," + clusterKey;
+                        if (partitionKey.isEmpty() )  primaryKey="";
+                        else  if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey  + ")";
+                        else  primaryKey=" (" + partitionKey + ")," + clusterKey;
 
-                //if (primaryKey != null) fieldsString.append("" + entry.getKey() + " (" + primaryKey + " )");
-                if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
+                        if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
+                    }
+                    fieldsString.append(")");
+
+                } // end of last field check
+
+            } // end of for each
+            // information about the name-value style properties
+            Map<String, Object> propertiesMap = tableObj.getProperties();
+            StringBuilder propertiesString = new StringBuilder();
+            if (propertiesMap != null) {
+                counter = 0;
+                for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) {
+                    Object ot = entry.getValue();
+                    String value = ot + "";
+                    if (ot instanceof String) {
+                        value = "'" + value + "'";
+                    } else if (ot instanceof Map) {
+                        @SuppressWarnings("unchecked")
+                        Map<String, Object> otMap = (Map<String, Object>) ot;
+                        value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}";
+                    }
+
+                    propertiesString.append(entry.getKey() + "=" + value + "");
+                    if (counter != propertiesMap.size() - 1)
+                        propertiesString.append(" AND ");
+
+                    counter = counter + 1;
+                }
             }
-      fieldsString.append(")");
-
-     } // end of last field check
-
-    } // end of for each
-        // information about the name-value style properties
-        Map<String, Object> propertiesMap = tableObj.getProperties();
-        StringBuilder propertiesString = new StringBuilder();
-        if (propertiesMap != null) {
-            counter = 0;
-            for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) {
-                Object ot = entry.getValue();
-                String value = ot + "";
-                if (ot instanceof String) {
-                    value = "'" + value + "'";
-                } else if (ot instanceof Map) {
-                    @SuppressWarnings("unchecked")
-                    Map<String, Object> otMap = (Map<String, Object>) ot;
-                    value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}";
+
+            String clusteringOrder = tableObj.getClusteringOrder();
+
+            if (clusteringOrder != null && !(clusteringOrder.isEmpty())) {
+                String[] arrayClusterOrder = clusteringOrder.split("[,]+");
+
+                for (int i = 0; i < arrayClusterOrder.length; i++) {
+                    String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+");
+                    if ( (clusterS.length ==2)  && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) {
+                        continue;
+                    } else {
+                        return response.status(Status.BAD_REQUEST)
+                        .entity(new JsonResponse(ResultType.FAILURE)
+                        .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname  order; please correct clusteringOrder:"+ clusteringOrder+".")
+                        .toMap()).build();
+                    }
+                    // add validation for column names in cluster key
                 }
 
-                propertiesString.append(entry.getKey() + "=" + value + "");
-                if (counter != propertiesMap.size() - 1)
-                    propertiesString.append(" AND ");
+                if (!(clusterKey.isEmpty())) {
+                    clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")";
+                    //cjc check if propertiesString.length() >0 instead propertiesMap
+                    if (propertiesMap != null) {
+                        propertiesString.append(" AND  "+ clusteringOrder);
+                    } else {
+                        propertiesString.append(clusteringOrder);
+                    }
+                } else {
+                    logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty ");
+                }
+            } //if non empty
 
-                counter = counter + 1;
-            }
-        }
+            queryObject.appendQueryString(
+                "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString);
 
-    String clusteringOrder = tableObj.getClusteringOrder();
-
-    if (clusteringOrder != null && !(clusteringOrder.isEmpty())) {
-       String[] arrayClusterOrder = clusteringOrder.split("[,]+");
-
-       for (int i = 0; i < arrayClusterOrder.length; i++) 
-          {
-           String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+");
-                if ( (clusterS.length ==2)  && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) continue;
-                else {
-                  //logger.error("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname  order; please correct clusteringOrder:\"+ clusteringOrder+\".\"", " valid clustering order is ASC or DESC; please correct clusteringOrder:"+ clusteringOrder+".");
-                    // logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
-                      //       ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
-                             return response.status(Status.BAD_REQUEST)
-                                     .entity(new JsonResponse(ResultType.FAILURE)
-                                             .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname  order; please correct clusteringOrder:"+ clusteringOrder+".")
-                                                       .toMap()).build();
-               }
-               // add validation for column names in cluster key
-       }
-
-       if (!(clusterKey.isEmpty())) 
-       {
-                clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")";
-                //cjc check if propertiesString.length() >0 instead propertiesMap
-                if (propertiesMap != null)  propertiesString.append(" AND  "+ clusteringOrder);
-                 else propertiesString.append(clusteringOrder);
-       } else {
-                logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty ");
-       }
-    } //if non empty
-       
-       queryObject.appendQueryString(
-                  "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString);
-
-
-    if (propertiesString != null &&  propertiesString.length()>0 )
-        queryObject.appendQueryString(" WITH " + propertiesString);
-        queryObject.appendQueryString(";");
-        ResultType result = ResultType.FAILURE;
-        try {
-          //logger.info("cjc query="+queryObject.getQuery());
-            result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
-        } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR);
-            response.status(Status.BAD_REQUEST);
-            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
-        }
-        if ( result.equals(ResultType.FAILURE) ) {
-            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build();
+
+            if (propertiesString != null &&  propertiesString.length()>0 )
+                queryObject.appendQueryString(" WITH " + propertiesString);
+            queryObject.appendQueryString(";");
+            ResultType result = ResultType.FAILURE;
+            try {
+                result = MusicCore.createTable(keyspace, tablename, queryObject, consistency);
+            } catch (MusicServiceException ex) {
+                logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR);
+                response.status(Status.BAD_REQUEST);
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
+            }
+            if ( result.equals(ResultType.FAILURE) ) {
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build();
+            }
+            return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build();
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
         }
-        return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename + " Created under keyspace " + keyspace).toMap()).build();
     }
 
     /**
-     * 
+     *
      * @param keyspace
      * @param tablename
      * @param fieldName
@@ -569,33 +603,35 @@ public class RestMusicDataAPI {
      * @throws Exception
      */
     @POST
-    @Path("/{keyspace}/tables/{tablename}/index/{field}")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/index/{field: .*}")
     @ApiOperation(value = "Create Index", response = String.class)
     @Produces(MediaType.APPLICATION_JSON)
     public Response createIndex(
                     @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename,
                     @ApiParam(value = "Field Name",required = true) @PathParam("field") String fieldName,
                     @Context UriInfo info) throws Exception {
+        try {
         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("one or more path parameters are not set, please check and try again")
+                .toMap()).build();
+        }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_INDEX)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
+        } 
 
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "createIndex");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-            response.status(Status.UNAUTHORIZED);
-            return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
-        }
         MultivaluedMap<String, String> rowParams = info.getQueryParameters();
         String indexName = "";
         if (rowParams.getFirst("index_name") != null)
@@ -603,12 +639,13 @@ public class RestMusicDataAPI {
         PreparedQueryObject query = new PreparedQueryObject();
         query.appendQueryString("Create index if not exists " + indexName + "  on " + keyspace + "."
                         + tablename + " (" + fieldName + ");");
-        
+
         ResultType result = ResultType.FAILURE;
         try {
             result = MusicCore.nonKeyRelatedPut(query, "eventual");
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
+                .CRITICAL, ErrorTypes.GENERALSERVICEERROR, ex);
             response.status(Status.BAD_REQUEST);
             return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
@@ -617,10 +654,13 @@ public class RestMusicDataAPI {
         } else {
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build();
         }
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param insObj
      * @param keyspace
      * @param tablename
@@ -628,7 +668,7 @@ public class RestMusicDataAPI {
      * @throws Exception
      */
     @POST
-    @Path("/{keyspace}/tables/{tablename}/rows")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
     @ApiOperation(value = "Insert Into Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
@@ -636,7 +676,7 @@ public class RestMusicDataAPI {
                     @ApiParam(value = "Major Version",required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     JsonInsert insObj,
@@ -644,37 +684,30 @@ public class RestMusicDataAPI {
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename) {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = null;
-        
         try {
-            authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                          aid, "insertIntoTable");
-        } catch (Exception e) {
-          logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-          return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
+        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("one or more path parameters are not set, please check and try again")
+                .toMap()).build();
         }
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
-            return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
         }
 
-        Map<String, Object> valuesMap = insObj.getValues();
         PreparedQueryObject queryObject = new PreparedQueryObject();
         TableMetadata tableInfo = null;
         try {
-            tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
+            tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
             if(tableInfo == null) {
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build();
             }
         } catch (MusicServiceException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
         }
         String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
@@ -683,9 +716,14 @@ public class RestMusicDataAPI {
                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
         StringBuilder valueString = new StringBuilder("(" + "?" + ",");
         queryObject.addValue(vectorTs);
+        
+        Map<String, Object> valuesMap = insObj.getValues();
+        if (valuesMap==null) {
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                    .setError("Nothing to insert. No values provided in request.").toMap()).build();
+        }
         int counter = 0;
         String primaryKey = "";
-        Map<String, byte[]> objectMap = insObj.getObjectMap();
         for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
             fieldsString.append("" + entry.getKey());
             Object valueObj = entry.getValue();
@@ -697,18 +735,19 @@ public class RestMusicDataAPI {
             try {
                 colType = tableInfo.getColumn(entry.getKey()).getType();
             } catch(NullPointerException ex) {
-                logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey(), AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+                logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey
+                    (), AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex);
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
             }
 
             Object formattedValue = null;
             try {
-              formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
+                formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
             } catch (Exception e) {
-              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+              logger.error(EELFLoggerDelegate.errorLogger,e);
           }
             valueString.append("?");
-            
+
             queryObject.addValue(formattedValue);
 
             if (counter == valuesMap.size() - 1) {
@@ -720,49 +759,46 @@ public class RestMusicDataAPI {
             }
             counter = counter + 1;
         }
-        
+
         //blobs..
+        Map<String, byte[]> objectMap = insObj.getObjectMap();
         if(objectMap != null) {
-        for (Map.Entry<String, byte[]> entry : objectMap.entrySet()) {
-               if(counter > 0) {
-                       fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ",");
-                       valueString.replace(valueString.length()-1, valueString.length(), ",");
-               }
-            fieldsString.append("" + entry.getKey());
-            byte[] valueObj = entry.getValue();
-            if (primaryKeyName.equals(entry.getKey())) {
-                primaryKey = entry.getValue() + "";
-                primaryKey = primaryKey.replace("'", "''");
-            }
+            for (Map.Entry<String, byte[]> entry : objectMap.entrySet()) {
+                if(counter > 0) {
+                    fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ",");
+                    valueString.replace(valueString.length()-1, valueString.length(), ",");
+                }
+                fieldsString.append("" + entry.getKey());
+                byte[] valueObj = entry.getValue();
+                if (primaryKeyName.equals(entry.getKey())) {
+                    primaryKey = entry.getValue() + "";
+                    primaryKey = primaryKey.replace("'", "''");
+                }
 
-            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
+                DataType colType = tableInfo.getColumn(entry.getKey()).getType();
 
-            ByteBuffer formattedValue = null;
-            
-            if(colType.toString().toLowerCase().contains("blob"))
-               formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
-            
-            valueString.append("?");
-            
-            queryObject.addValue(formattedValue);
-            counter = counter + 1;
-            /*if (counter == valuesMap.size() - 1) {
-                fieldsString.append(")");
-                valueString.append(")");
-            } else {*/
+                ByteBuffer formattedValue = null;
+
+                if(colType.toString().toLowerCase().contains("blob"))
+                    formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
+
+                valueString.append("?");
+
+                queryObject.addValue(formattedValue);
+                counter = counter + 1;
                 fieldsString.append(",");
                 valueString.append(",");
-            //}
-        } }
-        
+            } 
+        }
+
         if(primaryKey == null || primaryKey.length() <= 0) {
             logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap()).build();
         }
 
         fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")");
-               valueString.replace(valueString.length()-1, valueString.length(), ")");
-               
+        valueString.replace(valueString.length()-1, valueString.length(), ")");
+
         queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " "
                         + fieldsString + " VALUES " + valueString);
 
@@ -792,6 +828,13 @@ public class RestMusicDataAPI {
 
         ReturnType result = null;
         String consistency = insObj.getConsistencyInfo().get("type");
+        if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && insObj.getConsistencyInfo().get("consistency") != null) {
+            if(MusicUtil.isValidConsistency(insObj.getConsistencyInfo().get("consistency")))
+                queryObject.setConsistency(insObj.getConsistencyInfo().get("consistency"));
+            else
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
+        }
+        queryObject.setOperation("insert");
         try {
             if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
                 result = MusicCore.eventualPut(queryObject);
@@ -805,36 +848,41 @@ public class RestMusicDataAPI {
                 }
                 result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null);
             } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
-                result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null);
 
-            }
-            else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
-                result = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, primaryKey, queryObject, null);
+                result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null);
 
             }
         } catch (Exception ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
+                .WARN, ErrorTypes.MUSICSERVICEERROR, ex);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
-        
+
         if (result==null) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
+        }else if(result.getResult() == ResultType.FAILURE) {
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result.getResult()).setError(result.getMessage()).toMap()).build();
         }
         return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build();
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param insObj
      * @param keyspace
      * @param tablename
      * @param info
      * @return
+     * @throws MusicServiceException 
+     * @throws MusicQueryException 
      * @throws Exception
      */
     @PUT
-    @Path("/{keyspace}/tables/{tablename}/rows")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
     @ApiOperation(value = "Update Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
@@ -845,7 +893,7 @@ public class RestMusicDataAPI {
                                     required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
                                     required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",
                                     required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
@@ -854,30 +902,27 @@ public class RestMusicDataAPI {
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info) {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap;
+                    @Context UriInfo info) throws MusicQueryException, MusicServiceException {
         try {
-            authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                          aid, "updateTable");
-        } catch (Exception e) {
-              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-              return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
-        }
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-              return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                    .setError("one or more path parameters are not set, please check and try again")
+                    .toMap()).build();
         }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.UPDATE_TABLE)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
+        }
+
         long startTime = System.currentTimeMillis();
-        String operationId = UUID.randomUUID().toString();// just for infoging
-                                                          // purposes.
+        String operationId = UUID.randomUUID().toString();  // just for infoging
+                                                            // purposes.
         String consistency = updateObj.getConsistencyInfo().get("type");
+
         logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency
                         + " update-" + operationId + "-------------------------");
         // obtain the field value pairs of the update
@@ -887,19 +932,19 @@ public class RestMusicDataAPI {
 
         TableMetadata tableInfo;
         try {
-            tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
+            tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
         } catch (MusicServiceException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes
+                .GENERALSERVICEERROR, e);
               return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
         }
         if (tableInfo == null) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
-                            .setError("Table information not found. Please check input for table name= "
-                                            + keyspace + "." + tablename).toMap()).build();
+            logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+tablename, AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("Table information not found. Please check input for table name= "
+                + keyspace + "." + tablename).toMap()).build();
         }
-        String vectorTs =
-                        String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
+        String vectorTs = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
         StringBuilder fieldValueString = new StringBuilder("vector_ts=?,");
         queryObject.addValue(vectorTs);
         int counter = 0;
@@ -909,14 +954,14 @@ public class RestMusicDataAPI {
             try {
                 colType = tableInfo.getColumn(entry.getKey()).getType();
             } catch(NullPointerException ex) {
-                logger.error(EELFLoggerDelegate.errorLogger, "Invalid column name : "+entry.getKey());
+                logger.error(EELFLoggerDelegate.errorLogger, ex, "Invalid column name : "+entry.getKey(), ex);
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
             }
             Object valueString = null;
             try {
-              valueString = MusicUtil.convertToActualDataType(colType, valueObj);
+                valueString = MusicUtil.convertToActualDataType(colType, valueObj);
             } catch (Exception e) {
-              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+              logger.error(EELFLoggerDelegate.errorLogger,e);
             }
             fieldValueString.append(entry.getKey() + "= ?");
             queryObject.addValue(valueString);
@@ -929,7 +974,6 @@ public class RestMusicDataAPI {
 
         queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " ");
         if ((ttl != null) && (timestamp != null)) {
-
             logger.info("both there");
             queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?");
             queryObject.addValue(Integer.parseInt(ttl));
@@ -956,7 +1000,8 @@ public class RestMusicDataAPI {
                         .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();
             }
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes
+                .GENERALSERVICEERROR, ex);
               return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
 
@@ -967,18 +1012,25 @@ public class RestMusicDataAPI {
         Condition conditionInfo;
         if (updateObj.getConditions() == null)
             conditionInfo = null;
-        else {// to avoid parsing repeatedly, just send the select query to
-              // obtain row
+        else {
+            // to avoid parsing repeatedly, just send the select query to obtain row
             PreparedQueryObject selectQuery = new PreparedQueryObject();
             selectQuery.appendQueryString("SELECT *  FROM " + keyspace + "." + tablename + " WHERE "
-                            + rowId.rowIdString + ";");
+                + rowId.rowIdString + ";");
             selectQuery.addValue(rowId.primarKeyValue);
-            conditionInfo = new MusicCore.Condition(updateObj.getConditions(), selectQuery);
+            conditionInfo = new Condition(updateObj.getConditions(), selectQuery);
         }
 
         ReturnType operationResult = null;
         long jsonParseCompletionTime = System.currentTimeMillis();
 
+        if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && updateObj.getConsistencyInfo().get("consistency") != null) {
+            if(MusicUtil.isValidConsistency(updateObj.getConsistencyInfo().get("consistency")))
+                queryObject.setConsistency(updateObj.getConsistencyInfo().get("consistency"));
+            else
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
+        }
+        queryObject.setOperation("update");
         if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
             operationResult = MusicCore.eventualPut(queryObject);
         else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
@@ -994,20 +1046,23 @@ public class RestMusicDataAPI {
         } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) {
             // this function is mainly for the benchmarks
             try {
-              operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename,
-                              rowId.primarKeyValue, queryObject, conditionInfo);
+                operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename,
+                    rowId.primarKeyValue, queryObject, conditionInfo);
             } catch (MusicLockingException e) {
-                logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
-                  return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
+                logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN,
+                    ErrorTypes.GENERALSERVICEERROR, e);
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
             }
         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
             try {
-              operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
-                              queryObject, conditionInfo);
+                operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
+                    queryObject, conditionInfo);
             } catch (MusicLockingException e) {
-                logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+                logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e);
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
             }
+        }else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
+            operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue);
         }
         long actualUpdateCompletionTime = System.currentTimeMillis();
 
@@ -1023,10 +1078,10 @@ public class RestMusicDataAPI {
             timingString = timingString + lockManagementTime;
         }
         logger.info(EELFLoggerDelegate.applicationLogger, timingString);
-        
+
         if (operationResult==null) {
             logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
-              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
         }
         if ( operationResult.getResult() == ResultType.SUCCESS ) {
             return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build();
@@ -1034,20 +1089,24 @@ public class RestMusicDataAPI {
             logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(operationResult.getResult()).setError(operationResult.getMessage()).toMap()).build();
         }
-        
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param delObj
      * @param keyspace
      * @param tablename
      * @param info
      * @return
+     * @throws MusicServiceException 
+     * @throws MusicQueryException 
      * @throws Exception
      */
     @DELETE
-    @Path("/{keyspace}/tables/{tablename}/rows")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
     @ApiOperation(value = "Delete From table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
@@ -1058,7 +1117,7 @@ public class RestMusicDataAPI {
                                     required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
                                     required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",
                                     required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
@@ -1067,35 +1126,31 @@ public class RestMusicDataAPI {
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info) {
-        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = null;
+                    @Context UriInfo info) throws MusicQueryException, MusicServiceException {
         try {
-            authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                            aid, "deleteFromTable");
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-            return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
-        }
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-              return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
-        }
+        ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                    .setError("one or more path parameters are not set, please check and try again")
+                    .toMap()).build();
+        }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DELETE_FROM_TABLE)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
+        }
         if(delObj == null) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA  ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
-              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build();
+            logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA  ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build();
         }
         PreparedQueryObject queryObject = new PreparedQueryObject();
         StringBuilder columnString = new StringBuilder();
 
         int counter = 0;
-        ArrayList<String> columnList = delObj.getColumns();
+        List<String> columnList = delObj.getColumns();
         if (columnList != null) {
             for (String column : columnList) {
                 columnString.append(column);
@@ -1110,7 +1165,8 @@ public class RestMusicDataAPI {
         try {
             rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes
+                .GENERALSERVICEERROR, ex);
               return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
         String rowSpec = rowId.rowIdString.toString();
@@ -1131,20 +1187,31 @@ public class RestMusicDataAPI {
         }
         // get the conditional, if any
         Condition conditionInfo;
-        if (delObj.getConditions() == null)
+        if (delObj.getConditions() == null) {
             conditionInfo = null;
-        else {// to avoid parsing repeatedly, just send the select query to
-              // obtain row
+        } else {
+            // to avoid parsing repeatedly, just send the select query to
+            // obtain row
             PreparedQueryObject selectQuery = new PreparedQueryObject();
             selectQuery.appendQueryString("SELECT *  FROM " + keyspace + "." + tablename + " WHERE "
                             + rowId.rowIdString + ";");
             selectQuery.addValue(rowId.primarKeyValue);
-            conditionInfo = new MusicCore.Condition(delObj.getConditions(), selectQuery);
+            conditionInfo = new Condition(delObj.getConditions(), selectQuery);
         }
 
         String consistency = delObj.getConsistencyInfo().get("type");
 
+
+        if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && delObj.getConsistencyInfo().get("consistency")!=null) {
+
+            if(MusicUtil.isValidConsistency(delObj.getConsistencyInfo().get("consistency")))
+                queryObject.setConsistency(delObj.getConsistencyInfo().get("consistency"));
+            else
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build();
+        }
+
         ReturnType operationResult = null;
+        queryObject.setOperation("delete");
         try {
             if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
                 operationResult = MusicCore.eventualPut(queryObject);
@@ -1161,37 +1228,39 @@ public class RestMusicDataAPI {
             } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
                     operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
                                     queryObject, conditionInfo);
-            }
-            else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
-                    operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue,
-                                    queryObject, conditionInfo);
+            } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
+                
+                operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue);
             }
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
-              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+            logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
                     .setError("Unable to perform Delete operation. Exception from music").toMap()).build();
         }
         if (operationResult==null) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build();
         }
         if (operationResult.getResult().equals(ResultType.SUCCESS)) {
             return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build();
         } else {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
-              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build();
+            logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build();
+        }
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
         }
     }
 
     /**
-     * 
+     *
      * @param tabObj
      * @param keyspace
      * @param tablename
      * @throws Exception
      */
     @DELETE
-    @Path("/{keyspace}/tables/{tablename}")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}")
     @ApiOperation(value = "Drop Table", response = String.class)
     @Produces(MediaType.APPLICATION_JSON)
     public Response dropTable(
@@ -1201,7 +1270,7 @@ public class RestMusicDataAPI {
                                     required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
                                     required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",
                                     required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
@@ -1209,19 +1278,21 @@ public class RestMusicDataAPI {
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename) throws Exception {
+        try {
         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap =
-                        MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "dropTable");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-            return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("one or more path parameters are not set, please check and try again")
+                .toMap()).build();
         }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DROP_TABLE)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
+        }
+
         String consistency = "eventual";// for now this needs only eventual
                                         // consistency
         PreparedQueryObject query = new PreparedQueryObject();
@@ -1229,14 +1300,17 @@ public class RestMusicDataAPI {
         try {
             return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build();
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes
+                .GENERALSERVICEERROR);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
-
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param selObj
      * @param keyspace
      * @param tablename
@@ -1244,7 +1318,7 @@ public class RestMusicDataAPI {
      * @return
      */
     @PUT
-    @Path("/{keyspace}/tables/{tablename}/rows/criticalget")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/rows/criticalget")
     @ApiOperation(value = "Select Critical", response = Map.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
@@ -1255,7 +1329,7 @@ public class RestMusicDataAPI {
                                     required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
                                     required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
+                    @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
                     @ApiParam(value = "Application namespace",
                                     required = true) @HeaderParam(NS) String ns,
                     @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
@@ -1265,18 +1339,21 @@ public class RestMusicDataAPI {
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
                     @Context UriInfo info) throws Exception {
+        try {
         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Error while authentication... ", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-              return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("one or more path parameters are not set, please check and try again")
+                .toMap()).build();
+        }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT_CRITICAL)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
         }
+
         String lockId = selObj.getConsistencyInfo().get("lockId");
 
         PreparedQueryObject queryObject = new PreparedQueryObject();
@@ -1285,42 +1362,44 @@ public class RestMusicDataAPI {
         try {
             rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes
+                .GENERALSERVICEERROR, ex);
               return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
         queryObject.appendQueryString(
-                        "SELECT *  FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";");
+            "SELECT *  FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";");
 
         ResultSet results = null;
 
         String consistency = selObj.getConsistencyInfo().get("type");
-
+        try {
         if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
             if(lockId == null) {
                 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
-                        + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
+                    + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock "
-                        + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
+                    + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build();
             }
-            results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,
-                            lockId);
+            results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,lockId);
         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
             results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject);
         }
-        
-        else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
-            results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject);
+        }catch(Exception ex) {
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
+        
         if(results!=null && results.getAvailableWithoutFetching() >0) {
-               return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build();
+            return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build();
         }
         return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build();
 
-        
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param keyspace
      * @param tablename
      * @param info
@@ -1328,38 +1407,40 @@ public class RestMusicDataAPI {
      * @throws Exception
      */
     @GET
-    @Path("/{keyspace}/tables/{tablename}/rows")
+    @Path("/{keyspace: .*}/tables/{tablename: .*}/rows")
     @ApiOperation(value = "Select All or Select Specific", response = Map.class)
     @Produces(MediaType.APPLICATION_JSON)
     public Response select(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
-                    @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
-                    @ApiParam(value = "Application namespace",
-                                    required = true) @HeaderParam(NS) String ns,
-                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
-                    @ApiParam(value = "Keyspace Name",
-                                    required = true) @PathParam("keyspace") String keyspace,
-                    @ApiParam(value = "Table Name",
-                                    required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info) throws Exception {
+            @ApiParam(value = "Major Version",
+                            required = true) @PathParam("version") String version,
+            @ApiParam(value = "Minor Version",
+                            required = false) @HeaderParam(XMINORVERSION) String minorVersion,
+            @ApiParam(value = "Patch Version",
+                            required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
+            @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid,
+            @ApiParam(value = "Application namespace",
+                            required = true) @HeaderParam(NS) String ns,
+            @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
+            @ApiParam(value = "Keyspace Name",
+                            required = true) @PathParam("keyspace") String keyspace,
+            @ApiParam(value = "Table Name",
+                            required = true) @PathParam("tablename") String tablename,
+            @Context UriInfo info) throws Exception {
+        try { 
         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
-               Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
-               String userId = userCredentials.get(MusicUtil.USERID);
-               String password = userCredentials.get(MusicUtil.PASSWORD);
-        Map<String, Object> authMap =
-                        MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "select");
-        if (authMap.containsKey("aid"))
-            authMap.remove("aid");
-        if (!authMap.isEmpty()) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-            return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build();
+        if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                .setError("one or more path parameters are not set, please check and try again")
+                .toMap()).build();
+        }
+        EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) ");
+        if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT)) {
+            return response.status(Status.UNAUTHORIZED)
+                    .entity(new JsonResponse(ResultType.FAILURE)
+                            .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
+                            .toMap()).build();
         }
+
         PreparedQueryObject queryObject = new PreparedQueryObject();
 
         if (info.getQueryParameters().isEmpty())// select all
@@ -1367,10 +1448,10 @@ public class RestMusicDataAPI {
         else {
             int limit = -1; // do not limit the number of results
             try {
-                queryObject = selectSpecificQuery(VERSION, minorVersion, patchVersion, aid, ns,
-                                userId, password, keyspace, tablename, info, limit);
+                queryObject = selectSpecificQuery(keyspace, tablename, info, limit);
             } catch (MusicServiceException ex) {
-                logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+                logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN,
+                    ErrorTypes.GENERALSERVICEERROR, ex);
                 return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
             }
         }
@@ -1378,18 +1459,21 @@ public class RestMusicDataAPI {
         try {
             ResultSet results = MusicCore.get(queryObject);
             if(results.getAvailableWithoutFetching() >0) {
-               return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build();
+                return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build();
             }
-            return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build();
+            return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build();
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.ERROR,
+                ErrorTypes.MUSICSERVICEERROR, ex);
             return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
-
+        } finally {
+            EELFLoggerDelegate.mdcRemove("keyspace");
+        }
     }
 
     /**
-     * 
+     *
      * @param keyspace
      * @param tablename
      * @param info
@@ -1397,9 +1481,8 @@ public class RestMusicDataAPI {
      * @return
      * @throws MusicServiceException
      */
-    public PreparedQueryObject selectSpecificQuery(String version, String minorVersion,
-                    String patchVersion, String aid, String ns, String userId, String password,
-                    String keyspace, String tablename, UriInfo info, int limit)
+    public PreparedQueryObject selectSpecificQuery(String keyspace,
+            String tablename, UriInfo info, int limit)
                     throws MusicServiceException {
 
         PreparedQueryObject queryObject = new PreparedQueryObject();
@@ -1419,7 +1502,7 @@ public class RestMusicDataAPI {
     }
 
     /**
-     * 
+     *
      * @param keyspace
      * @param tablename
      * @param rowParams
@@ -1432,7 +1515,7 @@ public class RestMusicDataAPI {
                     throws MusicServiceException {
         StringBuilder rowSpec = new StringBuilder();
         int counter = 0;
-        TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
+        TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
         if (tableInfo == null) {
             logger.error(EELFLoggerDelegate.errorLogger,
                             "Table information not found. Please check input for table name= "
@@ -1449,10 +1532,10 @@ public class RestMusicDataAPI {
             DataType colType = null;
             Object formattedValue = null;
             try {
-              colType = tableInfo.getColumn(entry.getKey()).getType();
-              formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
+                colType = tableInfo.getColumn(entry.getKey()).getType();
+                formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
             } catch (Exception e) {
-              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+                logger.error(EELFLoggerDelegate.errorLogger,e);
             }
             if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey()))
             primaryKey.append(indValue);