diff options
Diffstat (limited to 'src/main/java/org/onap/music/rest')
5 files changed, 855 insertions, 297 deletions
diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index c66944cb..d1e82337 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -37,7 +37,10 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; + +import org.mindrot.jbcrypt.BCrypt; import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JSONObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; @@ -107,7 +110,7 @@ public class RestMusicAdminAPI { MusicUtil.DEFAULTKEYSPACENAME)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); @@ -142,7 +145,7 @@ public class RestMusicAdminAPI { ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); resultMap.put("Exception", "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."); - return Response.status(Status.UNAUTHORIZED).entity(resultMap).build(); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); } PreparedQueryObject pQuery = new PreparedQueryObject(); @@ -348,7 +351,7 @@ public class RestMusicAdminAPI { if (userId != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); if (password != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); if (isAAF != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); @@ -367,4 +370,14 @@ public class RestMusicAdminAPI { return Response.status(Status.OK).entity(resultMap).build(); } + + @POST + @Path("/callbackOps") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String callbackOps(JSONObject inputJsonObj) throws Exception { + + System.out.println("Input JSON: "+inputJsonObj.getData()); + return "Success"; + } } diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index 39d5a890..30656350 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -21,10 +21,13 @@ */ package org.onap.music.rest; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; + +import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -42,6 +45,9 @@ 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; @@ -66,6 +72,7 @@ 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; @@ -102,8 +109,6 @@ public class RestMusicDataAPI { private static final String XMINORVERSION = "X-minorVersion"; private static final String XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; - private static final String USERID = "userId"; - private static final String PASSWORD = "password"; private static final String VERSION = "v2"; private class RowIdentifier { @@ -141,13 +146,15 @@ public class RestMusicDataAPI { @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, - @ApiParam(value = "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) { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password); if (!authMap.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -160,6 +167,7 @@ public class RestMusicDataAPI { return response.entity(authMap).build(); } + try { authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, "createKeySpace"); @@ -229,6 +237,7 @@ public class RestMusicDataAPI { 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, " @@ -237,11 +246,11 @@ public class RestMusicDataAPI { 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(), password)); + 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, password); + CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); MusicCore.eventualPut(queryObject); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); @@ -268,12 +277,14 @@ public class RestMusicDataAPI { @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, - @ApiParam(value = "userId",required = true) @HeaderParam(USERID) String userId, - @ApiParam(value = "Password",required = true) @HeaderParam(PASSWORD) String password, @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"); @@ -343,12 +354,14 @@ public class RestMusicDataAPI { @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, JsonTable tableObj, @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "createTable"); if (authMap.containsKey("aid")) @@ -359,30 +372,116 @@ public class RestMusicDataAPI { } 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(')')); + 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(); } - 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; - } + + 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(); @@ -407,16 +506,48 @@ public class RestMusicDataAPI { } } - queryObject.appendQueryString( - "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); + String clusteringOrder = tableObj.getClusteringOrder(); - if (propertiesMap != null) - queryObject.appendQueryString(" WITH " + propertiesString); + if (clusteringOrder != null && !(clusteringOrder.isEmpty())) { + String[] arrayClusterOrder = clusteringOrder.split("[,]+"); + for (int i = 0; i < arrayClusterOrder.length; i++) + { + String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+"); + if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) continue; + else { + //logger.error("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:\"+ clusteringOrder+\".\"", " valid clustering order is ASC or DESC; please correct clusteringOrder:"+ clusteringOrder+"."); + // logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + // ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".") + .toMap()).build(); + } + // add validation for column names in cluster key + } + + if (!(clusterKey.isEmpty())) + { + clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")"; + //cjc check if propertiesString.length() >0 instead propertiesMap + if (propertiesMap != null) propertiesString.append(" AND "+ clusteringOrder); + else propertiesString.append(clusteringOrder); + } else { + logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); + } + } //if non empty + + queryObject.appendQueryString( + "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); + + + if (propertiesString != null && propertiesString.length()>0 ) + queryObject.appendQueryString(" WITH " + propertiesString); queryObject.appendQueryString(";"); ResultType result = ResultType.FAILURE; - try { + //logger.info("cjc query="+queryObject.getQuery()); result = MusicCore.nonKeyRelatedPut(queryObject, consistency); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); @@ -447,14 +578,16 @@ public class RestMusicDataAPI { @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 = "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"); @@ -468,7 +601,7 @@ public class RestMusicDataAPI { 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; @@ -480,9 +613,9 @@ public class RestMusicDataAPI { return response.entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } if ( result.equals(ResultType.SUCCESS) ) { - return response.entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(result).setMessage("Index Created on " + keyspace+"."+tablename+"."+fieldName).toMap()).build(); } else { - return response.entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); } } @@ -505,8 +638,7 @@ public class RestMusicDataAPI { @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, JsonInsert insObj, @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, @@ -514,6 +646,9 @@ public class RestMusicDataAPI { 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 { @@ -550,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(); @@ -573,6 +708,7 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } valueString.append("?"); + queryObject.addValue(formattedValue); if (counter == valuesMap.size() - 1) { @@ -585,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 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); @@ -675,10 +848,7 @@ public class RestMusicDataAPI { @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, JsonUpdate updateObj, @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, @@ -687,6 +857,9 @@ public class RestMusicDataAPI { @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, @@ -888,10 +1061,7 @@ public class RestMusicDataAPI { @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, JsonDelete delObj, @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, @@ -900,6 +1070,9 @@ public class RestMusicDataAPI { @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, @@ -1031,16 +1204,16 @@ public class RestMusicDataAPI { @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 = "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, "dropTable"); if (authMap.containsKey("aid")) @@ -1085,10 +1258,7 @@ public class RestMusicDataAPI { @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, JsonInsert selObj, @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, @@ -1097,6 +1267,9 @@ public class RestMusicDataAPI { @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"); @@ -1138,11 +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").setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); + + } /** @@ -1167,10 +1341,7 @@ public class RestMusicDataAPI { @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 = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", @@ -1178,6 +1349,9 @@ public class RestMusicDataAPI { @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"); if (authMap.containsKey("aid")) @@ -1203,10 +1377,10 @@ public class RestMusicDataAPI { try { ResultSet results = MusicCore.get(queryObject); - if(results!=null && results.getAvailableWithoutFetching() >0) { + 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).setError("No data found").setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); } catch (MusicServiceException ex) { 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(); diff --git a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java new file mode 100644 index 00000000..895f0abf --- /dev/null +++ b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java @@ -0,0 +1,120 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ +package org.onap.music.rest; + +import java.util.HashMap; +/** + * @author inam + * + */ +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +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.MediaType; +import javax.ws.rs.Consumes; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; + + +import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.eelf.healthcheck.MusicHealthCheck; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.datastax.driver.core.ConsistencyLevel; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + + + + +@Path("/v{version: [0-9]+}/service") +@Api(value="Healthcheck Api") +public class RestMusicHealthCheckAPI { + + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + + @GET + @Path("/pingCassandra/{consistency}") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response cassandraStatus(@Context HttpServletResponse response, @ApiParam(value = "Consistency level", + required = true) @PathParam("consistency") String consistency) { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra"); + + Map<String, Object> resultMap = new HashMap<>(); + if(ConsistencyLevel.valueOf(consistency) == null) { + resultMap.put("INVALID", "Consistency level is invalid..."); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + MusicHealthCheck cassHealthCheck = new MusicHealthCheck(); + String status = cassHealthCheck.getCassandraStatus(consistency); + if(status.equals("ACTIVE")) { + resultMap.put("ACTIVE", "Cassandra Running and Listening to requests"); + return Response.status(Status.OK).entity(resultMap).build(); + } else { + resultMap.put("INACTIVE", "One or more nodes in the Cluster is/are down or not responding."); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + + + + } + + @GET + @Path("/pingZookeeper") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response ZKStatus(@Context HttpServletResponse response) { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper"); + Map<String, Object> resultMap = new HashMap<>(); + MusicHealthCheck ZKHealthCheck = new MusicHealthCheck(); + String status = ZKHealthCheck.getZookeeperStatus(); + if(status.equals("ACTIVE")) { + resultMap.put("ACTIVE", "Zookeeper is Active and Running"); + return Response.status(Status.OK).entity(resultMap).build(); + }else { + resultMap.put("INACTIVE", "Zookeeper is not responding"); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + } + + + + + + + +} diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 22112ddf..70583baa 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -81,19 +81,19 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @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) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, @@ -133,19 +133,19 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @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) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, @@ -183,19 +183,19 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @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) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, @@ -230,19 +230,19 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @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) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, @@ -275,6 +275,7 @@ public class RestMusicLocksAPI { @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, @@ -332,19 +333,19 @@ public class RestMusicLocksAPI { public Response unLock(@PathParam("lockreference") String lockId, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @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) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockId); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, @@ -390,18 +391,18 @@ public class RestMusicLocksAPI { @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Application namespace", - required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "userId", - required = true) @HeaderParam("userId") String userId, - @ApiParam(value = "Password", - required = true) @HeaderParam("password") String password) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map<String, Object> resultMap = MusicCore.validateLock(lockName); if (resultMap.containsKey("Exception")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } + Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); resultMap.remove("keyspace"); resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index e08adaf7..8af334c7 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -1,31 +1,24 @@ /* - * ============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.util.HashMap; import java.util.Map; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -37,215 +30,472 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; - +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +// cjcimport javax.servlet.http.HttpServletResponse; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicCore; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.apache.commons.lang3.StringUtils; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.ResultSet; - +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +// cjc import org.onap.music.main.ReturnType; +import org.onap.music.response.jsonobjects.JsonResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -//@Path("/v{version: [0-9]+}/priorityq/") -@Path("/priorityq/") -@Api(value="Q Api") +// import io.swagger.models.Response; +// @Path("/v{version: [0-9]+}/priorityq/") +@Path("{version}/priorityq/") +@Api(value = "Q Api") public class RestMusicQAPI { - - private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); + // private static String xLatestVersion = "X-latestVersion"; + /* + * private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicDataAPI.class); + * private static final String XMINORVERSION = "X-minorVersion"; private static final String + * XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final + * String USERID = "userId"; private static final String PASSWORD = "password"; + * */ + // private static final String VERSION = "v2"; - /** - * - * @param tableObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @POST - @Path("/keyspaces/{keyspace}/{qname}") - @ApiOperation(value = "", response = Void.class) - @Consumes(MediaType.APPLICATION_JSON) - public Response createQ( - @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, - @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="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename) throws Exception{ - return new RestMusicDataAPI().createTable(version,minorVersion,patchVersion,aid, ns, userId, password, tableObj, keyspace, tablename); + /** + * + * @param tableObj + * @param keyspace + * @param tablename + * @throws Exception + */ + + @POST + @Path("/keyspaces/{keyspace}/{qname}") // is it same as tablename?down + @ApiOperation(value = "Create Q", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + + /* old + @POST + @Path("/keyspaces/{keyspace}/{qname}") + @ApiOperation(value = "", response = Void.class) + @Consumes(MediaType.APPLICATION_JSON) + */ + public Response createQ( + // public Map<String,Object> createQ( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonTable tableObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) + throws Exception { + //logger.info(logger, "cjc before start in q 1** major version=" + version); + + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + + Map<String, String> fields = tableObj.getFields(); + if (fields == null) { // || (!fields.containsKey("order")) ){ + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ/Required table fields are empty or not set").toMap()) + .build(); } - /** - * - * @param insObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @POST - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "", response = Void.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response insertIntoQ( - @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, - @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, JsonInsert insObj, - @ApiParam(value="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename) throws Exception{ - return new RestMusicDataAPI().insertIntoTable(version,minorVersion,patchVersion,aid, ns, userId, password, insObj, keyspace, tablename); + String primaryKey = tableObj.getPrimaryKey(); + String partitionKey = tableObj.getPartitionKey(); + String clusteringKey = tableObj.getClusteringKey(); + String filteringKey = tableObj.getFilteringKey(); + String clusteringOrder = tableObj.getClusteringOrder(); + + if(primaryKey == null) { + primaryKey = tableObj.getFields().get("PRIMARY KEY"); } - /** - * - * @param updateObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @PUT - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response updateQ( - @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, - @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, JsonUpdate updateObj, - @ApiParam(value="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception{ - return new RestMusicDataAPI().updateTable(version,minorVersion,patchVersion,aid, ns, userId, password, updateObj, keyspace, tablename, info); + if ((primaryKey == null) && (partitionKey == null)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Partition key cannot be empty").toMap()) + .build(); + } + + if ((primaryKey == null) && (clusteringKey == null)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering key cannot be empty").toMap()) + .build(); + } + + if (clusteringOrder == null) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering Order cannot be empty").toMap()) + .build(); + } + + 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("CreateQ 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("[\\(]+",""); + clusteringKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index + clusteringKey=clusteringKey.replaceAll("[)]+", ""); + } else { + partitionKey=primaryKey; + partitionKey=partitionKey.replaceAll("[\\)]+",""); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusteringKey=""; + } + } else { + partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + partitionKey.trim(); + clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); + clusteringKey=clusteringKey.replaceAll("[\\(]+",""); + clusteringKey=clusteringKey.replaceAll("[\\)]+",""); + clusteringKey.trim(); + if (clusteringKey.indexOf(",") == 0) clusteringKey=clusteringKey.substring(1); + clusteringKey.trim(); + if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) + } } - /** - * - * @param delObj - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @DELETE - @Path("/keyspaces/{keyspace}/{qname}/rows") - @ApiOperation(value = "", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response deleteFromQ( - @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, - @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, JsonDelete delObj, - @ApiParam(value="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception{ - return new RestMusicDataAPI().deleteFromTable(version,minorVersion,patchVersion,aid, ns, userId, password, delObj, keyspace, tablename, info); + if (partitionKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Partition key cannot be empty").toMap()) + .build(); + } + + if (clusteringKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Clustering key cannot be empty").toMap()) + .build(); + } + + if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("CreateQ: Filtering key cannot be same as Partition Key").toMap()) + .build(); + } + + return new RestMusicDataAPI().createTable(version, minorVersion, patchVersion, aid, ns, authorization, tableObj, keyspace, tablename); + } + + /** + * + * @param insObj + * @param keyspace + * @param tablename + * @throws Exception + */ + @POST + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "", response = Void.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + // public Map<String, Object> insertIntoQ( + public Response insertIntoQ( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert insObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) + throws Exception { + // ,@Context HttpServletResponse response) throws Exception { + + // Map<String, Object> valuesMap = insObj.getValues(); + // check valuesMap.isEmpty and proceed + // if(valuesMap.isEmpty() ) { + // response.addHeader(xLatestVersion, MusicUtil.getVersion()); + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (insObj.getValues().isEmpty()) { + // response.status(404); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Required HTTP Request body is missing.").toMap()).build(); + } + return new RestMusicDataAPI().insertIntoTable(version, minorVersion, patchVersion, aid, ns, + authorization, insObj, keyspace, tablename); + } + + /** + * + * @param updateObj + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @PUT + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "updateQ", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response updateQ( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonUpdate updateObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + + //logger.info(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + // ErrorTypes.DATAERROR); + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (updateObj.getValues().isEmpty()) { + // response.status(404); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE).setError( + "Required HTTP Request body is missing. JsonUpdate updateObj.getValues() is empty. ") + .toMap()) + .build(); + + + } + return new RestMusicDataAPI().updateTable(version, minorVersion, patchVersion, aid, ns, + authorization,updateObj, keyspace, tablename, info); + } + + /** + * + * @param delObj + * @param keyspace + * @param tablename + * @param info + * + * @return + * @throws Exception + */ + + @DELETE + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "deleteQ", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response deleteFromQ( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + // @ApiParam(value = "userId", required = true) @HeaderParam("userId") String userId, + // @ApiParam(value = "Password", required = true) @HeaderParam("password") String password, + JsonDelete delObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + // added checking as per RestMusicDataAPI + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (delObj == null) { + // response.status(404); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("deleteFromQ JsonDelete delObjis empty").toMap()).build(); } - /** - * - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception + return new RestMusicDataAPI().deleteFromTable(version, minorVersion, patchVersion, aid, ns, + authorization, delObj, keyspace, tablename, info); + } + + /** + * + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @GET + @Path("/keyspaces/{keyspace}/{qname}/peek") + @ApiOperation(value = "", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + //public Map<String, HashMap<String, Object>> peek( + public Response peek( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + int limit =1; //peek must return just the top row + Map<String ,String> auth = new HashMap<>(); + String userId =auth.get(MusicUtil.USERID); + String password =auth.get(MusicUtil.PASSWORD); + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + + PreparedQueryObject queryObject = new PreparedQueryObject(); + if (info.getQueryParameters() == null ) //|| info.getQueryParameters().isEmpty()) + queryObject.appendQueryString( + "SELECT * FROM " + keyspace + "." + tablename + " LIMIT " + limit + ";"); + else { + + try { + queryObject = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, + patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); + } catch (MusicServiceException ex) { + 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 response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) + .setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + } catch (MusicServiceException ex) { + 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(); + } + } + + /** + * + * + * @param keyspace + * @param tablename + * @param info + * @return + * @throws Exception + */ + @GET + @Path("/keyspaces/{keyspace}/{qname}/filter") + @ApiOperation(value = "filter", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + // public Map<String, HashMap<String, Object>> filter( + public Response filter( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + // @ApiParam(value = "userId", required = true) @HeaderParam("userId") String userId, + //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + //int limit = -1; + /* + * PreparedQueryObject query = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, + * patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); ResultSet results + * = MusicCore.get(query); return MusicCore.marshallResults(results); */ - @GET - @Path("/keyspaces/{keyspace}/{qname}/peek") - @ApiOperation(value = "", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map<String, HashMap<String, Object>> peek( - @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, - @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="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception{ - int limit =1; //peek must return just the top row - PreparedQueryObject query = new RestMusicDataAPI().selectSpecificQuery(version,minorVersion,patchVersion,aid, ns, userId, password,keyspace,tablename,info,limit); - ResultSet results = MusicCore.get(query); - return MusicCore.marshallResults(results); - - } + /* Map<String ,String> auth = new HashMap<>(); + String userId =auth.get(MusicUtil.USERID); + String password =auth.get(MusicUtil.PASSWORD); + */ + return new RestMusicDataAPI().select(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename, info);// , limit) - /** - * - * - * @param keyspace - * @param tablename - * @param info - * @return - * @throws Exception - */ - @GET - @Path("/keyspaces/{keyspace}/{qname}/filter") - @ApiOperation(value = "", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map<String, HashMap<String, Object>> filter( - @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, - @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="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception{ - int limit =-1; - PreparedQueryObject query = new RestMusicDataAPI().selectSpecificQuery(version,minorVersion,patchVersion,aid, ns, userId, password,keyspace,tablename,info,limit); - ResultSet results = MusicCore.get(query); - return MusicCore.marshallResults(results); - } - - /** - * - * @param tabObj - * @param keyspace - * @param tablename - * @throws Exception - */ - @DELETE - @ApiOperation(value = "", response = Void.class) - @Path("/keyspaces/{keyspace}/{qname}") - public Response dropQ( - @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, - @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, - @ApiParam(value="Key Space",required=true) @PathParam("keyspace") String keyspace, - @ApiParam(value="Table Name",required=true) @PathParam("tablename") String tablename) throws Exception{ - return new RestMusicDataAPI().dropTable(version,minorVersion,patchVersion,aid, ns, userId, password, keyspace, tablename); - } + } + + /** + * + * @param tabObj + * @param keyspace + * @param tablename + * @throws Exception + */ + @DELETE + @ApiOperation(value = "DropQ", response = String.class) + @Path("/keyspaces/{keyspace}/{qname}") + @Produces(MediaType.APPLICATION_JSON) + public Response dropQ( + @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, + @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + // @ApiParam(value = "userId", required = true) @HeaderParam("userId") String userId, + //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password, + // cjc JsonTable tabObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) + throws Exception { + // @Context HttpServletResponse response) throws Exception { + // tabObj never in use & thus no need to verify + + + return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); + } } |