Move string literal to left of string comparison
[music.git] / src / main / java / org / onap / music / rest / RestMusicDataAPI.java
index bcdb8dd..f0c1663 100755 (executable)
@@ -1,27 +1,32 @@
 /*
- * ============LICENSE_START========================================== org.onap.music
- * =================================================================== Copyright (c) 2017 AT&T
- * Intellectual Property ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ *  Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
  * 
- * http://www.apache.org/licenses/LICENSE-2.0
+ *     http://www.apache.org/licenses/LICENSE-2.0
  * 
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
  * 
  * ============LICENSE_END=============================================
  * ====================================================================
  */
 package org.onap.music.rest;
 
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
-import java.util.HashMap;
 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;
@@ -33,9 +38,16 @@ 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;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
 import javax.ws.rs.core.UriInfo;
+
+import org.apache.commons.lang3.StringUtils;
+import org.mindrot.jbcrypt.BCrypt;
 import org.onap.music.datastore.PreparedQueryObject;
 import org.onap.music.datastore.jsonobjects.JsonDelete;
 import org.onap.music.datastore.jsonobjects.JsonInsert;
@@ -56,16 +68,18 @@ import org.onap.music.main.ResultType;
 import org.onap.music.main.ReturnType;
 import org.onap.music.response.jsonobjects.JsonResponse;
 
-import com.att.eelf.configuration.EELFLogger;
 import com.datastax.driver.core.DataType;
 import com.datastax.driver.core.ResultSet;
 import com.datastax.driver.core.Row;
 import com.datastax.driver.core.TableMetadata;
+
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
 
-@Path("/v{version: [0-9]+}/keyspaces")
+/* Version 2 Class */
+//@Path("/v{version: [0-9]+}/keyspaces")
+@Path("/v2/keyspaces")
 @Api(value = "Data Api")
 public class RestMusicDataAPI {
     /*
@@ -82,18 +96,21 @@ public class RestMusicDataAPI {
      * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version
      * of the MAJOR (if not specified by the client on the request) - Contains a single position
      * value (e.g. if the full version is 1.24.5, X-patchVersion = "5") - Is mandatory for the
-     * server on response
+     * server on response  (CURRENTLY NOT USED)
      *
      *** X-latestVersion *** - Used only to communicate an API's latest version - Is mandatory for the
      * server on response, and shall include the entire version of the API (e.g. if the full version
      * is 1.24.5, X-latestVersion = "1.24.5") - Used in the response to inform clients that they are
-     * not using the latest version of the API
+     * not using the latest version of the API (CURRENTLY NOT USED)
      *
      */
 
     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class);
-    private static String xLatestVersion = "X-latestVersion";
-
+    private static final String XMINORVERSION = "X-minorVersion";
+    private static final String XPATCHVERSION = "X-patchVersion";
+    private static final String NS = "ns";
+    private static final String VERSION = "v2";
+    
     private class RowIdentifier {
         public String primarKeyValue;
         public StringBuilder rowIdString;
@@ -109,16 +126,6 @@ public class RestMusicDataAPI {
         }
     }
 
-    @SuppressWarnings("unused")
-    private String buildVersion(String major, String minor, String patch) {
-        if (minor != null) {
-            major += "." + minor;
-            if (patch != null) {
-                major += "." + patch;
-            }
-        }
-        return major;
-    }
 
     /**
      * Create Keyspace REST
@@ -133,48 +140,50 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Create Keyspace", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> createKeySpace(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+    //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 = "Application namespace",
-                                    required = true) @HeaderParam("ns") String ns,
-                    @ApiParam(value = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                    @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,
-                    @Context HttpServletResponse response) {
+                    @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);
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (!authMap.isEmpty()) {
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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());
-               return authMap;
-       }
+            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.applicationLogger,
-                        "Exception while authenting the user.");
-                       return new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap();
-               }
+            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 {
-                return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+                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();
             }
         }
 
@@ -188,7 +197,8 @@ public class RestMusicDataAPI {
         try {
             repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}";
         } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
+            
         }
         queryObject.appendQueryString(
                         "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString);
@@ -205,48 +215,10 @@ public class RestMusicDataAPI {
         ResultType result = ResultType.FAILURE;
         try {
             result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
-            logger.error(EELFLoggerDelegate.errorLogger, "resulta = " + result);
-        } catch (Exception e) {
-            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
-            return new JsonResponse(ResultType.FAILURE)
-                       .setError("Couldn't create keyspace. Please make sure all the information is correct.").toMap();
-        }
-
-        if (result==ResultType.FAILURE) {
-               logger.info(EELFLoggerDelegate.applicationLogger, "Cannot create keyspace, cleaning up");
-               JsonResponse resultJson = new JsonResponse(ResultType.FAILURE);
-            resultJson.setError("Keyspace already exists. Please contact admin.");
-            if (authMap.get("uuid").equals("new")) {
-                queryObject = new PreparedQueryObject();
-                queryObject.appendQueryString(
-                                "DELETE FROM admin.keyspace_master where uuid = " + newAid);
-                queryObject.appendQueryString(";");
-                try {
-                                       MusicCore.nonKeyRelatedPut(queryObject, consistency);
-                               } catch (MusicServiceException e) {
-                                       logger.error(EELFLoggerDelegate.errorLogger,
-                                                       "Error cleaning up createKeyspace. Cannot DELETE uuid. " + e.getMessage());
-                               }
-                return resultJson.toMap();
-            } else {
-                queryObject = new PreparedQueryObject();
-                queryObject.appendQueryString(
-                                "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;");
-                try {
-                       queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
-                                MusicUtil.DEFAULTKEYSPACENAME));
-                                       queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid));
-                               } catch (Exception e) {
-                                       logger.error(EELFLoggerDelegate.errorLogger,
-                                                       "Error cleaning up createKeyspace. Cannot get correct data types" + e.getMessage());
-                               }
-                try {
-                                        MusicCore.nonKeyRelatedPut(queryObject, consistency);
-                               } catch (MusicServiceException e) {
-                                       logger.error(EELFLoggerDelegate.errorLogger, "Unable to process operation. Error: "+e.getMessage());
-                               }
-                return resultJson.toMap();
-            }
+            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();
         }
         
         try {
@@ -260,10 +232,32 @@ public class RestMusicDataAPI {
             queryObject.appendQueryString(";");
             MusicCore.nonKeyRelatedPut(queryObject, consistency);
         } catch (Exception e) {
-               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+        }
+        
+        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();
         }
         
-        return new JsonResponse(ResultType.SUCCESS).toMap();
+        return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
     }
 
     /**
@@ -276,33 +270,26 @@ public class RestMusicDataAPI {
     @DELETE
     @Path("/{name}")
     @ApiOperation(value = "Delete Keyspace", response = String.class)
-    @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> dropKeySpace(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+    //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 = "Application namespace",
-                                    required = true) @HeaderParam("ns") String ns,
-                    @ApiParam(value = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
-                    JsonKeySpace kspObject,
-                    @ApiParam(value = "Keyspace Name",
-                                    required = true) @PathParam("name") String keyspaceName,
-                    @Context HttpServletResponse response) throws Exception {
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password,
-                        keyspaceName, aid, "dropKeySpace");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
+                    @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");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            return authMap;
+            return response.status(Status.UNAUTHORIZED).entity(authMap).build();
         }
 
         String consistency = MusicUtil.EVENTUAL;// for now this needs only
@@ -318,7 +305,9 @@ public class RestMusicDataAPI {
         long count = row.getLong(0);
 
         if (count == 0) {
-            return new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap();
+            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(
@@ -336,14 +325,20 @@ public class RestMusicDataAPI {
 
         PreparedQueryObject queryObject = new PreparedQueryObject();
         queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
-        return new JsonResponse(MusicCore.nonKeyRelatedPut(queryObject, consistency)).toMap();
+        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();
     }
 
     /**
      * 
      * @param tableObj
+     * @param version
      * @param keyspace
      * @param tablename
+     * @param headers
      * @return
      * @throws Exception
      */
@@ -352,61 +347,141 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Create Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> createTable(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+    //public Map<String, Object> createTable(
+    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
-                    JsonTable tableObj,
-                    @ApiParam(value = "Keyspace Name",
-                                    required = true) @PathParam("keyspace") String keyspace,
-                    @ApiParam(value = "Table Name",
-                                    required = true) @PathParam("tablename") String tablename,
-                    @Context HttpServletResponse response) throws Exception {
-       
+                    @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");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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
+
         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;
-        String primaryKey;
         for (Map.Entry<String, String> entry : fields.entrySet()) {
-            
             if (entry.getKey().equals("PRIMARY KEY")) {
-               if(! entry.getValue().contains("("))
-                       primaryKey = entry.getValue();
-               else {
-                       primaryKey = entry.getValue().substring(entry.getValue().indexOf('(') + 1);
-                       primaryKey = primaryKey.substring(0, primaryKey.indexOf(')'));
-               }
-               fieldsString.append("" + entry.getKey() + " (" + primaryKey + ")");
-            } else
-               fieldsString.append("" + entry.getKey() + " " + entry.getValue() + "");
-            if (counter == fields.size() - 1)
-                fieldsString.append(")");
-            else
-                fieldsString.append(",");
-            counter = counter + 1;
-        }
+                primaryKey = entry.getValue(); // replaces 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) ) {
+                 
+                 //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(
+                                "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 (primaryKey != null) fieldsString.append("" + entry.getKey() + " (" + 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();
@@ -431,23 +506,58 @@ public class RestMusicDataAPI {
             }
         }
 
-        queryObject.appendQueryString(
-                        "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString);
-
-        if (propertiesMap != null)
-            queryObject.appendQueryString(" WITH " + propertiesString);
-
+    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) {
-               response.setStatus(400);
-            return new JsonResponse(result).toMap();
+            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();
         }
-
-        return new JsonResponse(result).toMap();
+        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 + " Created under keyspace " + keyspace).toMap()).build();
     }
 
     /**
@@ -462,50 +572,51 @@ public class RestMusicDataAPI {
     @Path("/{keyspace}/tables/{tablename}/index/{field}")
     @ApiOperation(value = "Create Index", response = String.class)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> createIndex(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+    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 = "Application namespace",
-                                    required = true) @HeaderParam("ns") String ns,
-                    @ApiParam(value = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
-                    @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, @Context HttpServletResponse response) throws Exception {
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                        aid, "createIndex");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
+                    @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 {
+        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, "createIndex");
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
-        if (!authMap.isEmpty())
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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)
             indexName = rowParams.getFirst("index_name");
         PreparedQueryObject query = new PreparedQueryObject();
-        query.appendQueryString("Create index " + indexName + " if not exists on " + keyspace + "."
+        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) {
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
+            response.status(Status.BAD_REQUEST);
+            return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
+        }
+        if ( result.equals(ResultType.SUCCESS) ) {
+            return response.status(Status.OK).entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build();
+        } else {
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build();
         }
-
-        return new JsonResponse(result).toMap();
     }
 
     /**
@@ -521,54 +632,51 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Insert Into Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> insertIntoTable(
-                    @ApiParam(value = "Major Version",
-                                    required = true) @PathParam("version") String version,
-                    @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
-                    @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+    public Response insertIntoTable(
+                    @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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                    @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
+                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     JsonInsert insObj,
                     @ApiParam(value = "Keyspace Name",
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
-                                    required = true) @PathParam("tablename") String tablename,
-                    @Context HttpServletResponse response) {
+                                    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,
+            authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
                           aid, "insertIntoTable");
         } catch (Exception e) {
-          logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
-          return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
+          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();
         }
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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();
         }
 
         Map<String, Object> valuesMap = insObj.getValues();
         PreparedQueryObject queryObject = new PreparedQueryObject();
         TableMetadata tableInfo = null;
-               try {
-                       tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
-                       if(tableInfo == null) {
-                               return new JsonResponse(ResultType.FAILURE)
-                                               .setError("Table name doesn't exists. Please check the table name.").toMap();
-                       }
-               } catch (MusicServiceException e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
-                       return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
-               }
+        try {
+            tableInfo = MusicCore.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);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
+        }
         String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
         StringBuilder fieldsString = new StringBuilder("(vector_ts,");
         String vectorTs =
@@ -577,7 +685,7 @@ public class RestMusicDataAPI {
         queryObject.addValue(vectorTs);
         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();
@@ -585,8 +693,13 @@ public class RestMusicDataAPI {
                 primaryKey = entry.getValue() + "";
                 primaryKey = primaryKey.replace("'", "''");
             }
-
-            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
+            DataType colType = null;
+            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);
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
+            }
 
             Object formattedValue = null;
             try {
@@ -595,6 +708,7 @@ public class RestMusicDataAPI {
               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
           }
             valueString.append("?");
+            
             queryObject.addValue(formattedValue);
 
             if (counter == valuesMap.size() - 1) {
@@ -607,11 +721,48 @@ public class RestMusicDataAPI {
             counter = counter + 1;
         }
         
+        //blobs..
+        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("'", "''");
+            }
+
+            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 {*/
+                fieldsString.append(",");
+                valueString.append(",");
+            //}
+        } }
+        
         if(primaryKey == null || primaryKey.length() <= 0) {
-               logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
-                       return new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap();
+            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(), ")");
+               
         queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " "
                         + fieldsString + " VALUES " + valueString);
 
@@ -646,8 +797,13 @@ public class RestMusicDataAPI {
                 result = MusicCore.eventualPut(queryObject);
             } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
                 String lockId = insObj.getConsistencyInfo().get("lockId");
-                result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,
-                                null);
+                if(lockId == null) {
+                    logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
+                            + " 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();
+                }
+                result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null);
             } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
                 result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null);
 
@@ -657,14 +813,15 @@ public class RestMusicDataAPI {
 
             }
         } catch (Exception ex) {
-               logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
         
         if (result==null) {
-               return new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,"", 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();
         }
-        return new JsonResponse(result.getResult()).toMap();
+        return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build();
     }
 
     /**
@@ -681,39 +838,41 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Update Table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> updateTable(
+    public Response updateTable(
                     @ApiParam(value = "Major Version",
                                     required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
+                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+                                    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                                    required = true) @HeaderParam(NS) String ns,
+                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     JsonUpdate updateObj,
                     @ApiParam(value = "Keyspace Name",
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info, @Context HttpServletResponse response) {
+                    @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;
         try {
-               authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
+            authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
                           aid, "updateTable");
         } catch (Exception e) {
-          logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
-          return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
+              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();
         }
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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();
         }
         long startTime = System.currentTimeMillis();
         String operationId = UUID.randomUUID().toString();// just for infoging
@@ -727,16 +886,17 @@ public class RestMusicDataAPI {
         Map<String, Object> valuesMap = updateObj.getValues();
 
         TableMetadata tableInfo;
-               try {
-                       tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
-               } catch (MusicServiceException e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
-                       return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
-               }
+        try {
+            tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
+        } catch (MusicServiceException 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();
+        }
         if (tableInfo == null) {
-            return new JsonResponse(ResultType.FAILURE)
+            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();
+                                            + keyspace + "." + tablename).toMap()).build();
         }
         String vectorTs =
                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
@@ -745,7 +905,13 @@ public class RestMusicDataAPI {
         int counter = 0;
         for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
             Object valueObj = entry.getValue();
-            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
+            DataType colType = null;
+            try {
+                colType = tableInfo.getColumn(entry.getKey()).getType();
+            } catch(NullPointerException ex) {
+                logger.error(EELFLoggerDelegate.errorLogger, "Invalid column name : "+entry.getKey());
+                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);
@@ -786,13 +952,12 @@ public class RestMusicDataAPI {
         try {
             rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
             if(rowId == null || rowId.primarKeyValue.isEmpty()) {
-               
-               return new JsonResponse(ResultType.FAILURE)
-                               .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap();
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE)
+                        .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build();
             }
         } catch (MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage());
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
 
         queryObject.appendQueryString(
@@ -818,6 +983,12 @@ public class RestMusicDataAPI {
             operationResult = MusicCore.eventualPut(queryObject);
         else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
             String lockId = updateObj.getConsistencyInfo().get("lockId");
+            if(lockId == null) {
+                logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
+                        + " 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();
+            }
             operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue,
                             queryObject, lockId, conditionInfo);
         } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) {
@@ -826,16 +997,16 @@ public class RestMusicDataAPI {
               operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename,
                               rowId.primarKeyValue, queryObject, conditionInfo);
             } catch (MusicLockingException e) {
-                logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
-                return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
+                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();
             }
         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
             try {
               operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
                               queryObject, conditionInfo);
             } catch (MusicLockingException e) {
-              logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
-              return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
+                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();
             }
         }
         long actualUpdateCompletionTime = System.currentTimeMillis();
@@ -854,9 +1025,16 @@ public class RestMusicDataAPI {
         logger.info(EELFLoggerDelegate.applicationLogger, timingString);
         
         if (operationResult==null) {
-               return new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap();
+            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() == ResultType.SUCCESS ) {
+            return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build();
+        } else {
+            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();
         }
-        return new JsonResponse(operationResult.getResult()).toMap();
+        
     }
 
     /**
@@ -873,42 +1051,46 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Delete From table", response = String.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> deleteFromTable(
+    public Response deleteFromTable(
                     @ApiParam(value = "Major Version",
                                     required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
+                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+                                    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                                    required = true) @HeaderParam(NS) String ns,
+                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     JsonDelete delObj,
                     @ApiParam(value = "Keyspace Name",
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info, @Context HttpServletResponse response) {
+                    @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;
-               try {
-                       authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                                       aid, "deleteFromTable");
-               } catch (Exception e) {
-                       return new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap();
-               }
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
+        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");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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(delObj == null) {
-                       return new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap();
-               }
+            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();
+        }
         PreparedQueryObject queryObject = new PreparedQueryObject();
         StringBuilder columnString = new StringBuilder();
 
@@ -928,7 +1110,8 @@ public class RestMusicDataAPI {
         try {
             rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
         } catch (MusicServiceException ex) {
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+              return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
         String rowSpec = rowId.rowIdString.toString();
 
@@ -946,7 +1129,6 @@ public class RestMusicDataAPI {
             queryObject.appendQueryString(
                             "DELETE " + columnString + " FROM " + keyspace + "." + rowSpec + ";");
         }
-
         // get the conditional, if any
         Condition conditionInfo;
         if (delObj.getConditions() == null)
@@ -964,28 +1146,41 @@ public class RestMusicDataAPI {
 
         ReturnType operationResult = null;
         try {
-               if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
-                   operationResult = MusicCore.eventualPut(queryObject);
-               else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
-                   String lockId = delObj.getConsistencyInfo().get("lockId");
-                   operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue,
-                                   queryObject, lockId, conditionInfo);
-               } 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);
-               }
+            if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
+                operationResult = MusicCore.eventualPut(queryObject);
+            else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
+                String lockId = delObj.getConsistencyInfo().get("lockId");
+                if(lockId == null) {
+                    logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
+                            + " 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();
+                }
+                operationResult = MusicCore.criticalPut(keyspace, tablename, rowId.primarKeyValue,
+                                queryObject, lockId, conditionInfo);
+            } 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);
+            }
         } catch (MusicLockingException e) {
-                       return new JsonResponse(ResultType.FAILURE)
-                                       .setError("Unable to perform Delete operation. Exception from music").toMap();
-               }
+            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+              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) {
-               return new JsonResponse(ResultType.FAILURE).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,"", 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();
         }
-        return new JsonResponse(operationResult.getResult()).toMap();
     }
 
     /**
@@ -998,44 +1193,44 @@ public class RestMusicDataAPI {
     @DELETE
     @Path("/{keyspace}/tables/{tablename}")
     @ApiOperation(value = "Drop Table", response = String.class)
-    @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> dropTable(
+    public Response dropTable(
                     @ApiParam(value = "Major Version",
                                     required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
+                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+                                    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
-                    JsonTable tabObj,
+                                    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 HttpServletResponse response) throws Exception {
+                                    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, "dropTable");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-               return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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();
         }
         String consistency = "eventual";// for now this needs only eventual
                                         // consistency
         PreparedQueryObject query = new PreparedQueryObject();
         query.appendQueryString("DROP TABLE  " + keyspace + "." + tablename + ";");
         try {
-            return new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap();
+            return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build();
         } catch (MusicServiceException ex) {
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
 
     }
@@ -1053,34 +1248,34 @@ public class RestMusicDataAPI {
     @ApiOperation(value = "Select Critical", response = Map.class)
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> selectCritical(
+    public Response selectCritical(
                     @ApiParam(value = "Major Version",
                                     required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
+                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+                                    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                                    required = true) @HeaderParam(NS) String ns,
+                    @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
                     JsonInsert selObj,
                     @ApiParam(value = "Keyspace Name",
                                     required = true) @PathParam("keyspace") String keyspace,
                     @ApiParam(value = "Table Name",
                                     required = true) @PathParam("tablename") String tablename,
-                    @Context UriInfo info, @Context HttpServletResponse response) throws Exception {
-        Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
-                        aid, "selectCritical");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
+                    @Context UriInfo info) 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, "selectCritical");
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-            logger.error("Error while authentication... ");
-            return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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();
         }
         String lockId = selObj.getConsistencyInfo().get("lockId");
 
@@ -1090,7 +1285,8 @@ public class RestMusicDataAPI {
         try {
             rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
         } catch (MusicServiceException ex) {
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+              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 + ";");
@@ -1100,6 +1296,12 @@ public class RestMusicDataAPI {
         String consistency = selObj.getConsistencyInfo().get("type");
 
         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);
+                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();
+            }
             results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,
                             lockId);
         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
@@ -1109,8 +1311,12 @@ public class RestMusicDataAPI {
         else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
             results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject);
         }
+        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).setError("No data found").toMap()).build();
 
-        return new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap();
+        
     }
 
     /**
@@ -1125,33 +1331,34 @@ public class RestMusicDataAPI {
     @Path("/{keyspace}/tables/{tablename}/rows")
     @ApiOperation(value = "Select All or Select Specific", response = Map.class)
     @Produces(MediaType.APPLICATION_JSON)
-    public Map<String, Object> select(
+    public Response select(
                     @ApiParam(value = "Major Version",
                                     required = true) @PathParam("version") String version,
                     @ApiParam(value = "Minor Version",
-                                    required = false) @HeaderParam("X-minorVersion") String minorVersion,
+                                    required = false) @HeaderParam(XMINORVERSION) String minorVersion,
                     @ApiParam(value = "Patch Version",
-                                    required = false) @HeaderParam("X-patchVersion") String patchVersion,
+                                    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 = "userId",
-                                    required = true) @HeaderParam("userId") String userId,
-                    @ApiParam(value = "Password",
-                                    required = true) @HeaderParam("password") String password,
+                                    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, @Context HttpServletResponse response) throws Exception {
+                    @Context UriInfo info) 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, "select");
-        response.addHeader(xLatestVersion, MusicUtil.getVersion());
         if (authMap.containsKey("aid"))
-               authMap.remove("aid");
+            authMap.remove("aid");
         if (!authMap.isEmpty()) {
-               logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
-               return new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap();
+            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();
         }
         PreparedQueryObject queryObject = new PreparedQueryObject();
 
@@ -1160,19 +1367,23 @@ public class RestMusicDataAPI {
         else {
             int limit = -1; // do not limit the number of results
             try {
-                queryObject = selectSpecificQuery(version, minorVersion, patchVersion, aid, ns,
+                queryObject = selectSpecificQuery(VERSION, minorVersion, patchVersion, aid, ns,
                                 userId, password, keyspace, tablename, info, limit);
             } catch (MusicServiceException ex) {
-                return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+                logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+                return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
             }
         }
 
         try {
             ResultSet results = MusicCore.get(queryObject);
-            return new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap();
+            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(MusicCore.marshallResults(results)).setError("No data found").toMap()).build();
         } catch (MusicServiceException ex) {
-               logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
-            return new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap();
+            logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR  ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
+            return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
         }
 
     }
@@ -1235,13 +1446,15 @@ public class RestMusicDataAPI {
             String keyName = entry.getKey();
             List<String> valueList = entry.getValue();
             String indValue = valueList.get(0);
-            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
+            DataType colType = null;
             Object formattedValue = null;
             try {
+              colType = tableInfo.getColumn(entry.getKey()).getType();
               formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
             } catch (Exception e) {
               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
             }
+            if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey()))
             primaryKey.append(indValue);
             rowSpec.append(keyName + "= ?");
             queryObject.addValue(formattedValue);