From a27be9fdbbf2d271c9c5780ba70fe15a24dbdb63 Mon Sep 17 00:00:00 2001 From: "Nelson,Thomas(tn1381)(arthurdent3)" Date: Tue, 29 Jan 2019 15:55:37 -0500 Subject: Push variuos changes - Spring Boot - Cadi - Cassandra Locking Change-Id: Ie9882f81f0ca141bdb7862cdabf978481fcd7c4a Issue-ID: MUSIC-296,MUSIC-272 Signed-off-by: Nelson,Thomas(tn1381)(arthurdent3) --- src/main/java/org/onap/music/rest/Application.java | 79 ++ .../org/onap/music/rest/RestMusicAdminAPI.java | 720 +++++------------- .../java/org/onap/music/rest/RestMusicBmAPI.java | 47 +- .../java/org/onap/music/rest/RestMusicDataAPI.java | 842 ++++++++++++--------- .../onap/music/rest/RestMusicHealthCheckAPI.java | 147 ++-- .../org/onap/music/rest/RestMusicLocksAPI.java | 215 ++++-- .../java/org/onap/music/rest/RestMusicQAPI.java | 123 ++- .../java/org/onap/music/rest/RestMusicTestAPI.java | 43 +- .../org/onap/music/rest/RestMusicVersionAPI.java | 32 +- 9 files changed, 1078 insertions(+), 1170 deletions(-) create mode 100644 src/main/java/org/onap/music/rest/Application.java (limited to 'src/main/java/org/onap/music/rest') diff --git a/src/main/java/org/onap/music/rest/Application.java b/src/main/java/org/onap/music/rest/Application.java new file mode 100644 index 00000000..5375155b --- /dev/null +++ b/src/main/java/org/onap/music/rest/Application.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.rest; + +public class Application { + + private String application_name; + private String username; + private String password; + private String keyspace_name; + private boolean is_aaf; + private String uuid; + private boolean is_api; + + public String getApplication_name() { + return application_name; + } + public void setApplication_name(String application_name) { + this.application_name = application_name; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + public String getKeyspace_name() { + return keyspace_name; + } + public void setKeyspace_name(String keyspace_name) { + this.keyspace_name = keyspace_name; + } + public boolean isIs_aaf() { + return is_aaf; + } + public void setIs_aaf(boolean is_aaf) { + this.is_aaf = is_aaf; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public boolean getIs_api() { + return is_api; + } + public void setIs_api(boolean is_api) { + this.is_api = is_api; + } + + +} diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 8e4facd2..289cab06 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -9,45 +9,33 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import java.util.UUID; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; @@ -57,44 +45,31 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; -import org.codehaus.jackson.map.ObjectMapper; import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.JSONCallbackResponse; -import org.onap.music.datastore.jsonobjects.JSONObject; -import org.onap.music.datastore.jsonobjects.JsonCallback; -import org.onap.music.datastore.jsonobjects.JsonNotification; -import org.onap.music.datastore.jsonobjects.JsonNotifyClientResponse; import org.onap.music.datastore.jsonobjects.JsonOnboard; 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.MusicServiceException; +//import org.onap.music.main.CacheAccess; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; -import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; -import com.datastax.driver.core.TableMetadata; -import com.datastax.driver.core.exceptions.InvalidQueryException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; -import com.sun.jersey.client.urlconnection.HTTPSProperties; -import com.sun.jersey.core.util.Base64; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +//import java.util.Base64.Encoder; +//import java.util.Base64.Decoder; @Path("/v2/admin") // @Path("/v{version: [0-9]+}/admin") @@ -103,16 +78,21 @@ import io.swagger.annotations.ApiOperation; public class RestMusicAdminAPI { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); + // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist. + private static final boolean KEYSPACE_ACTIVE = false; + /* * API to onboard an application with MUSIC. This is the mandatory first step. - * + * */ @POST @Path("/onboardAppWithMusic") @ApiOperation(value = "Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception { + public Response onboardAppWithMusic(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); Map resultMap = new HashMap<>(); @@ -120,8 +100,22 @@ public class RestMusicAdminAPI { String userId = jsonObj.getUserId(); String isAAF = jsonObj.getIsAAF(); String password = jsonObj.getPassword(); + String keyspace_name = jsonObj.getKeyspace(); + try { + if (!MusicAuthentication.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + } catch (Exception e) { + return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } if (appName == null || userId == null || isAAF == null || password == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, + 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", "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing."); @@ -129,24 +123,24 @@ 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()) { - resultMap.put("Exception", "Application " + appName - + " has already been onboarded. Please contact admin."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - - 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(); String uuid = CachingUtil.generateUUID(); pQuery.appendQueryString( "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); + 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.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); @@ -155,9 +149,10 @@ public class RestMusicAdminAPI { String returnStr = MusicCore.eventualPut(pQuery).toString(); if (returnStr.contains("Failure")) { - resultMap.put("Exception", - "Oops. Something wrong with onboarding process. Please retry later or contact admin."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + 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); resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC."); @@ -171,15 +166,29 @@ public class RestMusicAdminAPI { @ApiOperation(value = "Search Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception { + public Response getOnboardedInfoSearch(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String uuid = jsonObj.getAid(); String isAAF = jsonObj.getIsAAF(); + try { + if (!MusicAuthentication.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + } catch (Exception e) { + return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } if (appName == null && uuid == null && isAAF == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); resultMap.put("Exception", "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."); @@ -215,13 +224,14 @@ public class RestMusicAdminAPI { } if (resultMap.isEmpty()) { if (uuid != null) { - resultMap.put("Exception", - "Please make sure Aid is correct and application is onboarded."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError("Please make sure Aid is correct and application is onboarded.").toMap()).build(); + } else { - resultMap.put("Exception", - "Application is not onboarded. Please make sure all the information is correct."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError("Application is not onboarded. Please make sure all the information is correct.").toMap()).build(); } } return response.status(Status.OK).entity(resultMap).build(); @@ -233,32 +243,48 @@ public class RestMusicAdminAPI { @ApiOperation(value = "Delete Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception { + public Response deleteOnboardApp(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String aid = jsonObj.getAid(); PreparedQueryObject pQuery = new PreparedQueryObject(); String consistency = MusicUtil.EVENTUAL;; + try { + if (!MusicAuthentication.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + } catch (Exception e) { + return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } if (appName == null && aid == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, + 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) { - 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 ( 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); + } + } } pQuery = new PreparedQueryObject(); pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); @@ -270,7 +296,7 @@ public class RestMusicAdminAPI { } else { resultMap.put("Exception", "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, + 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(); @@ -287,7 +313,7 @@ public class RestMusicAdminAPI { if (rows.isEmpty()) { resultMap.put("Exception", "Application not found. Please make sure Application exists."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, + logger.error(EELFLoggerDelegate.errorLogger, "Application not found. Please make sure Application exists.", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } else if (rows.size() == 1) { @@ -315,7 +341,7 @@ public class RestMusicAdminAPI { } else { resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MULTIPLERECORDS, + logger.error(EELFLoggerDelegate.errorLogger, "More than one Aid exists for this application, so please provide Aid.", AppMessages.MULTIPLERECORDS, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -327,7 +353,8 @@ public class RestMusicAdminAPI { @ApiOperation(value = "Update Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response updateOnboardApp(JsonOnboard jsonObj) throws Exception { + public Response updateOnboardApp(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); Map resultMap = new HashMap<>(); String aid = jsonObj.getAid(); @@ -337,10 +364,22 @@ public class RestMusicAdminAPI { String password = jsonObj.getPassword(); String consistency = "eventual"; PreparedQueryObject pQuery; - + try { + if (!MusicAuthentication.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + } catch (Exception e) { + return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } if (aid == null) { resultMap.put("Exception", "Please make sure Aid is present"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + logger.error(EELFLoggerDelegate.errorLogger, "Please make sure Aid is present", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -348,7 +387,7 @@ public class RestMusicAdminAPI { if (appName == null && userId == null && password == null && isAAF == null) { resultMap.put("Exception", "No parameters found to update. Please update atleast one parameter."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, + logger.error(EELFLoggerDelegate.errorLogger, "No parameters found to update. Please update atleast one parameter.", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -362,7 +401,7 @@ public class RestMusicAdminAPI { if (!rs.all().isEmpty()) { resultMap.put("Exception", "Application " + appName + " has already been onboarded. Please contact admin."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST, + logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"has already been onboarded. Please contact admin.", AppMessages.ALREADYEXIST, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -398,7 +437,7 @@ public class RestMusicAdminAPI { } else { resultMap.put("Exception", "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, + logger.error(EELFLoggerDelegate.errorLogger, "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -406,482 +445,63 @@ public class RestMusicAdminAPI { return response.status(Status.OK).entity(resultMap).build(); } - Client client = Client.create(); - ObjectMapper mapper = new ObjectMapper(); - - @POST - @Path("/callbackOps") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - public Response callbackOps(final JSONObject inputJsonObj) { - ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - Map resultMap = new HashMap<>(); - new Thread(new Runnable() { - public void run() { - makeAsyncCall(inputJsonObj); - } - }).start(); - - return response.status(Status.OK).entity(resultMap).build(); - } - - private Response makeAsyncCall(JSONObject inputJsonObj) { - ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - Map resultMap = new HashMap<>(); - try { - logger.info(EELFLoggerDelegate.applicationLogger, "Got notification: " + inputJsonObj.getData()); - logger.info("Got notification: " + inputJsonObj.getData()); - String dataStr = inputJsonObj.getData(); - JSONCallbackResponse jsonResponse = mapper.readValue(dataStr, JSONCallbackResponse.class); - String operation = jsonResponse.getOperation(); - Map changeValueMap = jsonResponse.getChangeValue(); - String ksTableName = jsonResponse.getFull_table(); //conductor.plans - if("admin.notification_master".equals(ksTableName)) { - CachingUtil.updateCallbackNotifyList(new ArrayList()); - return response.status(Status.OK).entity(resultMap).build(); - } - List inputUpdateList = jsonResponse.getUpdateList(); - - String field_value = null; - List notifiyList = CachingUtil.getCallbackNotifyList(); - if(notifiyList == null || notifiyList.isEmpty()) { - logger.info("Is cache empty? reconstructing Object from cache.."); - constructJsonCallbackFromCache(); - } - notifiyList = CachingUtil.getCallbackNotifyList(); - JsonCallback baseRequestObj = null; - - if("update".equals(operation)) { - for(String element: inputUpdateList) { - baseRequestObj = CachingUtil.getCallBackCache(element); - if(baseRequestObj != null) { - logger.info("Found the element that was changed... "+element); - break; - } - } - - List updateList = jsonResponse.getUpdateList(); - for(String element : updateList) { - if(notifiyList.contains(element)) { - logger.info("Found the notifyOn property: "+element); - field_value = element; - break; - } - } - if(baseRequestObj == null || field_value == null) { - for(String element: inputUpdateList) { - String[] elementArr = element.split(":"); - String newElement = null; - if(elementArr.length >= 2) { - newElement = elementArr[0]+":"+elementArr[1]; - } - baseRequestObj = CachingUtil.getCallBackCache(newElement); - if(baseRequestObj != null) { - logger.info("Found the element that was changed... "+newElement); - break; - } - } - for(String element : updateList) { - String[] elementArr = element.split(":"); - String newElement = null; - if(elementArr.length >= 2) { - newElement = elementArr[0]+":"+elementArr[1]; - } - if(notifiyList.contains(newElement)) { - logger.info("Found the notifyOn property: "+newElement); - field_value = newElement; - break; - } - } - } - } else { - field_value = jsonResponse.getFull_table(); - baseRequestObj = CachingUtil.getCallBackCache(field_value); - } - - if(baseRequestObj == null || field_value == null) { - resultMap.put("Exception", - "Oops. Something went wrong. Please make sure Callback properties are onboarded."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - logger.info(EELFLoggerDelegate.applicationLogger, "Going through list: "+operation+ " && List: "+jsonResponse.getUpdateList()); - - String key = "admin" + "." + "notification_master" + "." + baseRequestObj.getUuid(); - String lockId = MusicCore.createLockReference(key); - ReturnType lockAcqResult = MusicCore.acquireLock(key, lockId); - if(!"SUCCESS".equals(lockAcqResult.getResult().toString())) { - logger.error(EELFLoggerDelegate.errorLogger, "Some other node is notifying the caller..: "); - } - - logger.info(EELFLoggerDelegate.applicationLogger, operation+ ": Operation :: changeValue: "+changeValueMap); - if("update".equals(operation)) { - String notifyWhenChangeIn = baseRequestObj.getNotifyWhenChangeIn(); // conductor.plans.status - if(null!=field_value && field_value.equals(notifyWhenChangeIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } else if("delete".equals(operation)) { - String notifyWhenDeletesIn = baseRequestObj.getNotifyWhenDeletesIn(); // conductor.plans.status - if(null!=field_value && field_value.equals(notifyWhenDeletesIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } else if("insert".equals(operation)) { - String notifyWhenInsertsIn = baseRequestObj.getNotifyWhenInsertsIn(); // conductor.plans.status - if(null!=field_value && field_value.equals(notifyWhenInsertsIn)) { - notifyCallBackAppl(jsonResponse, baseRequestObj); - } - } - MusicCore.releaseLock(lockId, true); - } catch(Exception e) { - e.printStackTrace(); - logger.error(EELFLoggerDelegate.errorLogger, "Exception while notifying...."+e.getMessage()); - } - logger.info(EELFLoggerDelegate.applicationLogger, "callback is completed. Notification was sent from Music..."); - return response.status(Status.OK).entity(resultMap).build(); - } - - private void notifyCallBackAppl(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) throws Exception { - int notifytimeout = MusicUtil.getNotifyTimeout(); - int notifyinterval = MusicUtil.getNotifyInterval(); - String endpoint = baseRequestObj.getApplicationNotificationEndpoint(); - String username = baseRequestObj.getApplicationUsername(); - String password = baseRequestObj.getApplicationPassword(); - JsonNotification jsonNotification = constructJsonNotification(jsonResponse, baseRequestObj); - jsonNotification.setPassword("************"); - jsonNotification.setOperation_type(jsonResponse.getOperation()); - logger.info(EELFLoggerDelegate.applicationLogger, "Notification Response sending is: "+jsonNotification); - logger.info("Notification Response sending is: "+jsonNotification); - jsonNotification.setPassword(baseRequestObj.getApplicationPassword()); - client.resource(endpoint); - String authData = username+":"+password; - byte[] plainCredsBytes = authData.getBytes(); - byte[] base64CredsBytes = Base64.encode(plainCredsBytes); - String base64Creds = new String(base64CredsBytes); - ClientConfig config = new DefaultClientConfig(); - config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - ClientResponse response = null; - WebResource service = null; - boolean ok = false; - try { - Client client = Client.create(config); - TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){ - public X509Certificate[] getAcceptedIssuers(){return null;} - public void checkClientTrusted(X509Certificate[] certs, String authType){} - public void checkServerTrusted(X509Certificate[] certs, String authType){} - }}; - - // Install the all-trusting trust manager - try { - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, trustAllCerts, new SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - - try { - SSLContext sslcontext = SSLContext.getInstance( "TLS" ); - sslcontext.init( null, null, null ); - Map properties = config.getProperties(); - HTTPSProperties httpsProperties = new HTTPSProperties( - new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }, sslcontext - ); - properties.put( HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties ); - HttpsURLConnection.setDefaultHostnameVerifier (new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - Client.create( config ); - } - catch ( KeyManagementException | NoSuchAlgorithmException e ) { - throw new RuntimeException( e ); - } - - service = client.resource(endpoint); - - response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON) - .post(ClientResponse.class, jsonNotification); - - } catch (Exception chf) { - logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?"); - logger.info("An Exception occured while notifying. "+chf+ " : "+chf.getMessage() +" ...Retrying for: "+notifytimeout); - } - if(response != null && response.getStatus() == 200) ok = true; - if(!ok) { - long now= System.currentTimeMillis(); - long end = now+notifytimeout; - while(! ok) { - logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback for "+notifytimeout+"ms"); - logger.info("retrying since error in notifying callback.. response status: "+ (response == null ? "404" : response.getStatus())); - try { - ok = true; - response = service.header("Authorization", "Basic " + base64Creds).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON) - .post(ClientResponse.class, jsonNotification); - if(response != null && response.getStatus() == 200) ok = true; - else if(System.currentTimeMillis() < end) { - try{ Thread.sleep(notifyinterval); } catch(Exception e1) {} - ok = false; - } - }catch (Exception e) { - logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis())); - if(response == null && System.currentTimeMillis() < end) ok = false; - else ok = true; - try{ Thread.sleep(notifyinterval); } catch(Exception e1) {} - } - } - } - - if(response == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond.."); - return; - } - try { - JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class); - logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr); - logger.info("Response from Notified client: "+responseStr); - } catch(Exception e) { - logger.info("Exception while reading response from Caller"); - logger.error("Exception while reading response from Caller"); - logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond.."); - } - } - - private JsonNotification constructJsonNotification(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) { - - JsonNotification jsonNotification = new JsonNotification(); - try { - jsonNotification.setNotify_field(baseRequestObj.getNotifyOn()); - jsonNotification.setEndpoint(baseRequestObj.getApplicationNotificationEndpoint()); - jsonNotification.setUsername(baseRequestObj.getApplicationUsername()); - jsonNotification.setPassword(baseRequestObj.getApplicationPassword()); - String pkValue = jsonResponse.getPrimary_key(); - - String[] fullNotifyArr = baseRequestObj.getNotifyOn().split(":"); - - String[] tableArr = fullNotifyArr[0].split("\\."); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(tableArr[0], tableArr[1]); - DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType(); - String primaryId = tableInfo.getPrimaryKey().get(0).getName(); - - Map responseBodyMap = baseRequestObj.getResponseBody(); - for (Entry entry : new HashSet<>(responseBodyMap.entrySet())) { - String trimmed = entry.getKey().trim(); - if (!trimmed.equals(entry.getKey())) { - responseBodyMap.remove(entry.getKey()); - responseBodyMap.put(trimmed, entry.getValue()); - } - } - - Set keySet = responseBodyMap.keySet(); - Map newMap = new HashMap<>(); - if(responseBodyMap.size() == 1 && responseBodyMap.containsKey("")) { - jsonNotification.setResponse_body(newMap); - return jsonNotification; - } - logger.info(EELFLoggerDelegate.applicationLogger, "responseBodyMap is not blank: "+responseBodyMap); - String cql = "select *"; - /*for(String keys: keySet) { - cql = cql + keys + ","; - }*/ - //cql = cql.substring(0, cql.length()-1); - cql = cql + " FROM "+fullNotifyArr[0]+" WHERE "+primaryId+" = ?"; - logger.info(EELFLoggerDelegate.applicationLogger, "CQL in constructJsonNotification: "+cql); - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString(cql); - pQuery.addValue(MusicUtil.convertToActualDataType(primaryIdType, pkValue)); - Row row = MusicCore.get(pQuery).one(); - if(row != null) { - ColumnDefinitions colInfo = row.getColumnDefinitions(); - for (Definition definition : colInfo) { - String colName = definition.getName(); - if(keySet.contains(colName)) { - DataType colType = definition.getType(); - Object valueObj = MusicCore.getDSHandle().getColValue(row, colName, colType); - Object valueString = MusicUtil.convertToActualDataType(colType, valueObj); - logger.info(colName+" : "+valueString); - newMap.put(colName, valueString.toString()); - keySet.remove(colName); - } - } - } - if(! keySet.isEmpty()) { - Iterator iterator = keySet.iterator(); - while (iterator.hasNext()) { - String element = iterator.next(); - newMap.put(element,"COLUMN_NOT_FOUND"); - } - } - - if("delete".equals(jsonResponse.getOperation()) || newMap.isEmpty()) { - newMap.put(primaryId, pkValue); - } - jsonNotification.setResponse_body(newMap); - } catch(Exception e) { - logger.error(e.getMessage(), e); - e.printStackTrace(); - } - return jsonNotification; - } - - private void constructJsonCallbackFromCache() throws Exception{ - PreparedQueryObject pQuery = new PreparedQueryObject(); - JsonCallback jsonCallback = null; - List notifyList = new java.util.ArrayList<>(); - String cql = - "select id, endpoint_userid, endpoint_password, notify_to_endpoint, notify_insert_on," - + " notify_delete_on, notify_update_on, request, notifyon from admin.notification_master allow filtering"; - pQuery.appendQueryString(cql); - - ResultSet rs = MusicCore.get(pQuery); - Iterator it = rs.iterator(); - while (it.hasNext()) { - Row row = (Row) it.next(); - String endpoint = row.getString("notify_to_endpoint"); - String username = row.getString("endpoint_userid"); - ByteBuffer passwordBytes = row.getBytes("endpoint_password"); - String insert = row.getString("notify_insert_on"); - String delete = row.getString("notify_delete_on"); - String update = row.getString("notify_update_on"); - String request = row.getString("request"); - String notifyon = row.getString("notifyon"); - String uuid = row.getUUID("id").toString(); - notifyList.add(notifyon); - jsonCallback = new JsonCallback(); - jsonCallback.setApplicationNotificationEndpoint(endpoint); - - Charset charset = Charset.forName("ISO-8859-1"); - String decodedPwd = charset.decode(passwordBytes).toString(); - jsonCallback.setApplicationPassword(decodedPwd); - jsonCallback.setApplicationUsername(username); - jsonCallback.setNotifyOn(notifyon); - jsonCallback.setNotifyWhenInsertsIn(insert); - jsonCallback.setNotifyWhenDeletesIn(delete); - jsonCallback.setNotifyWhenChangeIn(update); - jsonCallback.setUuid(uuid); - logger.info(EELFLoggerDelegate.applicationLogger, "From DB. Saved request_body: "+request); - request = request.substring(1, request.length()-1); - String[] keyValuePairs = request.split(","); - Map responseBody = new HashMap<>(); - - for(String pair : keyValuePairs) { - String[] entry = pair.split("="); - String val = ""; - if(entry.length == 2) - val = entry[1]; - responseBody.put(entry[0], val); - } - logger.info(EELFLoggerDelegate.applicationLogger, "After parsing. Saved request_body: "+responseBody); - jsonCallback.setResponseBody(responseBody); - logger.info(EELFLoggerDelegate.applicationLogger, "Updating Cache with updateCallBackCache: "+notifyon+ " :::: "+jsonCallback); - CachingUtil.updateCallBackCache(notifyon, jsonCallback); - } - CachingUtil.updateCallbackNotifyList(notifyList); - } - - @POST - @Path("/onboardCallback") + //Dashboard related calls + @GET + @Path("/getall") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - public Response addCallback(JsonNotification jsonNotification) { - Map resultMap = new HashMap<>(); + 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()); - String username = jsonNotification.getUsername(); - String password = jsonNotification.getPassword(); - String endpoint = jsonNotification.getEndpoint(); - String notify_field = jsonNotification.getNotify_field(); - Map responseBody = jsonNotification.getResponse_body(); - String triggerName = jsonNotification.getTriggerName(); - if(triggerName == null || triggerName.length() == 0) - triggerName = "MusicTrigger"; - - String[] allFields = notify_field.split(":"); - String inserts = null; - String updates = null; - String deletes = null; - String tableName = null; - if(allFields.length >= 2) { - inserts = updates = notify_field; - } else if(allFields.length == 1) { - inserts = deletes = notify_field;; + Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT * FROM " + "admin" + "." + "keyspace_master" + ";"); + ResultSet results = MusicCore.get(queryObject); + for(Row row : results) { + Application app = new Application(); + app.setApplication_name(row.getString("application_name")); + app.setIs_aaf(row.getBool("is_aaf")); + app.setIs_api(row.getBool("is_api")); + app.setUsername(row.getString("username")); + app.setKeyspace_name(row.getString("keyspace_name")); + app.setUuid(row.getUUID("uuid").toString()); + appList.add(app); } - tableName = allFields[0]; - String cql = "CREATE TRIGGER IF NOT EXISTS musictrigger ON "+tableName+" Using '"+triggerName+"'"; - PreparedQueryObject pQuery = new PreparedQueryObject(); + return appList; + + //return app; - String uuid = CachingUtil.generateUUID(); - try { - pQuery.appendQueryString( - "INSERT INTO admin.notification_master (id, endpoint_userid, endpoint_password, notify_to_endpoint, " - + "notifyon, notify_insert_on, notify_delete_on, notify_update_on, request, current_notifier) VALUES (?,?,?,?,?,?,?,?,?,?)"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), username)); - Charset charset = Charset.forName("ISO-8859-1"); - ByteBuffer decodedPwd = charset.encode(password); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.blob(), decodedPwd.array())); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), endpoint)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notify_field)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), inserts)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), deletes)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), updates)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), responseBody)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicCore.getMyHostId())); - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - JsonCallback jsonCallback = new JsonCallback(); - jsonCallback.setUuid(uuid); - jsonCallback.setApplicationNotificationEndpoint(endpoint); - jsonCallback.setApplicationPassword(password); - jsonCallback.setApplicationUsername(username); - jsonCallback.setNotifyOn(notify_field); - jsonCallback.setNotifyWhenChangeIn(updates); - jsonCallback.setNotifyWhenDeletesIn(deletes); - jsonCallback.setNotifyWhenInsertsIn(inserts); - jsonCallback.setResponseBody(responseBody); - CachingUtil.updateCallBackCache(notify_field, jsonCallback); - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString(cql); - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - logger.info(EELFLoggerDelegate.applicationLogger, "Created trigger"); - } catch (InvalidQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,"Exception callback_api table not configured."+e.getMessage()); - resultMap.put("Exception", "Please make sure admin.notification_master table is configured."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } catch(Exception e) { - logger.error(e.getMessage(), e); - e.printStackTrace(); - resultMap.put("Exception", "Exception Occured."); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully registered").toMap()).build(); } - @DELETE - @Path("/onboardCallback") + @Path("/delete") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - public Response deleteCallbackProp(JsonNotification jsonNotification) { + public boolean 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()); - String notifyOn = jsonNotification.getNotify_field(); - PreparedQueryObject pQuery = new PreparedQueryObject(); + Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid)); + ResultType result; try { - pQuery.appendQueryString("DELETE FROM admin.notification_master WHERE notifyon = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notifyOn)); - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setMessage("Callback api registration failed").toMap()).build(); + result = MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + }catch(Exception ex) { + return false; } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully deleted").toMap()).build(); + return true; + } + + + @GET + @Path("/login") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public boolean login(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + + boolean result = MusicAuthentication.authenticateAdmin(authorization); + return result; } } diff --git a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java index 60305bfb..f2946c14 100644 --- a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java @@ -1,22 +1,25 @@ /* - * ============LICENSE_START========================================== org.onap.music - * =================================================================== Copyright (c) 2017 AT&T - * Intellectual Property - * Modifications Copyright (C) 2018 IBM. + * ============LICENSE_START========================================== + * org.onap.music * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.List; @@ -39,6 +42,8 @@ import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; +import org.onap.music.service.impl.MusicZKCore; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.DataType; import com.datastax.driver.core.TableMetadata; @@ -66,7 +71,7 @@ public class RestMusicBmAPI { @Path("/purezk/{name}") @Consumes(MediaType.APPLICATION_JSON) public void pureZkCreate(@PathParam("name") String nodeName) throws Exception { - MusicCore.pureZkCreate("/" + nodeName); + MusicZKCore.pureZkCreate("/" + nodeName); } @@ -83,7 +88,7 @@ public class RestMusicBmAPI { throws Exception { logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zk normal update-------------------------"); long start = System.currentTimeMillis(); - MusicCore.pureZkWrite(nodeName, insObj.serialize()); + MusicZKCore.pureZkWrite(nodeName, insObj.serialize()); long end = System.currentTimeMillis(); logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk normal update:" + (end - start) + " ms"); } @@ -98,7 +103,7 @@ public class RestMusicBmAPI { @Path("/purezk/{name}") @Consumes(MediaType.TEXT_PLAIN) public byte[] pureZkGet(@PathParam("name") String nodeName) throws Exception { - return MusicCore.pureZkRead(nodeName); + return MusicZKCore.pureZkRead(nodeName); } /** @@ -135,13 +140,19 @@ public class RestMusicBmAPI { if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId); - MusicCore.pureZkWrite(lockname, data); + MusicZKCore.pureZkWrite(lockname, data); zkPutTime = System.currentTimeMillis(); boolean voluntaryRelease = true; +/*<<<<<<< HEAD if (("atomic").equals(consistency)) MusicCore.releaseLock(lockId, voluntaryRelease); else if (("atomic_delete_lock").equals(consistency)) MusicCore.deleteLock(lockname); +=======*/ + if (consistency.equals("atomic")) + MusicCore.releaseLock(lockId, voluntaryRelease); + else if (consistency.equals("atomic_delete_lock")) + MusicCore.deleteLock(lockname); lockReleaseTime = System.currentTimeMillis(); } else { MusicCore.destroyLockRef(lockId); @@ -189,7 +200,7 @@ public class RestMusicBmAPI { ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockName, lockId, leasePeriod); if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info("acquired lock with id " + lockId); - MusicCore.pureZkRead(nodeName); + MusicZKCore.pureZkRead(nodeName); boolean voluntaryRelease = true; MusicCore.releaseLock(lockId, voluntaryRelease); } else { @@ -225,7 +236,7 @@ public class RestMusicBmAPI { + "-------------------------"); PreparedQueryObject queryObject = new PreparedQueryObject(); Map valuesMap = insObj.getValues(); - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); String vectorTs = "'" + Thread.currentThread().getId() + System.currentTimeMillis() + "'"; String fieldValueString = "vector_ts= ? ,"; queryObject.addValue(vectorTs); @@ -290,7 +301,7 @@ public class RestMusicBmAPI { long jsonParseCompletionTime = System.currentTimeMillis(); boolean operationResult = true; - MusicCore.getDSHandle().executePut(queryObject, insObj.getConsistencyInfo().get("type")); + MusicDataStoreHandle.getDSHandle().executePut(queryObject, insObj.getConsistencyInfo().get("type")); long actualUpdateCompletionTime = System.currentTimeMillis(); diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index a8fd1fc2..507bcd40 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -7,18 +7,19 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.nio.ByteBuffer; @@ -48,6 +49,7 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -56,17 +58,20 @@ import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicCore.Condition; +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; +import org.onap.music.service.impl.MusicZKCore; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ResultSet; @@ -76,6 +81,8 @@ import com.datastax.driver.core.TableMetadata; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ApiResponse; /* Version 2 Class */ //@Path("/v{version: [0-9]+}/keyspaces") @@ -90,7 +97,7 @@ public class RestMusicDataAPI { * (e.g. if the full version is 1.24.5, X-minorVersion = "24") - Is optional for the client on * request; however, this header should be provided if the client needs to take advantage of * MINOR incremented version functionality - Is mandatory for the server on response - * + * *** X-patchVersion *** - Used only to communicate a PATCH version in a response for * troubleshooting purposes only, and will not be provided by the client on request - This will * be the latest PATCH version of the MINOR requested by the client, or the latest PATCH version @@ -110,7 +117,9 @@ public class RestMusicDataAPI { private static final String XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final String VERSION = "v2"; - + // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist. + private static final boolean KEYSPACE_ACTIVE = false; + private class RowIdentifier { public String primarKeyValue; public StringBuilder rowIdString; @@ -129,7 +138,7 @@ public class RestMusicDataAPI { /** * Create Keyspace REST - * + * * @param kspObject * @param keyspaceName * @return @@ -137,7 +146,7 @@ public class RestMusicDataAPI { */ @POST @Path("/{name}") - @ApiOperation(value = "Create Keyspace", response = String.class) + @ApiOperation(value = "Create Keyspace", response = String.class,hidden = true) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) //public Map createKeySpace( @@ -145,122 +154,142 @@ public class RestMusicDataAPI { @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, JsonKeySpace kspObject, @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) { - ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map 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 has an error. verifyOnboarding may have failed silently", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); - } - if(kspObject == null || kspObject.getReplicationInfo() == null) { - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - - try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, - "createKeySpace"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap()).build(); - } - String newAid = null; - if (!authMap.isEmpty()) { - if (authMap.containsKey("aid")) { - newAid = (String) authMap.get("aid"); - } else { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + 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(); } - } - - String consistency = MusicUtil.EVENTUAL;// for now this needs only - // eventual consistency - - PreparedQueryObject queryObject = new PreparedQueryObject(); - 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); - - } - queryObject.appendQueryString( - "CREATE KEYSPACE " + keyspaceName + " WITH replication = " + repString); - if (kspObject.getDurabilityOfWrites() != null) { + if(kspObject == null || kspObject.getReplicationInfo() == null) { + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } + + + try { + authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, + "createKeySpace"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap()).build(); + } + String newAid = null; + if (!authMap.isEmpty()) { + if (authMap.containsKey("aid")) { + newAid = (String) authMap.get("aid"); + } else { + logger.error(EELFLoggerDelegate.errorLogger,String.valueOf(authMap.get("Exception")), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + } + } + + String consistency = MusicUtil.EVENTUAL;// for now this needs only + // eventual consistency + + PreparedQueryObject queryObject = new PreparedQueryObject(); + 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); + + } queryObject.appendQueryString( - " AND durable_writes = " + kspObject.getDurabilityOfWrites()); - } - - queryObject.appendQueryString(";"); - long end = System.currentTimeMillis(); - logger.info(EELFLoggerDelegate.applicationLogger, - "Time taken for setting up query in create keyspace:" + (end - start)); - - ResultType result = ResultType.FAILURE; - try { - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); - logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); - } catch ( MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build(); - } - - 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); + long end = System.currentTimeMillis(); + logger.info(EELFLoggerDelegate.applicationLogger, + "Time taken for setting up query in create keyspace:" + (end - start)); + + ResultType result = ResultType.FAILURE; + try { + result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result); + } catch ( MusicServiceException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build(); + } + + 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); + } + + try { + boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns)); + String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString( + "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + CachingUtil.updateMusicCache(keyspaceName, ns); + CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); + MusicCore.eventualPut(queryObject); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } + + return 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(); } - - try { - boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns)); - String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt()); - queryObject = new PreparedQueryObject(); - queryObject.appendQueryString( - "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " - + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); - CachingUtil.updateMusicCache(keyspaceName, ns); - CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd); - MusicCore.eventualPut(queryObject); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); - return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build(); } /** - * + * * @param kspObject * @param keyspaceName * @return @@ -268,71 +297,84 @@ public class RestMusicDataAPI { */ @DELETE @Path("/{name}") - @ApiOperation(value = "Delete Keyspace", response = String.class) + @ApiOperation(value = "Delete Keyspace", response = String.class,hidden=true) @Produces(MediaType.APPLICATION_JSON) - //public Map dropKeySpace( public Response dropKeySpace( @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicCore.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - return response.status(Status.UNAUTHORIZED).entity(authMap).build(); - } - - String consistency = MusicUtil.EVENTUAL;// for now this needs only - // eventual - // consistency - String appName = CachingUtil.getAppName(keyspaceName); - String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName); - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - Row row = MusicCore.get(pQuery).one(); - long count = row.getLong(0); - - if (count == 0) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build(); - // Admin Functions: - } else if (count == 1) { - pQuery = new PreparedQueryObject(); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); + logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); + if ( KEYSPACE_ACTIVE ) { + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map authMap = MusicAuthentication.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace"); + if (authMap.containsKey("aid")) + authMap.remove("aid"); + 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(); + } + + 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 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(); } - - 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(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build(); } /** - * + * * @param tableObj * @param version * @param keyspace @@ -342,31 +384,41 @@ public class RestMusicDataAPI { * @throws Exception */ @POST - @Path("/{keyspace}/tables/{tablename}") + @Path("/{keyspace: .*}/tables/{tablename: .*}") @ApiOperation(value = "Create Table", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - //public Map createTable( + @ApiResponses(value={ + @ApiResponse(code= 400, message = "Will return JSON response with message"), + @ApiResponse(code= 401, message = "Unautorized User") + }) public Response createTable( @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + if((keyspace == null || keyspace == null) || (tablename.isEmpty() || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "createTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String consistency = MusicUtil.EVENTUAL; @@ -389,19 +441,19 @@ public class RestMusicDataAPI { for (Map.Entry entry : fields.entrySet()) { if (entry.getKey().equals("PRIMARY KEY")) { primaryKey = entry.getValue(); // replaces primaryKey - primaryKey.trim(); + primaryKey = primaryKey.trim(); } else { if (counter == 0 ) fieldsString.append("" + entry.getKey() + " " + entry.getValue() + ""); - else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); + else fieldsString.append("," + entry.getKey() + " " + entry.getValue() + ""); } - if (counter != (fields.size() - 1) ) { - - counter = counter + 1; - } else { + if (counter != (fields.size() - 1) ) { + + counter = counter + 1; + } else { if((primaryKey != null) && (partitionKey == null)) { - primaryKey.trim(); + primaryKey = primaryKey.trim(); int count1 = StringUtils.countMatches(primaryKey, ')'); int count2 = StringUtils.countMatches(primaryKey, '('); if (count1 != count2) { @@ -410,44 +462,43 @@ public class RestMusicDataAPI { .toMap()).build(); } - if ( primaryKey.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(")") +1) == primaryKey.length() ) ) + 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=""; + if (primaryKey.contains(",") ) { + partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusterKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index + clusterKey=clusterKey.replaceAll("[)]+", ""); + } else { + partitionKey=primaryKey; + partitionKey=partitionKey.replaceAll("[\\)]+",""); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + clusterKey=""; } } else { // not null and has ) before the last char - partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); - partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey.trim(); - clusterKey= primaryKey.substring(primaryKey.indexOf(')')); - clusterKey=clusterKey.replaceAll("[\\(]+",""); - clusterKey=clusterKey.replaceAll("[\\)]+",""); - clusterKey.trim(); - if (clusterKey.indexOf(",") == 0) clusterKey=clusterKey.substring(1); - clusterKey.trim(); - if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) - - } + partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); + partitionKey=partitionKey.replaceAll("[\\(]+",""); + partitionKey = partitionKey.trim(); + clusterKey= primaryKey.substring(primaryKey.indexOf(')')); + clusterKey=clusterKey.replaceAll("[\\(]+",""); + clusterKey=clusterKey.replaceAll("[\\)]+",""); + clusterKey = clusterKey.trim(); + if (clusterKey.indexOf(',') == 0) clusterKey=clusterKey.substring(1); + clusterKey = clusterKey.trim(); + if (clusterKey.equals(",") ) clusterKey=""; // print error if needed ( ... ),) + } if (!(partitionKey.isEmpty() || clusterKey.isEmpty()) && (partitionKey.equalsIgnoreCase(clusterKey) || clusterKey.contains(partitionKey) || partitionKey.contains(clusterKey)) ) { - logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey ); - return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( + logger.error("DataAPI createTable partition/cluster key ERROR: partitionKey="+partitionKey+", clusterKey=" + clusterKey + " and primary key=" + primaryKey ); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError( "Create Table primary key error: clusterKey(" + clusterKey + ") equals/contains/overlaps partitionKey(" +partitionKey+ ") of" + " primary key=" + primaryKey) - .toMap()).build(); + .toMap()).build(); - } + } if (partitionKey.isEmpty() ) primaryKey=""; else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")"; @@ -504,38 +555,39 @@ public class RestMusicDataAPI { } } - 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(); - } - // add validation for column names in cluster key - } + 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 + } - 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); + if (!(clusterKey.isEmpty())) { + clusteringOrder = "CLUSTERING ORDER BY (" +clusteringOrder +")"; + //cjc check if propertiesString.length() >0 instead propertiesMap + if (propertiesMap != null) { + propertiesString.append(" AND "+ clusteringOrder); + } else { + propertiesString.append(clusteringOrder); + } } else { logger.warn("Skipping clustering order=("+clusteringOrder+ ") since clustering key is empty "); } } //if non empty - - queryObject.appendQueryString( - "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); + + queryObject.appendQueryString( + "CREATE TABLE " + keyspace + "." + tablename + " " + fieldsString); if (propertiesString != null && propertiesString.length()>0 ) @@ -543,8 +595,7 @@ public class RestMusicDataAPI { queryObject.appendQueryString(";"); ResultType result = ResultType.FAILURE; try { - //logger.info("cjc query="+queryObject.getQuery()); - result = MusicCore.nonKeyRelatedPut(queryObject, consistency); + 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); @@ -553,11 +604,14 @@ public class RestMusicDataAPI { if ( result.equals(ResultType.FAILURE) ) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Creating Table " + tablename).toMap()).build(); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("TableName " + tablename + " Created under keyspace " + keyspace).toMap()).build(); + 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"); + } } /** - * + * * @param keyspace * @param tablename * @param fieldName @@ -565,30 +619,36 @@ public class RestMusicDataAPI { * @throws Exception */ @POST - @Path("/{keyspace}/tables/{tablename}/index/{field}") + @Path("/{keyspace: .*}/tables/{tablename: .*}/index/{field: .*}") @ApiOperation(value = "Create Index", response = String.class) @Produces(MediaType.APPLICATION_JSON) public Response createIndex( @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename, @ApiParam(value = "Field Name",required = true) @PathParam("field") String fieldName, @Context UriInfo info) throws Exception { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "createIndex"); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty()) || (fieldName == null || fieldName.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace,aid, "createIndex"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); response.status(Status.UNAUTHORIZED); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } @@ -599,7 +659,7 @@ public class RestMusicDataAPI { PreparedQueryObject query = new PreparedQueryObject(); query.appendQueryString("Create index if not exists " + indexName + " on " + keyspace + "." + tablename + " (" + fieldName + ");"); - + ResultType result = ResultType.FAILURE; try { result = MusicCore.nonKeyRelatedPut(query, "eventual"); @@ -613,10 +673,13 @@ public class RestMusicDataAPI { } else { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Unknown Error in create index.").toMap()).build(); } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param insObj * @param keyspace * @param tablename @@ -624,7 +687,7 @@ public class RestMusicDataAPI { * @throws Exception */ @POST - @Path("/{keyspace}/tables/{tablename}/rows") + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") @ApiOperation(value = "Insert Into Table", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -632,7 +695,7 @@ public class RestMusicDataAPI { @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version",required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, JsonInsert insObj, @@ -640,24 +703,30 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename) { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map authMap = null; - + try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable"); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } @@ -665,7 +734,7 @@ public class RestMusicDataAPI { PreparedQueryObject queryObject = new PreparedQueryObject(); TableMetadata tableInfo = null; try { - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); if(tableInfo == null) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build(); } @@ -704,7 +773,7 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); } valueString.append("?"); - + queryObject.addValue(formattedValue); if (counter == valuesMap.size() - 1) { @@ -716,14 +785,14 @@ public class RestMusicDataAPI { } counter = counter + 1; } - + //blobs.. 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(), ","); - } + 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())) { @@ -734,12 +803,12 @@ public class RestMusicDataAPI { DataType colType = tableInfo.getColumn(entry.getKey()).getType(); ByteBuffer formattedValue = null; - + if(colType.toString().toLowerCase().contains("blob")) - formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); - + formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); + valueString.append("?"); - + queryObject.addValue(formattedValue); counter = counter + 1; /*if (counter == valuesMap.size() - 1) { @@ -750,15 +819,15 @@ public class RestMusicDataAPI { valueString.append(","); //} } } - + if(primaryKey == null || primaryKey.length() <= 0) { logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName ); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap()).build(); } fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")"); - valueString.replace(valueString.length()-1, valueString.length(), ")"); - + valueString.replace(valueString.length()-1, valueString.length(), ")"); + queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " " + fieldsString + " VALUES " + valueString); @@ -788,6 +857,13 @@ public class RestMusicDataAPI { ReturnType result = null; String consistency = insObj.getConsistencyInfo().get("type"); + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && insObj.getConsistencyInfo().get("consistency") != null) { + if(MusicUtil.isValidConsistency(insObj.getConsistencyInfo().get("consistency"))) + queryObject.setConsistency(insObj.getConsistencyInfo().get("consistency")); + else + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build(); + } + queryObject.setOperation("insert"); try { if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) { result = MusicCore.eventualPut(queryObject); @@ -801,6 +877,7 @@ public class RestMusicDataAPI { } result = MusicCore.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null); } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { + result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null); } @@ -812,25 +889,32 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } - + if (result==null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); + }else if(result.getResult() == ResultType.FAILURE) { + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result.getResult()).setError(result.getMessage()).toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param insObj * @param keyspace * @param tablename * @param info * @return + * @throws MusicServiceException + * @throws MusicQueryException * @throws Exception */ @PUT - @Path("/{keyspace}/tables/{tablename}/rows") + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") @ApiOperation(value = "Update Table", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -841,7 +925,7 @@ public class RestMusicDataAPI { required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @@ -850,15 +934,21 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) { + @Context UriInfo info) throws MusicQueryException, MusicServiceException { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map authMap; try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "updateTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -867,13 +957,14 @@ public class RestMusicDataAPI { if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } long startTime = System.currentTimeMillis(); String operationId = UUID.randomUUID().toString();// just for infoging // purposes. String consistency = updateObj.getConsistencyInfo().get("type"); + logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency + " update-" + operationId + "-------------------------"); // obtain the field value pairs of the update @@ -883,13 +974,13 @@ public class RestMusicDataAPI { TableMetadata tableInfo; try { - tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); } catch (MusicServiceException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } if (tableInfo == null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + 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(); @@ -969,12 +1060,19 @@ public class RestMusicDataAPI { selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new MusicCore.Condition(updateObj.getConditions(), selectQuery); + conditionInfo = new Condition(updateObj.getConditions(), selectQuery); } ReturnType operationResult = null; long jsonParseCompletionTime = System.currentTimeMillis(); + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && updateObj.getConsistencyInfo().get("consistency") != null) { + if(MusicUtil.isValidConsistency(updateObj.getConsistencyInfo().get("consistency"))) + queryObject.setConsistency(updateObj.getConsistencyInfo().get("consistency")); + else + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build(); + } + queryObject.setOperation("update"); if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) operationResult = MusicCore.eventualPut(queryObject); else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) { @@ -1004,6 +1102,8 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } + }else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { + operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue); } long actualUpdateCompletionTime = System.currentTimeMillis(); @@ -1019,7 +1119,7 @@ public class RestMusicDataAPI { timingString = timingString + lockManagementTime; } logger.info(EELFLoggerDelegate.applicationLogger, timingString); - + if (operationResult==null) { logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); @@ -1030,20 +1130,24 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(operationResult.getResult()).setError(operationResult.getMessage()).toMap()).build(); } - + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param delObj * @param keyspace * @param tablename * @param info * @return + * @throws MusicServiceException + * @throws MusicQueryException * @throws Exception */ @DELETE - @Path("/{keyspace}/tables/{tablename}/rows") + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") @ApiOperation(value = "Delete From table", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -1054,7 +1158,7 @@ public class RestMusicDataAPI { required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @@ -1063,15 +1167,21 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) { + @Context UriInfo info) throws MusicQueryException, MusicServiceException { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map authMap = null; try { - authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, + authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "deleteFromTable"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); @@ -1080,11 +1190,11 @@ public class RestMusicDataAPI { if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } if(delObj == null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); + logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build(); } PreparedQueryObject queryObject = new PreparedQueryObject(); @@ -1135,12 +1245,22 @@ public class RestMusicDataAPI { selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";"); selectQuery.addValue(rowId.primarKeyValue); - conditionInfo = new MusicCore.Condition(delObj.getConditions(), selectQuery); + conditionInfo = new Condition(delObj.getConditions(), selectQuery); } String consistency = delObj.getConsistencyInfo().get("type"); + + if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && delObj.getConsistencyInfo().get("consistency")!=null) { + + if(MusicUtil.isValidConsistency(delObj.getConsistencyInfo().get("consistency"))) + queryObject.setConsistency(delObj.getConsistencyInfo().get("consistency")); + else + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Invalid Consistency type").toMap()).build(); + } + ReturnType operationResult = null; + queryObject.setOperation("delete"); try { if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) operationResult = MusicCore.eventualPut(queryObject); @@ -1161,6 +1281,9 @@ public class RestMusicDataAPI { else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); + }else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { + + operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue); } } catch (MusicLockingException e) { logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); @@ -1168,26 +1291,29 @@ public class RestMusicDataAPI { .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); } if (operationResult==null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,"Null result - Please Contact admin", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Null result - Please Contact admin").toMap()).build(); } if (operationResult.getResult().equals(ResultType.SUCCESS)) { return response.status(Status.OK).entity(new JsonResponse(operationResult.getResult()).setMessage(operationResult.getMessage()).toMap()).build(); } else { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,operationResult.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build(); } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param tabObj * @param keyspace * @param tablename * @throws Exception */ @DELETE - @Path("/{keyspace}/tables/{tablename}") + @Path("/{keyspace: .*}/tables/{tablename: .*}") @ApiOperation(value = "Drop Table", response = String.class) @Produces(MediaType.APPLICATION_JSON) public Response dropTable( @@ -1197,7 +1323,7 @@ public class RestMusicDataAPI { required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @@ -1205,17 +1331,23 @@ public class RestMusicDataAPI { required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename) throws Exception { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map authMap = - MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "dropTable"); + MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "dropTable"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String consistency = "eventual";// for now this needs only eventual @@ -1228,11 +1360,13 @@ public class RestMusicDataAPI { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } - + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param selObj * @param keyspace * @param tablename @@ -1240,7 +1374,7 @@ public class RestMusicDataAPI { * @return */ @PUT - @Path("/{keyspace}/tables/{tablename}/rows/criticalget") + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows/criticalget") @ApiOperation(value = "Select Critical", response = Map.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -1251,7 +1385,7 @@ public class RestMusicDataAPI { required = false) @HeaderParam(XMINORVERSION) String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @@ -1261,16 +1395,22 @@ public class RestMusicDataAPI { @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, @Context UriInfo info) throws Exception { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical"); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"Error while authentication... ", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } String lockId = selObj.getConsistencyInfo().get("lockId"); @@ -1303,20 +1443,22 @@ public class RestMusicDataAPI { } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject); } - + else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) { results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject); } if(results!=null && results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build(); - + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param keyspace * @param tablename * @param info @@ -1324,36 +1466,42 @@ public class RestMusicDataAPI { * @throws Exception */ @GET - @Path("/{keyspace}/tables/{tablename}/rows") + @Path("/{keyspace: .*}/tables/{tablename: .*}/rows") @ApiOperation(value = "Select All or Select Specific", response = Map.class) @Produces(MediaType.APPLICATION_JSON) public Response select( - @ApiParam(value = "Major Version", - required = true) @PathParam("version") String version, - @ApiParam(value = "Minor Version", - required = false) @HeaderParam(XMINORVERSION) String minorVersion, - @ApiParam(value = "Patch Version", - required = false) @HeaderParam(XPATCHVERSION) String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", - required = true) @HeaderParam(NS) String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - @ApiParam(value = "Keyspace Name", - required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", - required = true) @PathParam("tablename") String tablename, - @Context UriInfo info) throws Exception { + @ApiParam(value = "Major Version", + required = true) @PathParam("version") String version, + @ApiParam(value = "Minor Version", + required = false) @HeaderParam(XMINORVERSION) String minorVersion, + @ApiParam(value = "Patch Version", + required = false) @HeaderParam(XPATCHVERSION) String patchVersion, + @ApiParam(value = "AID", required = false) @HeaderParam("aid") String aid, + @ApiParam(value = "Application namespace", + required = true) @HeaderParam(NS) String ns, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "Keyspace Name", + required = true) @PathParam("keyspace") String keyspace, + @ApiParam(value = "Table Name", + required = true) @PathParam("tablename") String tablename, + @Context UriInfo info) throws Exception { + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + if((keyspace == null || keyspace.isEmpty()) || (tablename == null || tablename.isEmpty())){ + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) + .setError("one or more path parameters are not set, please check and try again") + .toMap()).build(); + } + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); Map authMap = - MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "select"); + MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "select"); if (authMap.containsKey("aid")) authMap.remove("aid"); if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } PreparedQueryObject queryObject = new PreparedQueryObject(); @@ -1366,7 +1514,7 @@ public class RestMusicDataAPI { queryObject = selectSpecificQuery(VERSION, minorVersion, patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } } @@ -1374,18 +1522,20 @@ public class RestMusicDataAPI { try { ResultSet results = MusicCore.get(queryObject); if(results.getAvailableWithoutFetching() >0) { - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).setError("No data found").toMap()).build(); + return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build(); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } - + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** - * + * * @param keyspace * @param tablename * @param info @@ -1415,7 +1565,7 @@ public class RestMusicDataAPI { } /** - * + * * @param keyspace * @param tablename * @param rowParams @@ -1428,7 +1578,7 @@ public class RestMusicDataAPI { throws MusicServiceException { StringBuilder rowSpec = new StringBuilder(); int counter = 0; - TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename); + TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); if (tableInfo == null) { logger.error(EELFLoggerDelegate.errorLogger, "Table information not found. Please check input for table name= " diff --git a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java index f6dc4e57..a9b4c7af 100644 --- a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java @@ -21,6 +21,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.HashMap; @@ -54,81 +55,81 @@ import io.swagger.annotations.ApiParam; -@Path("/v{version: [0-9]+}/service") +@Path("/v2/service") @Api(value="Healthcheck Api") public class RestMusicHealthCheckAPI { - - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - private static final String activeStatus = "ACTIVE"; - - @GET - @Path("/pingCassandra/{consistency}") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response cassandraStatus(@Context HttpServletResponse response, @ApiParam(value = "Consistency level", + + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + private static final String ACTIVE_STATUS = "ACTIVE"; + + @GET + @Path("/pingCassandra/{consistency}") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response cassandraStatus(@Context HttpServletResponse response, @ApiParam(value = "Consistency level", required = true) @PathParam("consistency") String consistency) { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra"); - - Map resultMap = new HashMap<>(); - if(ConsistencyLevel.valueOf(consistency) == null) { - resultMap.put("INVALID", "Consistency level is invalid..."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - MusicHealthCheck cassHealthCheck = new MusicHealthCheck(); - String status = cassHealthCheck.getCassandraStatus(consistency); - if(status.equals(activeStatus)) { - resultMap.put(activeStatus, "Cassandra Running and Listening to requests"); - return Response.status(Status.OK).entity(resultMap).build(); - } else { - resultMap.put("INACTIVE", "One or more nodes in the Cluster is/are down or not responding."); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - - - - } - - @GET - @Path("/pingZookeeper") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response ZKStatus(@Context HttpServletResponse response) { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper"); - Map resultMap = new HashMap<>(); - MusicHealthCheck ZKHealthCheck = new MusicHealthCheck(); - String status = ZKHealthCheck.getZookeeperStatus(); - if(status.equals(activeStatus)) { - resultMap.put(activeStatus, "Zookeeper is Active and Running"); - return Response.status(Status.OK).entity(resultMap).build(); - }else { - resultMap.put("INACTIVE", "Zookeeper is not responding"); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - } - - @GET - @Path("/musicHealthCheck") - @ApiOperation(value = "Get Health Status", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Response musicHealthCheck() { - logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for Health Check status for MUSIC"); - Map resultMap = new HashMap<>(); - MusicHealthCheck healthCheck = new MusicHealthCheck(); - String status = healthCheck.getZookeeperStatus(); - if(status.equals(activeStatus)) { - resultMap.put("ZooKeeper", "Active"); - }else { - resultMap.put("ZooKeeper", "Inactive"); - } - status = healthCheck.getCassandraStatus(ConsistencyLevel.ANY.toString()); - if(status.equals(activeStatus)) { - resultMap.put("Cassandra", "Active"); - } else { - resultMap.put("Cassandra", "Inactive"); - } - resultMap.put("MUSIC", "Active"); - return Response.status(Status.OK).entity(resultMap).build(); - } + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra"); + + Map resultMap = new HashMap<>(); + if(ConsistencyLevel.valueOf(consistency) == null) { + resultMap.put("INVALID", "Consistency level is invalid..."); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + MusicHealthCheck cassHealthCheck = new MusicHealthCheck(); + String status = cassHealthCheck.getCassandraStatus(consistency); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put(ACTIVE_STATUS, "Cassandra Running and Listening to requests"); + return Response.status(Status.OK).entity(resultMap).build(); + } else { + resultMap.put("INACTIVE", "One or more nodes in the Cluster is/are down or not responding."); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + + + + } + + @GET + @Path("/pingZookeeper") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response ZKStatus(@Context HttpServletResponse response) { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper"); + Map resultMap = new HashMap<>(); + MusicHealthCheck ZKHealthCheck = new MusicHealthCheck(); + String status = ZKHealthCheck.getZookeeperStatus(); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put(ACTIVE_STATUS, "Zookeeper is Active and Running"); + return Response.status(Status.OK).entity(resultMap).build(); + }else { + resultMap.put("INACTIVE", "Zookeeper is not responding"); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + } + + @GET + @Path("/musicHealthCheck") + @ApiOperation(value = "Get Health Status", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Response musicHealthCheck() { + logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for Health Check status for MUSIC"); + Map resultMap = new HashMap<>(); + MusicHealthCheck healthCheck = new MusicHealthCheck(); + String status = healthCheck.getZookeeperStatus(); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put("ZooKeeper", "Active"); + }else { + resultMap.put("ZooKeeper", "Inactive"); + } + status = healthCheck.getCassandraStatus(ConsistencyLevel.ANY.toString()); + if(status.equals(ACTIVE_STATUS)) { + resultMap.put("Cassandra", "Active"); + } else { + resultMap.put("Cassandra", "Inactive"); + } + resultMap.put("MUSIC", "Active"); + return Response.status(Status.OK).entity(resultMap).build(); + } } diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 70583baa..0bb2368a 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -19,6 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.Map; @@ -35,12 +36,14 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; + +import org.onap.music.authentication.MusicAuthentication; import org.onap.music.datastore.jsonobjects.JsonLeasedLock; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.lockingservice.cassandra.MusicLockState; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; @@ -85,24 +88,28 @@ public class RestMusicLocksAPI { @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "createLockReference"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } ResultType status = ResultType.SUCCESS; String lockId = MusicCore.createLockReference(lockName); @@ -113,6 +120,9 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError("Lock Id is null").toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(status).setLock(lockId).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** @@ -137,24 +147,28 @@ public class RestMusicLocksAPI { @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "accquireLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } try { String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); @@ -169,6 +183,9 @@ public class RestMusicLocksAPI { logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap()).build(); } + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } @@ -187,25 +204,29 @@ public class RestMusicLocksAPI { @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "accquireLockWithLease"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); @@ -217,6 +238,9 @@ public class RestMusicLocksAPI { return response.entity(new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName) .setMessage(lockLeaseStatus.getMessage()) .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } @@ -234,24 +258,28 @@ public class RestMusicLocksAPI { @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "currentLockHolder"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } String who = MusicCore.whoseTurnIsIt(lockName); ResultType status = ResultType.SUCCESS; @@ -263,6 +291,9 @@ public class RestMusicLocksAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); } return response.status(Status.OK).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } @GET @@ -278,43 +309,61 @@ public class RestMusicLocksAPI { @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", - required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "userId", - required = true) @HeaderParam("userId") String userId, - @ApiParam(value = "Password", - required = true) @HeaderParam("password") String password) throws Exception{ + required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, - "currentLockState"); - + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + resultMap.remove("keyspace"); + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, + "currentLockHolder"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - MusicLockState mls = MusicCore.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(); + String who = MusicCore.whoseTurnIsIt(lockName); + ResultType status = ResultType.SUCCESS; + String error = ""; + if ( who == null ) { + status = ResultType.FAILURE; + error = "There was a problem getting the lock holder"; + logger.error(EELFLoggerDelegate.errorLogger,"There was a problem getting the lock holder", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError(error).setLock(lockName).setLockHolder(who).toMap()).build(); + } + 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(); +// } + } /** @@ -337,24 +386,28 @@ public class RestMusicLocksAPI { @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockId); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "unLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } boolean voluntaryRelease = true; MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); @@ -376,6 +429,9 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); } return response.entity(returnMap).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } /** @@ -394,31 +450,38 @@ public class RestMusicLocksAPI { @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns) throws Exception{ + try { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); Map resultMap = MusicCore.validateLock(lockName); - if (resultMap.containsKey("Exception")) { + if (resultMap.containsKey("Error")) { logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); + EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid, + resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, "deleteLock"); if (resultMap.containsKey("aid")) resultMap.remove("aid"); if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - return response.status(Status.BAD_REQUEST).entity(resultMap).build(); + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); + response.status(Status.UNAUTHORIZED); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } try{ - MusicCore.deleteLock(lockName); + MusicCore.deleteLock(lockName); }catch (Exception e) { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } + } return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).toMap()).build(); + } finally { + EELFLoggerDelegate.mdcRemove("keyspace"); + } } } diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index a883534e..4164f27f 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -1,21 +1,25 @@ /* - * ============LICENSE_START========================================== org.onap.music - * =================================================================== Copyright (c) 2017 AT&T - * Intellectual Property ===================================================================Modifications Copyright (c) 2018 IBM - * Intellectual Property =================================================================== * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.HashMap; @@ -45,6 +49,7 @@ import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.apache.commons.lang3.StringUtils; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import com.datastax.driver.core.ResultSet; import org.onap.music.exceptions.MusicServiceException; @@ -52,13 +57,15 @@ 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.onap.music.service.impl.MusicZKCore; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; - +// import io.swagger.models.Response; // @Path("/v{version: [0-9]+}/priorityq/") -@Path("{version}/priorityq/") +@Path("/v2/priorityq/") @Api(value = "Q Api") public class RestMusicQAPI { @@ -74,37 +81,29 @@ public class RestMusicQAPI { */ @POST - @Path("/keyspaces/{keyspace}/{qname}") // is it same as tablename?down + @Path("/keyspaces/{keyspace}/{qname}") // qname same as tablename @ApiOperation(value = "Create Q", response = String.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - - /* old - @POST - @Path("/keyspaces/{keyspace}/{qname}") - @ApiOperation(value = "", response = Void.class) - @Consumes(MediaType.APPLICATION_JSON) - */ public Response createQ( - // public Map createQ( @ApiParam(value = "Major Version", required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version", required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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 { - + //logger.info(logger, "cjc before start in q 1** major version=" + version); ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); Map fields = tableObj.getFields(); - if (fields == null) { + if (fields == null) { // || (!fields.containsKey("order")) ){ logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST) @@ -151,19 +150,19 @@ public class RestMusicQAPI { } if ((primaryKey!=null) && (partitionKey == null)) { - primaryKey.trim(); - int count1 = StringUtils.countMatches(primaryKey, ')'); - int count2 = StringUtils.countMatches(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) .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.indexOf('(') == -1 || ( count2 == 1 && (primaryKey.lastIndexOf(')') +1) == primaryKey.length() ) ) { if (primaryKey.contains(",") ) { - partitionKey= primaryKey.substring(0,primaryKey.indexOf(",")); + partitionKey= primaryKey.substring(0,primaryKey.indexOf(',')); partitionKey=partitionKey.replaceAll("[\\(]+",""); clusteringKey=primaryKey.substring(primaryKey.indexOf(',')+1); // make sure index clusteringKey=clusteringKey.replaceAll("[)]+", ""); @@ -176,18 +175,14 @@ public class RestMusicQAPI { } else { partitionKey= primaryKey.substring(0,primaryKey.indexOf(')')); partitionKey=partitionKey.replaceAll("[\\(]+",""); - partitionKey.trim(); + partitionKey = partitionKey.trim(); clusteringKey= primaryKey.substring(primaryKey.indexOf(')')); clusteringKey=clusteringKey.replaceAll("[\\(]+",""); clusteringKey=clusteringKey.replaceAll("[\\)]+",""); - clusteringKey.trim(); - if (clusteringKey.indexOf(",") == 0) { - clusteringKey=clusteringKey.substring(1); - } - clusteringKey.trim(); - if (",".equals(clusteringKey) ) { - clusteringKey=""; // print error if needed ( ... ),) - } + clusteringKey = clusteringKey.trim(); + if (clusteringKey.indexOf(',') == 0) clusteringKey=clusteringKey.substring(1); + clusteringKey = clusteringKey.trim(); + if (clusteringKey.equals(",") ) clusteringKey=""; // print error if needed ( ... ),) } } @@ -240,16 +235,13 @@ public class RestMusicQAPI { required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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) throws Exception { - - // check valuesMap.isEmpty and proceed - // response.addHeader(xLatestVersion, MusicUtil.getVersion()); ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (insObj.getValues().isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, @@ -281,13 +273,13 @@ public class RestMusicQAPI { required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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) { + @Context UriInfo info) throws Exception { ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (updateObj.getValues().isEmpty()) { @@ -327,15 +319,13 @@ public class RestMusicQAPI { required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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 = "userId", required = true) @HeaderParam("userId") String userId, - // @ApiParam(value = "Password", required = true) @HeaderParam("password") String password, JsonDelete delObj, @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) { + @Context UriInfo info) throws Exception { // added checking as per RestMusicDataAPI ResponseBuilder response = MusicUtil.buildVersionResponse(version, minorVersion, patchVersion); if (delObj == null) { @@ -368,7 +358,7 @@ public class RestMusicQAPI { required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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, @@ -390,7 +380,6 @@ public class RestMusicQAPI { queryObject = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST) @@ -402,9 +391,8 @@ public class RestMusicQAPI { try { ResultSet results = MusicCore.get(queryObject); return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS) - .setDataResult(MusicCore.marshallResults(results)).toMap()).build(); + .setDataResult(MusicDataStoreHandle.marshallResults(results)).toMap()).build(); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex); logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST) @@ -428,20 +416,15 @@ public class RestMusicQAPI { @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 = true) @HeaderParam("aid") String aid, - @ApiParam(value = "Application namespace", required = true) @HeaderParam("ns") String ns, - @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, - // @ApiParam(value = "userId", required = true) @HeaderParam("userId") String userId, - //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password, - @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, - @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename, - @Context UriInfo info) throws Exception { - + @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) } @@ -463,17 +446,13 @@ public class RestMusicQAPI { required = false) @HeaderParam("X-minorVersion") String minorVersion, @ApiParam(value = "Patch Version", required = false) @HeaderParam("X-patchVersion") String patchVersion, - @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid, + @ApiParam(value = "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 = "userId", required = true) @HeaderParam("userId") String userId, - //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password, - // cjc JsonTable tabObj, @ApiParam(value = "Key Space", required = true) @PathParam("keyspace") String keyspace, @ApiParam(value = "Table Name", required = true) @PathParam("qname") String tablename) throws Exception { - return new RestMusicDataAPI().dropTable(version, minorVersion, patchVersion, aid, ns, authorization, keyspace, tablename); } } diff --git a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java index 287fa176..6d973acb 100644 --- a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicTestAPI.java @@ -19,6 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.HashMap; @@ -41,27 +42,27 @@ import io.swagger.annotations.ApiOperation; @Path("/v{version: [0-9]+}/test") @Api(value="Test Api") public class RestMusicTestAPI { - - @SuppressWarnings("unused") + + @SuppressWarnings("unused") private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class); - /** - * Returns a test JSON. This will confirm that REST is working. - * @return - */ - @GET - @ApiOperation(value = "Get Test", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - public Map> simpleTests( - @Context HttpServletResponse response) { - response.addHeader("X-latestVersion",MusicUtil.getVersion()); - Map> testMap = new HashMap<>(); - for(int i=0; i < 3; i++){ - HashMap innerMap = new HashMap<>(); - innerMap.put(i+"", i+1+""); - innerMap.put(i+1+"", i+2+""); - testMap.put(i+"", innerMap); - } - return testMap; - } + /** + * Returns a test JSON. This will confirm that REST is working. + * @return + */ + @GET + @ApiOperation(value = "Get Test", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + public Map> simpleTests( + @Context HttpServletResponse response) { + response.addHeader("X-latestVersion",MusicUtil.getVersion()); + Map> testMap = new HashMap<>(); + for(int i=0; i < 3; i++){ + HashMap innerMap = new HashMap<>(); + innerMap.put("Music Version",MusicUtil.getVersion()); + innerMap.put(i+1+"", i+2+""); + testMap.put(i+"", innerMap); + } + return testMap; + } } diff --git a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java index b9754f61..74b8e5dd 100644 --- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java @@ -19,6 +19,7 @@ * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; import java.util.Map; @@ -35,6 +36,9 @@ import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -43,18 +47,18 @@ import io.swagger.annotations.ApiOperation; @Api(value="Version Api") public class RestMusicVersionAPI { - private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); - - /** - * Get the version of MUSIC - * @return - */ - @GET - @ApiOperation(value = "Get Version", response = Map.class) - @Produces(MediaType.APPLICATION_JSON) - 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(); - } + private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class); + + /** + * Get the version of MUSIC + * @return + */ + @GET + @ApiOperation(value = "Get Version", response = Map.class) + @Produces(MediaType.APPLICATION_JSON) + 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(); + } } \ No newline at end of file -- cgit 1.2.3-korg