X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Forg%2Fonap%2Fmusic%2Frest%2FRestMusicAdminAPI.java;h=664747f676b2cc8a052812476cd88fa17dcc10f4;hb=d6e7b63cc580e7b3822be61fe92a493ad5e222a3;hp=8e4facd215d274960bfa089917c37f28c7aa5f8e;hpb=b98dd8dffd51f7611fce4d6b7032ef1edeab8bfa;p=music.git diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 8e4facd2..664747f6 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -5,49 +5,39 @@ * Copyright (c) 2017 AT&T Intellectual Property * =================================================================== * Modifications Copyright (C) 2018 IBM. + * Modifications Copyright (c) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ============LICENSE_END============================================= * ==================================================================== */ + package org.onap.music.rest; -import java.nio.ByteBuffer; -import java.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.Arrays; 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,109 +47,122 @@ 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.CachingUtil; +import org.onap.music.authentication.MusicAAFAuthentication; +import org.onap.music.authentication.MusicAuthenticator; +import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.datastore.jsonobjects.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.datastore.jsonobjects.MusicResponse; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.main.CachingUtil; +import org.onap.music.exceptions.MusicServiceException; 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 org.springframework.beans.factory.config.YamlProcessor.ResolutionMethod; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.TableMetadata; -import com.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 com.sun.xml.bind.v2.TODO; 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") -// @Path("/admin") @Api(value = "Admin Api", hidden = true) 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; + + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); + /* * 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()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); - String isAAF = jsonObj.getIsAAF(); String password = jsonObj.getPassword(); - if (appName == null || userId == null || isAAF == null || password == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, + String keyspace_name = jsonObj.getKeyspace(); + + if (appName == null || userId == null || password == null || keyspace_name == null) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); resultMap.put("Exception", "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing."); - return response.status(Status.UNAUTHORIZED).entity(resultMap).build(); + return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( - "select uuid from admin.keyspace_master where application_name = ? allow filtering"); + "select uuid from admin.keyspace_master where application_name = ? and keyspace_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace_name)); ResultSet rs = MusicCore.get(pQuery); if (!rs.all().isEmpty()) { - resultMap.put("Exception", "Application " + appName - + " has already been onboarded. Please 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("Application " + appName + " has already been onboarded. Please contact admin.").toMap()) + .build(); } - + pQuery = new PreparedQueryObject(); - String uuid = CachingUtil.generateUUID(); + String uuid = MusicUtil.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.cboolean(), "False")); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "true")); String returnStr = MusicCore.eventualPut(pQuery).toString(); if (returnStr.contains("Failure")) { - 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); + //CachingUtil.updateisAAFCache(appName, isAAF); resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC."); resultMap.put("Generated AID", uuid); return response.status(Status.OK).entity(resultMap).build(); @@ -171,15 +174,25 @@ 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()); + + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String uuid = jsonObj.getAid(); String isAAF = jsonObj.getIsAAF(); - 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 +228,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,31 +247,45 @@ 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()); + + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String aid = jsonObj.getAid(); PreparedQueryObject pQuery = new PreparedQueryObject(); - String consistency = MusicUtil.EVENTUAL;; + String consistency = MusicUtil.EVENTUAL; if (appName == null && aid == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + logger.error(EELFLoggerDelegate.errorLogger, + "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present"); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } if (aid != null) { - pQuery.appendQueryString( + if (MusicUtil.isKeyspaceActive()) { + pQuery.appendQueryString( "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.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); + 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(); @@ -269,9 +297,11 @@ public class RestMusicAdminAPI { resultMap.put("Success", "Your application has been deleted successfully"); } else { resultMap.put("Exception", - "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); + "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded"); + logger.error(EELFLoggerDelegate.errorLogger, + "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded", + AppMessages.INCORRECTDATA, + ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -287,7 +317,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 +345,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,28 +357,37 @@ 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()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String aid = jsonObj.getAid(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); - String isAAF = jsonObj.getIsAAF(); - String password = jsonObj.getPassword(); + String cassandraKeyspace=jsonObj.getKeyspace(); String consistency = "eventual"; PreparedQueryObject pQuery; - + 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(); } - if (appName == null && userId == null && password == null && isAAF == null) { + if (appName == null || userId == null || cassandraKeyspace == null) { resultMap.put("Exception", "No parameters found to update. Please update atleast one parameter."); - logger.error(EELFLoggerDelegate.errorLogger, "", 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(); } @@ -359,10 +398,10 @@ public class RestMusicAdminAPI { "select uuid from admin.keyspace_master where application_name = ? allow filtering"); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); ResultSet rs = MusicCore.get(pQuery); - if (!rs.all().isEmpty()) { + if (rs.all().isEmpty()) { resultMap.put("Exception", "Application " + appName - + " has already been onboarded. Please contact admin."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST, + + " not found. Please contact admin."); + logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"not found. Please contact admin.", AppMessages.ALREADYEXIST, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(resultMap).build(); } @@ -374,10 +413,8 @@ public class RestMusicAdminAPI { preCql.append(" application_name = ?,"); if (userId != null) preCql.append(" username = ?,"); - if (password != null) - preCql.append(" password = ?,"); - if (isAAF != null) - preCql.append(" is_aaf = ?,"); + if (cassandraKeyspace != null) + preCql.append(" keyspace_name = ?,"); preCql.deleteCharAt(preCql.length() - 1); preCql.append(" WHERE uuid = ? IF EXISTS"); pQuery.appendQueryString(preCql.toString()); @@ -385,10 +422,8 @@ public class RestMusicAdminAPI { pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); if (userId != null) pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - if (password != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt()))); - if (isAAF != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF)); + if (cassandraKeyspace != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), cassandraKeyspace)); pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); @@ -398,7 +433,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 +441,195 @@ public class RestMusicAdminAPI { return response.status(Status.OK).entity(resultMap).build(); } - Client client = Client.create(); - ObjectMapper mapper = new ObjectMapper(); - - @POST - @Path("/callbackOps") + + + //Dashboard related calls + //TODO Make return object Response. + + @GET + @Path("/getall") @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()); + public MusicResponse getall(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws MusicServiceException{ + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "Auth failed for admin"); + return response; } - 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); + + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT * FROM " + "admin" + "." + "keyspace_master" + ";"); + try { + ResultSet results = MusicCore.get(queryObject); + for(Row row : results) { + Application app = new Application(); + 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()); + response.addAppToList(app); } - 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) {} - } - } + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); } + return response; - if(response == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond.."); - return; + } + + + @DELETE + @Path("/delete") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public MusicResponse delete(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception { + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "Auth failed for admin"); + return response; } + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid)); + ResultType result; try { - 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.."); + result = MusicCore.nonKeyRelatedPut(queryObject, "eventual"); + response.setResposne("success", "Application deleted successfully. Please contact ops team to delete keyspace"); + }catch(Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, ex); + response.setResposne("fail", ex.getMessage()); + return response; } + return response; } - 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()); - } - } + @POST + @Path("/onboard") + @ApiOperation(value = "Onboard application", response = String.class) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse onboard(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "auth error"); + } + PreparedQueryObject pQurey = new PreparedQueryObject(); + pQurey.appendQueryString("Describe keyspace + ?"); + pQurey.addValue(MusicUtil.convertToActualDataType(DataType.text(),jsonObj.getKeyspace())); + KeyspaceMetadata keyspaceInfo = null; + //authenticator.checkOnbaordUserAccess(jsonObj.getUserId(), jsonObj.getAppname()); + try { + keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace()); + }catch (Exception e) { + logger.info(EELFLoggerDelegate.applicationLogger,"Application onbaord failed for "+ jsonObj.getKeyspace()); - 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); + } + if(keyspaceInfo == null) { + logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again"); + response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and onboard again"); + return response; + } + Response result = null; + try { + result = onboardAppWithMusic(jsonObj, authorization); + if(result.getStatus()!= 200) { + response.setResposne("fail", result.getEntity().toString()); + }else { + response.setResposne("success", "Onboard Success"); } - 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); + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); + return response; + } - CachingUtil.updateCallbackNotifyList(notifyList); + return response; } @POST - @Path("/onboardCallback") - @Produces(MediaType.APPLICATION_JSON) + @Path("/disable") + @ApiOperation(value = "Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) - public Response addCallback(JsonNotification jsonNotification) { - Map resultMap = new HashMap<>(); - 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;; + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse disableApplicationAccess(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization, + @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "Authorization failed for music admin"); } - tableName = allFields[0]; - String cql = "CREATE TRIGGER IF NOT EXISTS musictrigger ON "+tableName+" Using '"+triggerName+"'"; - PreparedQueryObject pQuery = new PreparedQueryObject(); - - String uuid = CachingUtil.generateUUID(); + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("SELECT * from admin.keyspace_master where uuid = ?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + Row row = MusicDataStoreHandle.getDSHandle().executeGet(queryObject, "eventual").one(); + boolean toggleAccess = row.getBool("is_api"); + queryObject = null; + queryObject = new PreparedQueryObject(); + queryObject.appendQueryString("UPDATE admin.keyspace_master SET is_api = ? WHERE uuid = ?"); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), !toggleAccess)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); try { - 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(); + MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual"); + response.setResposne("success","Access toggle success"); + }catch(Exception ex) { + response.setResposne("fail", ex.getMessage()); } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully registered").toMap()).build(); + + return response; } - @DELETE - @Path("/onboardCallback") - @Produces(MediaType.APPLICATION_JSON) + @POST + @Path("/editApplication") + @ApiOperation(value = "Onboard application", response = String.class) @Consumes(MediaType.APPLICATION_JSON) - public Response deleteCallbackProp(JsonNotification jsonNotification) { - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - String notifyOn = jsonNotification.getNotify_field(); - PreparedQueryObject pQuery = new PreparedQueryObject(); + @Produces(MediaType.APPLICATION_JSON) + public MusicResponse editApplication(JsonOnboard jsonObj, + @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { + logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); + MusicResponse response = new MusicResponse(); + if (!authenticator.authenticateAdmin(authorization)) { + logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + response.setResposne("fail", "auth error"); + } + KeyspaceMetadata keyspaceInfo = null; + try { + keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace()); + }catch (Exception e) { + logger.info(EELFLoggerDelegate.applicationLogger,"Application Update failed for "+ jsonObj.getKeyspace()); + + } + if(keyspaceInfo == null) { + logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again"); + response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and update again"); + return response; + } + try { - 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(); + Response res = updateOnboardApp(jsonObj, authorization); + if(res.getStatus() != 200) { + response.setResposne("fail", res.getEntity().toString()); + }else + response.setResposne("success", "Update success"); + }catch(Exception ex){ + logger.info(EELFLoggerDelegate.errorLogger,"Exception while updating application"); + logger.info(EELFLoggerDelegate.errorLogger,ex.getMessage()); + response.setResposne("fail", ex.getMessage()); + } - return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully deleted").toMap()).build(); + return response; } + + }