From d6e7b63cc580e7b3822be61fe92a493ad5e222a3 Mon Sep 17 00:00:00 2001 From: "Nelson, Thomas (arthurdent3)" Date: Thu, 9 May 2019 14:16:37 +0000 Subject: Changes Listed below: - Added build version API - Updated Keyspace active to use Properties setting - Update Libraries Netty,jbcrypt,Jackson Databind and log4j - Removed some irrelivant files - Updated some usint tests to ignore some tests(This will be updated soon) - Bugfixes - Missing Values, inform user. - Respond with proper error - Fix Locking Contention issue. - Add locking retry for atomic calls. Change-Id: Ie218dd92edb0c20e4a0efe33eeaaec84e5293c44 Issue-ID: MUSIC-393 Signed-off-by: Nelson, Thomas (arthurdent3) --- .../org/onap/music/rest/RestMusicAdminAPI.java | 277 +++++-- .../java/org/onap/music/rest/RestMusicDataAPI.java | 853 +++++++++++---------- .../org/onap/music/rest/RestMusicLocksAPI.java | 38 +- .../java/org/onap/music/rest/RestMusicQAPI.java | 624 ++++++++------- .../org/onap/music/rest/RestMusicVersionAPI.java | 25 +- 5 files changed, 977 insertions(+), 840 deletions(-) (limited to 'src/main/java/org/onap/music/rest') diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index fddeebff..664747f6 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -27,6 +27,7 @@ package org.onap.music.rest; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -50,8 +51,10 @@ import org.mindrot.jbcrypt.BCrypt; import org.onap.music.authentication.CachingUtil; import org.onap.music.authentication.MusicAAFAuthentication; import org.onap.music.authentication.MusicAuthenticator; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; +import org.onap.music.datastore.jsonobjects.MusicResponse; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; @@ -61,10 +64,14 @@ import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.springframework.beans.factory.config.YamlProcessor.ResolutionMethod; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; +import com.datastax.driver.core.TableMetadata; +import com.sun.xml.bind.v2.TODO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -73,8 +80,6 @@ import io.swagger.annotations.ApiParam; //import java.util.Base64.Decoder; @Path("/v2/admin") -// @Path("/v{version: [0-9]+}/admin") -// @Path("/admin") @Api(value = "Admin Api", hidden = true) public class RestMusicAdminAPI { private static EELFLoggerDelegate logger = @@ -110,11 +115,10 @@ public class RestMusicAdminAPI { Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); - String isAAF = jsonObj.getIsAAF(); String password = jsonObj.getPassword(); String keyspace_name = jsonObj.getKeyspace(); - if (appName == null || userId == null || isAAF == null || password == null) { + if (appName == null || userId == null || password == null || keyspace_name == null) { logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); resultMap.put("Exception", @@ -123,18 +127,22 @@ public class RestMusicAdminAPI { } PreparedQueryObject pQuery = new PreparedQueryObject(); - /* - * pQuery.appendQueryString( - * "select uuid from admin.keyspace_master where application_name = ? allow filtering" - * ); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - * appName)); ResultSet rs = MusicCore.get(pQuery); if (!rs.all().isEmpty()) { - * logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA - * ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - * response.status(Status.BAD_REQUEST); return response.entity(new - * JsonResponse(ResultType.FAILURE).setError("Application " + appName + - * " has already been onboarded. Please contact admin.").toMap()).build(); } - */ - //pQuery = new PreparedQueryObject(); + + pQuery.appendQueryString( + "select uuid from admin.keyspace_master where application_name = ? and keyspace_name = ? allow filtering"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace_name)); + ResultSet rs = MusicCore.get(pQuery); + if (!rs.all().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, + ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE) + .setError("Application " + appName + " has already been onboarded. Please contact admin.").toMap()) + .build(); + } + + pQuery = new PreparedQueryObject(); String uuid = MusicUtil.generateUUID(); pQuery.appendQueryString( "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " @@ -142,10 +150,10 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),keyspace_name)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "False")); 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)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "true")); String returnStr = MusicCore.eventualPut(pQuery).toString(); if (returnStr.contains("Failure")) { @@ -154,7 +162,7 @@ public class RestMusicAdminAPI { return response.entity(new JsonResponse(ResultType.FAILURE).setError("Oops. Something wrong with onboarding process. " + "Please retry later or contact admin.").toMap()).build(); } - CachingUtil.updateisAAFCache(appName, isAAF); + //CachingUtil.updateisAAFCache(appName, isAAF); resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC."); resultMap.put("Generated AID", uuid); return response.status(Status.OK).entity(resultMap).build(); @@ -258,26 +266,27 @@ public class RestMusicAdminAPI { PreparedQueryObject pQuery = new PreparedQueryObject(); String consistency = MusicUtil.EVENTUAL; if (appName == null && aid == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + logger.error(EELFLoggerDelegate.errorLogger, + "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present"); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } if (aid != null) { - if ( KEYSPACE_ACTIVE ) { - pQuery.appendQueryString( - "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString(aid))); - Row row = MusicCore.get(pQuery).one(); - if (row != null) { - String ks = row.getString("keyspace_name"); - if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); - } - } + if (MusicUtil.isKeyspaceActive()) { + pQuery.appendQueryString( + "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), + UUID.fromString(aid))); + Row row = MusicCore.get(pQuery).one(); + if (row != null) { + String ks = row.getString("keyspace_name"); + if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";"); + MusicCore.nonKeyRelatedPut(queryObject, consistency); + } + } } pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); @@ -288,9 +297,11 @@ public class RestMusicAdminAPI { resultMap.put("Success", "Your application has been deleted successfully"); } else { resultMap.put("Exception", - "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded"); - logger.error(EELFLoggerDelegate.errorLogger, "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded"); + logger.error(EELFLoggerDelegate.errorLogger, + "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded", + AppMessages.INCORRECTDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -362,8 +373,7 @@ public class RestMusicAdminAPI { String aid = jsonObj.getAid(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); - String isAAF = jsonObj.getIsAAF(); - String password = jsonObj.getPassword(); + String cassandraKeyspace=jsonObj.getKeyspace(); String consistency = "eventual"; PreparedQueryObject pQuery; @@ -374,7 +384,7 @@ public class RestMusicAdminAPI { return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } - if (appName == null && userId == null && password == null && isAAF == null) { + if (appName == null || userId == null || cassandraKeyspace == null) { resultMap.put("Exception", "No parameters found to update. Please update atleast one parameter."); logger.error(EELFLoggerDelegate.errorLogger, "No parameters found to update. Please update atleast one parameter.", AppMessages.MISSINGDATA, @@ -388,10 +398,10 @@ public class RestMusicAdminAPI { "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); ResultSet rs = MusicCore.get(pQuery); - if (!rs.all().isEmpty()) { + if (rs.all().isEmpty()) { resultMap.put("Exception", "Application " + appName - + " has already been onboarded. Please contact admin."); - logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"has already been onboarded. Please contact admin.", AppMessages.ALREADYEXIST, + + " not found. Please contact admin."); + logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"not found. Please contact admin.", AppMessages.ALREADYEXIST, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -403,10 +413,8 @@ public class RestMusicAdminAPI { preCql.append(" application_name = ?,"); if (userId != null) preCql.append(" username = ?,"); - if (password != null) - preCql.append(" password = ?,"); - if (isAAF != null) - preCql.append(" is_aaf = ?,"); + if (cassandraKeyspace != null) + preCql.append(" keyspace_name = ?,"); preCql.deleteCharAt(preCql.length() - 1); preCql.append(" WHERE uuid = ? IF EXISTS"); pQuery.appendQueryString(preCql.toString()); @@ -414,10 +422,8 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); if (userId != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - if (password != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); - if (isAAF != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + if (cassandraKeyspace != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), cassandraKeyspace)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); @@ -438,22 +444,24 @@ public class RestMusicAdminAPI { //Dashboard related calls + //TODO Make return object Response. + @GET @Path("/getall") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - public List getall(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws MusicServiceException{ - List appList = new ArrayList<>(); - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + public MusicResponse getall(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws MusicServiceException{ + MusicResponse response = new MusicResponse(); if (!authenticator.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return appList; + response.setResposne("fail", "Auth failed for admin"); + return response; } PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("SELECT * FROM " + "admin" + "." + "keyspace_master" + ";"); + try { ResultSet results = MusicCore.get(queryObject); for(Row row : results) { Application app = new Application(); @@ -463,36 +471,165 @@ public class RestMusicAdminAPI { app.setUsername(row.getString("username")); app.setKeyspace_name(row.getString("keyspace_name")); app.setUuid(row.getUUID("uuid").toString()); - appList.add(app); + response.addAppToList(app); } - return appList; - - //return app; + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); + } + return response; } + + @DELETE @Path("/delete") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - public boolean delete(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + public MusicResponse delete(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception { - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + MusicResponse response = new MusicResponse(); if (!authenticator.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return false; + response.setResposne("fail", "Auth failed for admin"); + return response; } PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?"); queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid)); ResultType result; try { - result = MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + result = MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + response.setResposne("success", "Application deleted successfully. Please contact ops team to delete keyspace"); }catch(Exception ex) { logger.error(EELFLoggerDelegate.errorLogger, ex); - return false; + response.setResposne("fail", ex.getMessage()); + return response; + } + return response; + } + + @POST + @Path("/onboard") + @ApiOperation(value = "Onboard application", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse onboard(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "auth error"); } - return true; + PreparedQueryObject pQurey = new PreparedQueryObject(); + pQurey.appendQueryString("Describe keyspace + ?"); + pQurey.addValue(MusicUtil.convertToActualDataType(DataType.text(),jsonObj.getKeyspace())); + KeyspaceMetadata keyspaceInfo = null; + //authenticator.checkOnbaordUserAccess(jsonObj.getUserId(), jsonObj.getAppname()); + try { + keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace()); + }catch (Exception e) { + logger.info(EELFLoggerDelegate.applicationLogger,"Application onbaord failed for "+ jsonObj.getKeyspace()); + + } + if(keyspaceInfo == null) { + logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again"); + response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and onboard again"); + return response; + } + Response result = null; + try { + result = onboardAppWithMusic(jsonObj, authorization); + if(result.getStatus()!= 200) { + response.setResposne("fail", result.getEntity().toString()); + }else { + response.setResposne("success", "Onboard Success"); + } + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); + return response; + + } + return response; } + + @POST + @Path("/disable") + @ApiOperation(value = "Onboard application", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse disableApplicationAccess(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "Authorization failed for music admin"); + } + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT * from admin.keyspace_master where uuid = ?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + Row row = MusicDataStoreHandle.getDSHandle().executeGet(queryObject, "eventual").one(); + boolean toggleAccess = row.getBool("is_api"); + queryObject = null; + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("UPDATE admin.keyspace_master SET is_api = ? WHERE uuid = ?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), !toggleAccess)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + try { + MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual"); + response.setResposne("success","Access toggle success"); + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); + } + + return response; + } + + @POST + @Path("/editApplication") + @ApiOperation(value = "Onboard application", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse editApplication(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "auth error"); + } + KeyspaceMetadata keyspaceInfo = null; + try { + keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace()); + }catch (Exception e) { + logger.info(EELFLoggerDelegate.applicationLogger,"Application Update failed for "+ jsonObj.getKeyspace()); + + } + if(keyspaceInfo == null) { + logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again"); + response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and update again"); + return response; + } + + try { + Response res = updateOnboardApp(jsonObj, authorization); + if(res.getStatus() != 200) { + response.setResposne("fail", res.getEntity().toString()); + }else + response.setResposne("success", "Update success"); + }catch(Exception ex){ + logger.info(EELFLoggerDelegate.errorLogger,"Exception while updating application"); + logger.info(EELFLoggerDelegate.errorLogger,ex.getMessage()); + response.setResposne("fail", ex.getMessage()); + + } + return response; + } + + } diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index 8500298b..5fa955e1 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -125,8 +125,8 @@ public class RestMusicDataAPI { public String primarKeyValue; public StringBuilder rowIdString; @SuppressWarnings("unused") - public PreparedQueryObject queryObject;// the string with all the row - // identifiers separated by AND + public PreparedQueryObject queryObject; // the string with all the row + // identifiers separated by AND public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString, PreparedQueryObject queryObject) { @@ -151,128 +151,130 @@ public class RestMusicDataAPI { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, - JsonKeySpace kspObject, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) { + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, + JsonKeySpace kspObject, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) { try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName); - if ( KEYSPACE_ACTIVE ) { - logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = CachingUtil.verifyOnboarding(ns, userId, password); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); - } - - if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_KEYSPACE)) { - return response.status(Status.UNAUTHORIZED) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check username, password and make sure your app is onboarded") - .toMap()).build(); - } - - String consistency = MusicUtil.EVENTUAL;// for now this needs only - // eventual consistency - - if(kspObject == null || kspObject.getReplicationInfo() == null) { - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - PreparedQueryObject queryObject = new PreparedQueryObject(); - if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && kspObject.getConsistencyInfo().get("consistency") != null) { - if(MusicUtil.isValidConsistency(kspObject.getConsistencyInfo().get("consistency"))) - queryObject.setConsistency(kspObject.getConsistencyInfo().get("consistency")); - else - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build(); - } - long start = System.currentTimeMillis(); - Map replicationInfo = kspObject.getReplicationInfo(); - String repString = null; - try { - repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}"; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity - .CRITICAL, ErrorTypes.DATAERROR, e); - - } - queryObject.appendQueryString( - "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString); - if (kspObject.getDurabilityOfWrites() != null) { + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); + logger.info(EELFLoggerDelegate.applicationLogger,"In Create Keyspace " + keyspaceName); + if ( MusicUtil.isKeyspaceActive() ) { + logger.info(EELFLoggerDelegate.applicationLogger,"Creating Keyspace " + keyspaceName); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map authMap = CachingUtil.verifyOnboarding(ns, userId, password); + if (!authMap.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + } + + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_KEYSPACE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); + } + + String consistency = MusicUtil.EVENTUAL;// for now this needs only + // eventual consistency + + if(kspObject == null || kspObject.getReplicationInfo() == null) { + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + PreparedQueryObject queryObject = new PreparedQueryObject(); + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && kspObject.getConsistencyInfo().get("consistency") != null) { + if (MusicUtil.isValidConsistency(kspObject.getConsistencyInfo().get("consistency"))) { + queryObject.setConsistency(kspObject.getConsistencyInfo().get("consistency")); + } else { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR) + .setError("Invalid Consistency type").toMap()).build(); + } + } + long start = System.currentTimeMillis(); + Map replicationInfo = kspObject.getReplicationInfo(); + String repString = null; + try { + repString = "{" + MusicUtil.jsonMaptoSqlString(replicationInfo, ",") + "}"; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity + .CRITICAL, ErrorTypes.DATAERROR, e); + + } queryObject.appendQueryString( - " AND durable_writes = " + kspObject.getDurabilityOfWrites()); - } - - queryObject.appendQueryString(";"); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger, - "Time taken for setting up query in create keyspace:" + (end - start)); - - ResultType result = ResultType.FAILURE; - try { - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); - logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); - } catch ( MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build(); - } - - try { - queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId - + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); - queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName - + " to '" + userId + "'"); + "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString); + if (kspObject.getDurabilityOfWrites() != null) { + queryObject.appendQueryString( + " AND durable_writes = " + kspObject.getDurabilityOfWrites()); + } + queryObject.appendQueryString(";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, e); - } - - try { - boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns)); - String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); - queryObject = new PreparedQueryObject(); - queryObject.appendQueryString( - "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), aid)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - CachingUtil.updateMusicCache(keyspaceName, ns); - CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); - MusicCore.eventualPut(queryObject); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity - .WARN, ErrorTypes.MUSICSERVICEERROR, e); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger, + "Time taken for setting up query in create keyspace:" + (end - start)); + + ResultType result = ResultType.FAILURE; + try { + result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); + } catch ( MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, ex); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build(); + } + + try { + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId + + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;"); + MusicCore.nonKeyRelatedPut(queryObject, consistency); + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName + + " to '" + userId + "'"); + queryObject.appendQueryString(";"); + MusicCore.nonKeyRelatedPut(queryObject, consistency); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, e); + } + + try { + boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns)); + String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString( + "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), aid)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + CachingUtil.updateMusicCache(keyspaceName, ns); + CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); + MusicCore.eventualPut(queryObject); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity + .WARN, ErrorTypes.MUSICSERVICEERROR, e); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } + + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build(); + } else { + String vError = "Keyspace Creation has been turned off. Contact DBA to create the keyspace or set keyspace.active to true."; + logger.info(EELFLoggerDelegate.applicationLogger,vError); + logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); } - - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build(); - } else { - String vError = "Keyspace Creation no longer supported after versions 3.2.x. Contact DBA to create the keyspace."; - logger.info(EELFLoggerDelegate.applicationLogger,vError); - logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); - } } finally { EELFLoggerDelegate.mdcRemove("keyspace"); } @@ -291,69 +293,68 @@ public class RestMusicDataAPI { @ApiOperation(value = "Delete Keyspace", response = String.class,hidden=true) @Produces(MediaType.APPLICATION_JSON) 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception { + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception { try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); - if ( KEYSPACE_ACTIVE ) { - if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DROP_KEYSPACE)) { - return response.status(Status.UNAUTHORIZED) + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + EELFLoggerDelegate.mdcPut("keyspace", "( " + keyspaceName + " ) "); + logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); + if (MusicUtil.isKeyspaceActive()) { + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DROP_KEYSPACE)) { + return response.status(Status.UNAUTHORIZED) .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check username, password and make sure your app is onboarded") - .toMap()).build(); - } - - String consistency = MusicUtil.EVENTUAL;// for now this needs only - // eventual - // consistency - String appName = CachingUtil.getAppName(keyspaceName); - String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName); - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - Row row = MusicCore.get(pQuery).one(); - long count = row.getLong(0); - - if (count == 0) { - logger.error(EELFLoggerDelegate.errorLogger,"Keyspace not found. Please make sure keyspace exists.", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build(); - // Admin Functions: - } else if (count == 1) { - pQuery = new PreparedQueryObject(); + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); + } + String consistency = MusicUtil.EVENTUAL;// for now this needs only + // eventual + // consistency + String appName = CachingUtil.getAppName(keyspaceName); + String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName); + PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( - "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - MusicCore.nonKeyRelatedPut(pQuery, consistency); + "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + Row row = MusicCore.get(pQuery).one(); + long count = row.getLong(0); + + if (count == 0) { + logger.error(EELFLoggerDelegate.errorLogger,"Keyspace not found. Please make sure keyspace exists.", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build(); + // Admin Functions: + } else if (count == 1) { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), + MusicUtil.DEFAULTKEYSPACENAME)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + MusicCore.nonKeyRelatedPut(pQuery, consistency); + } else { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + MusicCore.nonKeyRelatedPut(pQuery, consistency); + } + + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";"); + ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + if ( result.equals(ResultType.FAILURE) ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build(); } else { - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - MusicCore.nonKeyRelatedPut(pQuery, consistency); + String vError = "Keyspace deletion has been turned off. Contact DBA to delete the keyspace or set keyspace.active to true."; + logger.info(EELFLoggerDelegate.applicationLogger,vError); + logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); } - - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";"); - ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency); - if ( result.equals(ResultType.FAILURE) ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build(); - } else { - String vError = "Keyspace Droping no longer supported after versions 3.2.x. Contact DBA to drop the keyspace."; - logger.info(EELFLoggerDelegate.applicationLogger,vError); - logger.error(EELFLoggerDelegate.errorLogger,vError, AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(vError).toMap()).build(); - } } finally { EELFLoggerDelegate.mdcRemove("keyspace"); } @@ -367,7 +368,7 @@ public class RestMusicDataAPI { * @param tablename * @param headers * @return - * @throws Exception + * @throws Exception - */ @POST @Path("/{keyspace: .*}/tables/{tablename: .*}") @@ -379,216 +380,215 @@ public class RestMusicDataAPI { @ApiResponse(code= 401, message = "Unautorized User") }) public Response createTable( - @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonTable tableObj, - @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception { + @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonTable tableObj, + @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception { try { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){ - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("One or more path parameters are not set, please check and try again." - + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'") - .toMap()).build(); - } - EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_TABLE)) { - return response.status(Status.UNAUTHORIZED) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + if(keyspace == null || keyspace.isEmpty() || tablename == null || tablename.isEmpty()){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("One or more path parameters are not set, please check and try again." + + "Parameter values: keyspace='" + keyspace + "' tablename='" + tablename + "'") .toMap()).build(); - } - - 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 fields = tableObj.getFields(); - StringBuilder fieldsString = new StringBuilder("(vector_ts text,"); - int counter = 0; - for (Map.Entry entry : fields.entrySet()) { - if (entry.getKey().equals("PRIMARY KEY")) { - primaryKey = entry.getValue(); // replaces primaryKey - primaryKey = primaryKey.trim(); - } else { - if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); - else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); + } + String consistency = MusicUtil.EVENTUAL; + // for now this needs only eventual consistency + String primaryKey = null; + String partitionKey = tableObj.getPartitionKey(); + String clusterKey = tableObj.getClusteringKey(); + String filteringKey = tableObj.getFilteringKey(); + if(filteringKey != null) { + clusterKey = clusterKey + "," + filteringKey; + } + primaryKey = tableObj.getPrimaryKey(); // get primaryKey if available - if (counter != (fields.size() - 1) ) { - - counter = counter + 1; - } else { + PreparedQueryObject queryObject = new PreparedQueryObject(); + // first read the information about the table fields + Map fields = tableObj.getFields(); + if (fields == null) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Create Table Error: No fields in request").toMap()).build(); + } - if((primaryKey != null) && (partitionKey == null)) { + StringBuilder fieldsString = new StringBuilder("(vector_ts text,"); + int counter = 0; + for (Map.Entry entry : fields.entrySet()) { + if (entry.getKey().equals("PRIMARY KEY")) { + primaryKey = entry.getValue(); // replaces primaryKey primaryKey = primaryKey.trim(); - int count1 = StringUtils.countMatches(primaryKey, ')'); - int count2 = StringUtils.countMatches(primaryKey, '('); - if (count1 != count2) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + } else { + if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); + else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); + } + + if (counter != (fields.size() - 1) ) { + counter = counter + 1; + } else { + + if((primaryKey != null) && (partitionKey == null)) { + primaryKey = primaryKey.trim(); + int count1 = StringUtils.countMatches(primaryKey, ')'); + int count2 = StringUtils.countMatches(primaryKey, '('); + if (count1 != count2) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("Create Table Error: primary key '(' and ')' do not match, primary key=" + primaryKey) .toMap()).build(); - } + } - if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) - { - if (primaryKey.contains(",") ) { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index - clusterKey=clusterKey.replaceAll("[)]+", ""); - } else { - partitionKey=primaryKey; - partitionKey=partitionKey.replaceAll("[\\)]+",""); + 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("[\\(]+",""); - clusterKey=""; + partitionKey = partitionKey.trim(); + clusterKey= primaryKey.substring(primaryKey.indexOf(')')); + clusterKey=clusterKey.replaceAll("[\\(]+",""); + clusterKey=clusterKey.replaceAll("[\\)]+",""); + clusterKey = clusterKey.trim(); + if (clusterKey.indexOf(',') == 0) { + clusterKey=clusterKey.substring(1); + } + clusterKey = clusterKey.trim(); + if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) } - } else { // not null and has ) before the last char - partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey = partitionKey.trim(); - clusterKey= primaryKey.substring(primaryKey.indexOf(')')); - clusterKey=clusterKey.replaceAll("[\\(]+",""); - clusterKey=clusterKey.replaceAll("[\\)]+",""); - clusterKey = clusterKey.trim(); - if (clusterKey.indexOf(',') == 0) clusterKey=clusterKey.substring(1); - clusterKey = clusterKey.trim(); - if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) - } - if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) + 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( + 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) + + " primary key=" + primaryKey) .toMap()).build(); - } - - if (partitionKey.isEmpty() ) primaryKey=""; - else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; - else primaryKey=" (" + partitionKey + ")," + clusterKey; + } + if (partitionKey.isEmpty() ) primaryKey=""; + else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; + else primaryKey=" (" + partitionKey + ")," + clusterKey; - if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); + + if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); - } // end of length > 0 - else { - if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) + } else { // end of length > 0 + + if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) && (partitionKey.equalsIgnoreCase(clusterKey) || - clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) - { - logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( + clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { + logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ")") .toMap()).build(); - } + } - if (partitionKey.isEmpty() ) primaryKey=""; - else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; - else primaryKey=" (" + partitionKey + ")," + clusterKey; + if (partitionKey.isEmpty() ) primaryKey=""; + else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; + else primaryKey=" (" + partitionKey + ")," + clusterKey; + if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); + } + fieldsString.append(")"); + + } // end of last field check + + } // end of for each + // information about the name-value style properties + Map propertiesMap = tableObj.getProperties(); + StringBuilder propertiesString = new StringBuilder(); + if (propertiesMap != null) { + counter = 0; + for (Map.Entry entry : propertiesMap.entrySet()) { + Object ot = entry.getValue(); + String value = ot + ""; + if (ot instanceof String) { + value = "'" + value + "'"; + } else if (ot instanceof Map) { + @SuppressWarnings("unchecked") + Map otMap = (Map) ot; + value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}"; + } - if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )"); - } - fieldsString.append(")"); + propertiesString.append(entry.getKey() + "=" + value + ""); + if (counter != propertiesMap.size() - 1) + propertiesString.append(" AND "); - } // end of last field check - - } // end of for each - // information about the name-value style properties - Map propertiesMap = tableObj.getProperties(); - StringBuilder propertiesString = new StringBuilder(); - if (propertiesMap != null) { - counter = 0; - for (Map.Entry entry : propertiesMap.entrySet()) { - Object ot = entry.getValue(); - String value = ot + ""; - if (ot instanceof String) { - value = "'" + value + "'"; - } else if (ot instanceof Map) { - @SuppressWarnings("unchecked") - Map otMap = (Map) ot; - value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}"; + counter = counter + 1; } - - propertiesString.append(entry.getKey() + "=" + value + ""); - if (counter != propertiesMap.size() - 1) - propertiesString.append(" AND "); - - counter = counter + 1; } - } - String clusteringOrder = tableObj.getClusteringOrder(); + String clusteringOrder = tableObj.getClusteringOrder(); - if (clusteringOrder != null && !(clusteringOrder.isEmpty())) { - String[] arrayClusterOrder = clusteringOrder.split("[,]+"); + if (clusteringOrder != null && !(clusteringOrder.isEmpty())) { + String[] arrayClusterOrder = clusteringOrder.split("[,]+"); - for (int i = 0; i < arrayClusterOrder.length; i++) { - String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+"); - if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) { - continue; - } else { - return response.status(Status.BAD_REQUEST) - .entity(new JsonResponse(ResultType.FAILURE) - .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".") - .toMap()).build(); + for (int i = 0; i < arrayClusterOrder.length; i++) { + String[] clusterS = arrayClusterOrder[i].trim().split("[ ]+"); + if ( (clusterS.length ==2) && (clusterS[1].equalsIgnoreCase("ASC") || clusterS[1].equalsIgnoreCase("DESC"))) { + continue; + } else { + return response.status(Status.BAD_REQUEST) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:"+ clusteringOrder+".") + .toMap()).build(); + } + // add validation for column names in cluster key } - // 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); + 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 { - propertiesString.append(clusteringOrder); + logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); } - } else { - logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); - } - } //if non empty + } //if non empty - queryObject.appendQueryString( + queryObject.appendQueryString( "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); - if (propertiesString != null && propertiesString.length()>0 ) - queryObject.appendQueryString(" WITH " + propertiesString); - queryObject.appendQueryString(";"); - ResultType result = ResultType.FAILURE; - try { - result = MusicCore.createTable(keyspace, tablename, queryObject, consistency); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity - .CRITICAL, ErrorTypes.MUSICSERVICEERROR, ex); - response.status(Status.BAD_REQUEST); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); - } - if ( result.equals(ResultType.FAILURE) ) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build(); + if (propertiesString != null && propertiesString.length()>0 ) + queryObject.appendQueryString(" WITH " + propertiesString); + queryObject.appendQueryString(";"); + ResultType result = ResultType.FAILURE; + try { + result = MusicCore.createTable(keyspace, tablename, queryObject, consistency); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.MUSICSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + if ( result.equals(ResultType.FAILURE) ) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build(); + } + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename.trim() + " Created under keyspace " + keyspace.trim()).toMap()).build(); } finally { EELFLoggerDelegate.mdcRemove("keyspace"); } @@ -621,8 +621,8 @@ public class RestMusicDataAPI { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_INDEX)) { @@ -688,8 +688,8 @@ public class RestMusicDataAPI { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) { @@ -699,7 +699,6 @@ public class RestMusicDataAPI { .toMap()).build(); } - Map valuesMap = insObj.getValues(); PreparedQueryObject queryObject = new PreparedQueryObject(); TableMetadata tableInfo = null; try { @@ -717,9 +716,14 @@ public class RestMusicDataAPI { String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); StringBuilder valueString = new StringBuilder("(" + "?" + ","); queryObject.addValue(vectorTs); + + Map valuesMap = insObj.getValues(); + if (valuesMap==null) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Nothing to insert. No values provided in request.").toMap()).build(); + } int counter = 0; String primaryKey = ""; - Map objectMap = insObj.getObjectMap(); for (Map.Entry entry : valuesMap.entrySet()) { fieldsString.append("" + entry.getKey()); Object valueObj = entry.getValue(); @@ -738,7 +742,7 @@ public class RestMusicDataAPI { Object formattedValue = null; try { - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e); } @@ -757,38 +761,35 @@ public class RestMusicDataAPI { } //blobs.. + Map objectMap = insObj.getObjectMap(); if(objectMap != null) { - for (Map.Entry entry : objectMap.entrySet()) { - if(counter > 0) { - fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ","); - valueString.replace(valueString.length()-1, valueString.length(), ","); - } - fieldsString.append("" + entry.getKey()); - byte[] valueObj = entry.getValue(); - if (primaryKeyName.equals(entry.getKey())) { - primaryKey = entry.getValue() + ""; - primaryKey = primaryKey.replace("'", "''"); - } + for (Map.Entry entry : objectMap.entrySet()) { + if(counter > 0) { + fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ","); + valueString.replace(valueString.length()-1, valueString.length(), ","); + } + fieldsString.append("" + entry.getKey()); + byte[] valueObj = entry.getValue(); + if (primaryKeyName.equals(entry.getKey())) { + primaryKey = entry.getValue() + ""; + primaryKey = primaryKey.replace("'", "''"); + } - DataType colType = tableInfo.getColumn(entry.getKey()).getType(); + DataType colType = tableInfo.getColumn(entry.getKey()).getType(); - ByteBuffer formattedValue = null; + ByteBuffer formattedValue = null; - if(colType.toString().toLowerCase().contains("blob")) - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + if(colType.toString().toLowerCase().contains("blob")) + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); - valueString.append("?"); + valueString.append("?"); - queryObject.addValue(formattedValue); - counter = counter + 1; - /*if (counter == valuesMap.size() - 1) { - fieldsString.append(")"); - valueString.append(")"); - } else {*/ + queryObject.addValue(formattedValue); + counter = counter + 1; fieldsString.append(","); valueString.append(","); - //} - } } + } + } if(primaryKey == null || primaryKey.length() <= 0) { logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName ); @@ -907,7 +908,7 @@ public class RestMusicDataAPI { if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.UPDATE_TABLE)) { @@ -918,8 +919,8 @@ public class RestMusicDataAPI { } long startTime = System.currentTimeMillis(); - String operationId = UUID.randomUUID().toString();// just for infoging - // purposes. + String operationId = UUID.randomUUID().toString(); // just for infoging + // purposes. String consistency = updateObj.getConsistencyInfo().get("type"); logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency @@ -939,12 +940,11 @@ public class RestMusicDataAPI { } if (tableInfo == null) { logger.error(EELFLoggerDelegate.errorLogger,"Table information not found. Please check input for table name= "+tablename, AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("Table information not found. Please check input for table name= " - + keyspace + "." + tablename).toMap()).build(); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("Table information not found. Please check input for table name= " + + keyspace + "." + tablename).toMap()).build(); } - String vectorTs = - String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + String vectorTs = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); StringBuilder fieldValueString = new StringBuilder("vector_ts=?,"); queryObject.addValue(vectorTs); int counter = 0; @@ -959,7 +959,7 @@ public class RestMusicDataAPI { } Object valueString = null; try { - valueString = MusicUtil.convertToActualDataType(colType, valueObj); + valueString = MusicUtil.convertToActualDataType(colType, valueObj); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e); } @@ -974,7 +974,6 @@ public class RestMusicDataAPI { queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " "); if ((ttl != null) && (timestamp != null)) { - logger.info("both there"); queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?"); queryObject.addValue(Integer.parseInt(ttl)); @@ -1013,11 +1012,11 @@ public class RestMusicDataAPI { Condition conditionInfo; if (updateObj.getConditions() == null) conditionInfo = null; - else {// to avoid parsing repeatedly, just send the select query to - // obtain row + else { + // to avoid parsing repeatedly, just send the select query to obtain row PreparedQueryObject selectQuery = new PreparedQueryObject(); selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " - + rowId.rowIdString + ";"); + + rowId.rowIdString + ";"); selectQuery.addValue(rowId.primarKeyValue); conditionInfo = new Condition(updateObj.getConditions(), selectQuery); } @@ -1047,20 +1046,19 @@ public class RestMusicDataAPI { } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) { // this function is mainly for the benchmarks try { - operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, - rowId.primarKeyValue, queryObject, conditionInfo); + operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, + rowId.primarKeyValue, queryObject, conditionInfo); } catch (MusicLockingException e) { logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { try { - operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, - queryObject, conditionInfo); + operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, + queryObject, conditionInfo); } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, - ErrorTypes.GENERALSERVICEERROR, e); + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } }else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { @@ -1083,7 +1081,7 @@ public class RestMusicDataAPI { if (operationResult==null) { logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); } if ( operationResult.getResult() == ResultType.SUCCESS ) { return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); @@ -1134,7 +1132,7 @@ public class RestMusicDataAPI { if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DELETE_FROM_TABLE)) { @@ -1146,7 +1144,7 @@ public class RestMusicDataAPI { if(delObj == null) { logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build(); + 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(); @@ -1189,10 +1187,11 @@ public class RestMusicDataAPI { } // get the conditional, if any Condition conditionInfo; - if (delObj.getConditions() == null) + if (delObj.getConditions() == null) { conditionInfo = null; - else {// to avoid parsing repeatedly, just send the select query to - // obtain row + } else { + // to avoid parsing repeatedly, just send the select query to + // obtain row PreparedQueryObject selectQuery = new PreparedQueryObject(); selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); @@ -1234,9 +1233,8 @@ public class RestMusicDataAPI { operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue); } } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes - .GENERALSERVICEERROR, e); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); } if (operationResult==null) { @@ -1247,7 +1245,7 @@ public class RestMusicDataAPI { 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(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build(); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build(); } } finally { EELFLoggerDelegate.mdcRemove("keyspace"); @@ -1284,8 +1282,8 @@ public class RestMusicDataAPI { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DROP_TABLE)) { @@ -1345,8 +1343,8 @@ public class RestMusicDataAPI { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT_CRITICAL)) { @@ -1369,24 +1367,27 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } queryObject.appendQueryString( - "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); + "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); ResultSet results = null; String consistency = selObj.getConsistencyInfo().get("type"); - + try { if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { if(lockId == null) { logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or" - + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); + + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("LockId cannot be null. Create lock " - + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); + + "and acquire lock or use ATOMIC instead of CRITICAL").toMap()).build(); } - results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject, - lockId); + results = MusicCore.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,lockId); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject); } + }catch(Exception ex) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); + } + if(results!=null && results.getAvailableWithoutFetching() >0) { return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } @@ -1429,8 +1430,8 @@ public class RestMusicDataAPI { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("one or more path parameters are not set, please check and try again") - .toMap()).build(); + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT)) { @@ -1531,10 +1532,10 @@ public class RestMusicDataAPI { DataType colType = null; Object formattedValue = null; try { - colType = tableInfo.getColumn(entry.getKey()).getType(); - formattedValue = MusicUtil.convertToActualDataType(colType, indValue); + colType = tableInfo.getColumn(entry.getKey()).getType(); + formattedValue = MusicUtil.convertToActualDataType(colType, indValue); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e); + logger.error(EELFLoggerDelegate.errorLogger,e); } if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) primaryKey.append(indValue); diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 77c6ef1f..49b2d816 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -47,6 +47,7 @@ import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicLockingException; import org.onap.music.lockingservice.cassandra.MusicLockState; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; @@ -67,7 +68,7 @@ public class RestMusicLocksAPI { private static final String XMINORVERSION = "X-minorVersion"; private static final String XPATCHVERSION = "X-patchVersion"; private static final String VERSION = "v2"; - + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); /** @@ -113,7 +114,12 @@ public class RestMusicLocksAPI { } ResultType status = ResultType.SUCCESS; - String lockId = MusicCore.createLockReference(lockName); + String lockId; + try { + lockId= MusicCore.createLockReference(lockName); + } catch (MusicLockingException e) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } if (lockId == null) { status = ResultType.FAILURE; @@ -328,28 +334,13 @@ public class RestMusicLocksAPI { return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); } finally { EELFLoggerDelegate.mdcRemove("keyspace"); - } - - //MusicLockState mls = MusicZKCore.getMusicLockState(lockName); -// Map returnMap = null; -// JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName); -// if(mls == null) { -// jsonResponse.setError(""); -// jsonResponse.setMessage("No lock object created yet.."); -// logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); -// return response.status(Status.BAD_REQUEST).entity(jsonResponse.toMap()).build(); -// } else { -// jsonResponse.setStatus(ResultType.SUCCESS); -// jsonResponse.setLockStatus(mls.getLockStatus()); -// jsonResponse.setLockHolder(mls.getLockHolder()); -// return response.status(Status.OK).entity(jsonResponse.toMap()).build(); -// } + } } /** * - * deletes the process from the zk queue + * deletes the process from the lock queue * * @param lockId * @throws Exception @@ -357,7 +348,7 @@ public class RestMusicLocksAPI { @DELETE @Path("/release/{lockreference}") @ApiOperation(value = "Release Lock", - notes = "deletes the process from the zk queue", + notes = "deletes the process from the lock queue", response = Map.class) @Produces(MediaType.APPLICATION_JSON) public Response unLock(@PathParam("lockreference") String lockId, @@ -412,14 +403,15 @@ public class RestMusicLocksAPI { } /** - * + * @deprecated * @param lockName * @throws Exception */ @DELETE @Path("/delete/{lockname}") - @ApiOperation(value = "Delete Lock", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Lock", response = Map.class, hidden = true, notes = "Deprecated") + @Produces(MediaType.APPLICATION_JSON) + @Deprecated public Response deleteLock(@PathParam("lockname") String lockName, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index f3df9350..3940c84a 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -70,8 +70,8 @@ import io.swagger.annotations.ApiParam; @Api(value = "Q Api") public class RestMusicQAPI { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); - + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.class); + /** * @@ -81,138 +81,135 @@ public class RestMusicQAPI { * @throws Exception */ - @POST - @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename - @ApiOperation(value = "Create Q", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonTable tableObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @POST + @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename + @ApiOperation(value = "Create Q", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonTable tableObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - Map fields = tableObj.getFields(); + Map fields = tableObj.getFields(); if (fields == null) { - 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(); - } - - 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"); - } - - if ((primaryKey == null) && (partitionKey == null)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) + return response.status(Status.BAD_REQUEST) .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Partition key cannot be empty").toMap()) + .setError("CreateQ/Required table fields are empty or not set").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(); - } + String primaryKey = tableObj.getPrimaryKey(); + String partitionKey = tableObj.getPartitionKey(); + String clusteringKey = tableObj.getClusteringKey(); + String filteringKey = tableObj.getFilteringKey(); + String clusteringOrder = tableObj.getClusteringOrder(); - 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) { + primaryKey = tableObj.getFields().get("PRIMARY KEY"); + } - if ((primaryKey!=null) && (partitionKey == null)) { - primaryKey = primaryKey.trim(); - int count1 = StringUtils.countMatches(primaryKey,')'); - int count2 = StringUtils.countMatches(primaryKey,'('); - if (count1 != count2) { - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ Error: primary key '(' and ')' do not match, primary key=" + primaryKey) - .toMap()).build(); + 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.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("[)]+", ""); + 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 = 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; - partitionKey=partitionKey.replaceAll("[\\)]+",""); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - clusteringKey=""; - } - } else { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey = partitionKey.trim(); - clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); - clusteringKey=clusteringKey.replaceAll("[\\(]+",""); - clusteringKey=clusteringKey.replaceAll("[\\)]+",""); - clusteringKey = clusteringKey.trim(); - if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1); - clusteringKey = clusteringKey.trim(); - if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) - } - } + partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + partitionKey = partitionKey.trim(); + clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); + clusteringKey=clusteringKey.replaceAll("[\\(]+",""); + clusteringKey=clusteringKey.replaceAll("[\\)]+",""); + clusteringKey = clusteringKey.trim(); + if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1); + clusteringKey = clusteringKey.trim(); + if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) + } + } - if (partitionKey.trim().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + if (partitionKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) + return response.status(Status.BAD_REQUEST) .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Partition key cannot be empty").toMap()) + .setError("CreateQ: Partition key cannot be empty").toMap()) .build(); - } + } - if (clusteringKey.trim().isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + if (clusteringKey.trim().isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) + return response.status(Status.BAD_REQUEST) .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Clustering key cannot be empty").toMap()) + .setError("CreateQ: Clustering key cannot be empty").toMap()) .build(); - } + } - if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + if((filteringKey != null) && (filteringKey.equalsIgnoreCase(partitionKey))) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST) + return response.status(Status.BAD_REQUEST) .entity(new JsonResponse(ResultType.FAILURE) - .setError("CreateQ: Filtering key cannot be same as Partition Key").toMap()) + .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); - } + return new RestMusicDataAPI().createTable(version, minorVersion, patchVersion, aid, ns, authorization, tableObj, keyspace, tablename); + } /** * @@ -221,234 +218,225 @@ public class RestMusicQAPI { * @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 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonInsert insObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) - { - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - if (insObj.getValues().isEmpty()) { - 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, + @POST + @Path("/keyspaces/{keyspace}/{qname}/rows") + @ApiOperation(value = "", response = Void.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + // public Map 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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + JsonInsert insObj, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) { + + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (insObj.getValues().isEmpty()) { + 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - 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 MusicServiceException, MusicQueryException { - - ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); - if (updateObj.getValues().isEmpty()) { - 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 - */ + /** + * + * @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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + 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 MusicServiceException, MusicQueryException { + + ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); + if (updateObj.getValues().isEmpty()) { + 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); + } - @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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - JsonDelete delObj, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + /** + * + * @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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + 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 MusicServiceException, MusicQueryException { // added checking as per RestMusicDataAPI ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (delObj == null) { - 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(); + 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(); } - return new RestMusicDataAPI().deleteFromTable(version, minorVersion, patchVersion, aid, ns, - authorization, delObj, keyspace, tablename, info); - } + 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> 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + /** + * + * @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> 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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, @Context UriInfo info) { - int limit =1; //peek must return just the top row - Map 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(keyspace, tablename, info, limit); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, + int limit =1; //peek must return just the top row + Map 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(keyspace, tablename, info, limit); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, ex); - return response.status(Status.BAD_REQUEST) + 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(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); + } catch (MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, + ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR, ex); + 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(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); - } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, - ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR, ex); - 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> 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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, + @Context UriInfo info) throws Exception { + + 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 = "filter", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - // public Map> 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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) throws Exception { - return new RestMusicDataAPI().select(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename, info);// , limit) - - } + } - /** - * - * @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 = false) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, + /** + * + * @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 = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); - } + return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); + + } } diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java index 74b8e5dd..94540eb1 100644 --- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java @@ -47,10 +47,10 @@ import io.swagger.annotations.ApiOperation; @Api(value="Version Api") public class RestMusicVersionAPI { - private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); /** - * Get the version of MUSIC + * Get the version of MUSIC. * @return */ @GET @@ -59,6 +59,25 @@ public class RestMusicVersionAPI { public Map version(@Context HttpServletResponse response) { logger.info("Replying to request for MUSIC version with MUSIC:" + MusicUtil.getVersion()); response.addHeader("X-latestVersion",MusicUtil.getVersion()); - return new JsonResponse(ResultType.SUCCESS).setMusicVersion("MUSIC:" + MusicUtil.getVersion()).toMap(); + return new JsonResponse(ResultType.SUCCESS). + setMusicVersion("MUSIC:" + MusicUtil.getVersion()).toMap(); } + + /** + * Get the version of MUSIC. + * @return + */ + @GET + @Path("/build") + @ApiOperation(value = "Get Version", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Map build(@Context HttpServletResponse response) { + logger.info("Replying to request for MUSIC build with MUSIC:" + MusicUtil.getBuild()); + response.addHeader("X-latestVersion",MusicUtil.getVersion()); + return new JsonResponse(ResultType.SUCCESS) + .setMusicBuild("MUSIC:" + MusicUtil.getBuild()) + .setMusicVersion("MUSIC:" + MusicUtil.getVersion()).toMap(); + } + + } \ No newline at end of file -- cgit 1.2.3-korg