diff options
author | Bharath Balasubramanian <bharathb@research.att.com> | 2019-01-29 14:30:30 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-01-29 14:30:30 +0000 |
commit | 9b6c220d7063bd3a348a32d61966995d1af831a4 (patch) | |
tree | 4e78880c32bdaec86c4fb9439b87c5f1429601be /src/main/java/org | |
parent | 1f6168434fb9bb82dedd43f612bcf75ae59e7a51 (diff) | |
parent | d8c44ad0273ee54d8ee94ab2be06330cac9c08f3 (diff) |
Merge "refactord RestMusicAdminAPI.java as per spring MVC" into dev-cassandra-only
Diffstat (limited to 'src/main/java/org')
7 files changed, 612 insertions, 323 deletions
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java index 0bac1e31..c0c1d32a 100755 --- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java +++ b/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (c) 2017 AT&T Intellectual Property * =================================================================== + * Modifications Copyright (c) 2018-2019 IBM. + * =================================================================== * 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 @@ -35,6 +37,18 @@ public class JsonOnboard { private String isAAF; private String aid; + public JsonOnboard() { + } + + public JsonOnboard(String appname, String userId, String password, String isAAF, String aid) { + super(); + this.appname = appname; + this.userId = userId; + this.password = password; + this.isAAF = isAAF; + this.aid = aid; + } + @ApiModelProperty(value = "Application Password") public String getPassword() { return password; diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 90436499..27c0985b 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -2,7 +2,9 @@ * ============LICENSE_START========================================== * org.onap.music * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018-2019 IBM. * =================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,363 +23,76 @@ */ package org.onap.music.rest; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; -import org.mindrot.jbcrypt.BCrypt; -import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JSONObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -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.main.MusicCore; -import org.onap.music.main.MusicUtil; -import org.onap.music.main.ResultType; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; +import org.onap.music.rest.service.RestMusicAdminService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -@Path("/v2/admin") +@Controller +@RequestMapping("/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); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); + @Autowired + private RestMusicAdminService restAdminService; /* - * API to onboard an application with MUSIC. This is the mandatory first step. + * API to onboard an application with MUSIC. This is the mandatory first + * step. * */ @POST - @Path("/onboardAppWithMusic") + @RequestMapping("/onboardAppWithMusic") @ApiOperation(value = "Onboard application", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception { - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - Map<String, Object> 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, - 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(); - } - - 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(); - 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(), appName)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); - 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)); - - 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(); - } - 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(); + public @ResponseBody Response onboardAppWithMusic(@RequestBody JsonOnboard jsonObj) throws Exception { + Response res = restAdminService.onboardAppWithMusic(jsonObj); + return res; } - @POST - @Path("/search") + @RequestMapping("/search") @ApiOperation(value = "Search Onboard application", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception { - Map<String, Object> resultMap = new HashMap<>(); - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - 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, - ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - resultMap.put("Exception", - "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."); - return Response.status(Status.UNAUTHORIZED).entity(resultMap).build(); - } - - PreparedQueryObject pQuery = new PreparedQueryObject(); - String cql = "select uuid, keyspace_name from admin.keyspace_master where "; - if (appName != null) - cql = cql + "application_name = ? AND "; - if (uuid != null) - cql = cql + "uuid = ? AND "; - if (isAAF != null) - cql = cql + "is_aaf = ?"; - - if (cql.endsWith("AND ")) - cql = cql.trim().substring(0, cql.length() - 4); - System.out.println("Query is: " + cql); - cql = cql + " allow filtering"; - System.out.println("Get OnboardingInfo CQL: " + cql); - pQuery.appendQueryString(cql); - if (appName != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); - if (uuid != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); - if (isAAF != null) - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), - Boolean.parseBoolean(isAAF))); - ResultSet rs = MusicCore.get(pQuery); - Iterator<Row> it = rs.iterator(); - while (it.hasNext()) { - Row row = (Row) it.next(); - resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name")); - } - 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(); - } 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(); - } - } - return Response.status(Status.OK).entity(resultMap).build(); + public @ResponseBody Response getOnboardedInfoSearch(@RequestBody JsonOnboard jsonObj) throws Exception { + Response res = restAdminService.getOnboardedInfoSearch(jsonObj); + return res; } - @DELETE - @Path("/onboardAppWithMusic") + @RequestMapping("/deleteOnboardApp") @ApiOperation(value = "Delete Onboard application", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception { - Map<String, Object> resultMap = new HashMap<>(); - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - String appName = jsonObj.getAppname(); - String aid = jsonObj.getAid(); - PreparedQueryObject pQuery = new PreparedQueryObject(); - String consistency = MusicUtil.EVENTUAL;; - if (appName == null && aid == null) { - logger.error(EELFLoggerDelegate.errorLogger, "", 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); - } - } - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString(aid))); - ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); - if (result == ResultType.SUCCESS) { - 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); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - - } - return Response.status(Status.OK).entity(resultMap).build(); - } - - 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); - List<Row> rows = rs.all(); - String uuid = null; - if (rows.size() == 0) { - resultMap.put("Exception", - "Application not found. Please make sure Application exists."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } else if (rows.size() == 1) { - uuid = rows.get(0).getUUID("uuid").toString(); - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString(uuid))); - Row row = MusicCore.get(pQuery).one(); - String ks = row.getString("keyspace_name"); - if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString("DROP KEYSPACE " + ks + ";"); - MusicCore.nonKeyRelatedPut(queryObject, consistency); - } - - pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?"); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), - UUID.fromString(uuid))); - MusicCore.eventualPut(pQuery); - resultMap.put("Success", "Your application " + appName + " has been deleted."); - return Response.status(Status.OK).entity(resultMap).build(); - } else { - resultMap.put("Failure", - "More than one Aid exists for this application, so please provide Aid."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MULTIPLERECORDS, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } + public @ResponseBody Response deleteOnboardApp(@RequestBody JsonOnboard jsonObj) throws Exception { + Response res = restAdminService.deleteOnboardApp(jsonObj); + return res; } - @PUT - @Path("/onboardAppWithMusic") + @RequestMapping("/updateOnboardApp") @ApiOperation(value = "Update Onboard application", response = String.class) - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response updateOnboardApp(JsonOnboard jsonObj) throws Exception { - Map<String, Object> resultMap = new HashMap<>(); - ResponseBuilder response = - Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); - String aid = jsonObj.getAid(); - String appName = jsonObj.getAppname(); - String userId = jsonObj.getUserId(); - String isAAF = jsonObj.getIsAAF(); - String password = jsonObj.getPassword(); - String consistency = "eventual"; - PreparedQueryObject pQuery; - - if (aid == null) { - resultMap.put("Exception", "Please make sure Aid is present"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - - 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, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - - if (appName != null) { - 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."); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - } - - pQuery = new PreparedQueryObject(); - StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET "); - if (appName != null) - preCql.append(" application_name = ?,"); - if (userId != null) - preCql.append(" username = ?,"); - if (password != null) - preCql.append(" password = ?,"); - if (isAAF != null) - preCql.append(" is_aaf = ?,"); - preCql.deleteCharAt(preCql.length() - 1); - preCql.append(" WHERE uuid = ? IF EXISTS"); - pQuery.appendQueryString(preCql.toString()); - if (appName != null) - 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)); - - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); - ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency); - - if (result == ResultType.SUCCESS) { - resultMap.put("Success", "Your application has been updated successfully"); - } else { - resultMap.put("Exception", - "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded"); - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, - ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); - } - - return Response.status(Status.OK).entity(resultMap).build(); + public @ResponseBody Response updateOnboardApp(@RequestBody JsonOnboard jsonObj) throws Exception { + Response res = restAdminService.updateOnboardApp(jsonObj); + return res; } - + @POST - @Path("/callbackOps") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) + @RequestMapping("/callbackOps") public String callbackOps(JSONObject inputJsonObj) throws Exception { - - System.out.println("Input JSON: "+inputJsonObj.getData()); - return "Success"; + + System.out.println("Input JSON: " + inputJsonObj.getData()); + return "Success"; } } diff --git a/src/main/java/org/onap/music/rest/repository/RestMusicAdminRepository.java b/src/main/java/org/onap/music/rest/repository/RestMusicAdminRepository.java new file mode 100644 index 00000000..0b7e223f --- /dev/null +++ b/src/main/java/org/onap/music/rest/repository/RestMusicAdminRepository.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * 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.repository; + +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.ResultType; + +import com.datastax.driver.core.ResultSet; + +public interface RestMusicAdminRepository { + + ResultSet getUuidFromKeySpaceMasterUsingAppName(String appName) throws Exception; + + String insertValuesIntoKeySpaceMaster(String uuid, String appName, String userId, String isAAF, String password) + throws Exception; + + ResultSet fetchOnboardedInfoSearch(String appName, String uuid, String isAAF) throws Exception; + + ResultSet getKeySpaceNameFromKeySpaceMasterWithUuid(String aid) throws Exception; + + void dropKeySpace(String ks, String consistency) throws MusicServiceException; + + ResultType deleteFromKeySpaceMasterWithUuid(String aid, String consistency) throws Exception; + + ResultSet getKeySpaceNameFromKeySpaceMasterWithAppName(String appName) throws Exception; + + ResultType updateKeySpaceMaster(String appName, String userId, String password, String isAAF, String aid, + String consistency) throws Exception; +} diff --git a/src/main/java/org/onap/music/rest/repository/impl/RestMusicAdminRepositoryImpl.java b/src/main/java/org/onap/music/rest/repository/impl/RestMusicAdminRepositoryImpl.java new file mode 100644 index 00000000..bf841dc5 --- /dev/null +++ b/src/main/java/org/onap/music/rest/repository/impl/RestMusicAdminRepositoryImpl.java @@ -0,0 +1,147 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * 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.repository.impl; + +import java.util.UUID; + +import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.datastore.PreparedQueryObject; +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.rest.repository.RestMusicAdminRepository; +import org.onap.music.rest.util.RestMusicAdminAPIUtil; +import org.springframework.stereotype.Repository; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; + +@Repository +public class RestMusicAdminRepositoryImpl implements RestMusicAdminRepository { + + private PreparedQueryObject pQuery; + + @Override + public ResultSet getUuidFromKeySpaceMasterUsingAppName(String appName) throws Exception { + 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); + return rs; + } + + @Override + public String insertValuesIntoKeySpaceMaster(String uuid, String appName, String userId, String isAAF, + String password) throws Exception { + pQuery = new PreparedQueryObject(); + 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(), appName)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); + 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)); + + String returnStr = MusicCore.eventualPut(pQuery).toString(); + return returnStr; + } + + @Override + public ResultSet fetchOnboardedInfoSearch(String appName, String uuid, String isAAF) throws Exception { + pQuery = new PreparedQueryObject(); + pQuery = RestMusicAdminAPIUtil.getQueryString(appName, uuid, isAAF); + ResultSet rs = MusicCore.get(pQuery); + return rs; + } + + @Override + public ResultSet getKeySpaceNameFromKeySpaceMasterWithUuid(String aid) throws Exception { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); + ResultSet rs = MusicCore.get(pQuery); + return rs; + } + + @Override + public void dropKeySpace(String ks, String consistency) throws MusicServiceException { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";"); + MusicCore.nonKeyRelatedPut(pQuery, consistency); + + } + + @Override + public ResultType deleteFromKeySpaceMasterWithUuid(String aid, String consistency) throws Exception { + pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); + + ResultType rt = MusicCore.nonKeyRelatedPut(pQuery, consistency); + return rt; + } + + @Override + public ResultSet getKeySpaceNameFromKeySpaceMasterWithAppName(String appName) throws Exception { + 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); + return rs; + } + + @Override + public ResultType updateKeySpaceMaster(String appName, String userId, String password, String isAAF, String aid, + String consistency) throws Exception { + pQuery = new PreparedQueryObject(); + StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET "); + if (appName != null) + preCql.append(" application_name = ?,"); + if (userId != null) + preCql.append(" username = ?,"); + if (password != null) + preCql.append(" password = ?,"); + if (isAAF != null) + preCql.append(" is_aaf = ?,"); + preCql.deleteCharAt(preCql.length() - 1); + preCql.append(" WHERE uuid = ? IF EXISTS"); + pQuery.appendQueryString(preCql.toString()); + if (appName != null) + 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)); + + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid))); + ResultType rs = MusicCore.nonKeyRelatedPut(pQuery, consistency); + return rs; + } + +} diff --git a/src/main/java/org/onap/music/rest/service/RestMusicAdminService.java b/src/main/java/org/onap/music/rest/service/RestMusicAdminService.java new file mode 100644 index 00000000..dd2e5fc3 --- /dev/null +++ b/src/main/java/org/onap/music/rest/service/RestMusicAdminService.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * 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.service; + +import javax.ws.rs.core.Response; + +import org.onap.music.datastore.jsonobjects.JsonOnboard; + +public interface RestMusicAdminService { + Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception; + + Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception; + + Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception; + + Response updateOnboardApp(JsonOnboard jsonObj) throws Exception; +} diff --git a/src/main/java/org/onap/music/rest/service/impl/RestMusicAdminServiceImpl.java b/src/main/java/org/onap/music/rest/service/impl/RestMusicAdminServiceImpl.java new file mode 100644 index 00000000..6cce4f63 --- /dev/null +++ b/src/main/java/org/onap/music/rest/service/impl/RestMusicAdminServiceImpl.java @@ -0,0 +1,249 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * 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.service.impl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; + +import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.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.main.CachingUtil; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.rest.repository.RestMusicAdminRepository; +import org.onap.music.rest.service.RestMusicAdminService; +import org.onap.music.rest.util.RestMusicAdminAPIUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +@Service("restAdminService") +@Transactional +public class RestMusicAdminServiceImpl implements RestMusicAdminService { + + @Autowired + private RestMusicAdminRepository restMusicAdminRepository; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminServiceImpl.class); + + @Override + public Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception { + ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + Map<String, Object> 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) { + String message = "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."; + return RestMusicAdminAPIUtil.sendUnauthorisedResponseForEmptyParams(logger, message); + } + + ResultSet rs = restMusicAdminRepository.getUuidFromKeySpaceMasterUsingAppName(appName); + 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(); + } + + String uuid = CachingUtil.generateUUID(); + String returnStr = restMusicAdminRepository.insertValuesIntoKeySpaceMaster(uuid, appName, userId, isAAF, + password); + 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(); + } + 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(); + } + + @Override + public Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception { + Map<String, Object> resultMap = new HashMap<>(); + ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + String appName = jsonObj.getAppname(); + String uuid = jsonObj.getAid(); + String isAAF = jsonObj.getIsAAF(); + String message = "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF."; + if (appName == null && uuid == null && isAAF == null) { + return RestMusicAdminAPIUtil.sendUnauthorisedResponseForEmptyParams(logger, message); + } + + ResultSet rs = restMusicAdminRepository.fetchOnboardedInfoSearch(appName, uuid, isAAF); + Iterator<Row> it = rs.iterator(); + while (it.hasNext()) { + Row row = (Row) it.next(); + resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name")); + } + 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(); + } 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(); + } + } + return Response.status(Status.OK).entity(resultMap).build(); + } + + @Override + public Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception { + Map<String, Object> resultMap = new HashMap<>(); + ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + String appName = jsonObj.getAppname(); + String aid = jsonObj.getAid(); + PreparedQueryObject pQuery = new PreparedQueryObject(); + String consistency = MusicUtil.EVENTUAL; + ; + if (appName == null && aid == null) { + String message = "Please make sure either appName(ns) or Aid is present"; + return RestMusicAdminAPIUtil.sendUnauthorisedResponseForEmptyParams(logger, message); + } + if (aid != null) { + + ResultSet rs = restMusicAdminRepository.getKeySpaceNameFromKeySpaceMasterWithUuid(aid); + Row row = rs.one(); + if (row != null) { + String ks = row.getString("keyspace_name"); + if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { + restMusicAdminRepository.dropKeySpace(ks, consistency); + } + } + ResultType result = restMusicAdminRepository.deleteFromKeySpaceMasterWithUuid(aid, consistency); + if (result == ResultType.SUCCESS) { + 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); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + + } + return Response.status(Status.OK).entity(resultMap).build(); + } + + ResultSet rs = restMusicAdminRepository.getKeySpaceNameFromKeySpaceMasterWithAppName(appName); + List<Row> rows = rs.all(); + String uuid = null; + if (rows.size() == 0) { + resultMap.put("Exception", "Application not found. Please make sure Application exists."); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } else if (rows.size() == 1) { + uuid = rows.get(0).getUUID("uuid").toString(); + pQuery = new PreparedQueryObject(); + ResultSet rs1 = restMusicAdminRepository.getKeySpaceNameFromKeySpaceMasterWithUuid(aid); + Row row = rs1.one(); + String ks = row.getString("keyspace_name"); + if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) { + restMusicAdminRepository.dropKeySpace(ks, consistency); + } + + restMusicAdminRepository.deleteFromKeySpaceMasterWithUuid(uuid, consistency); + resultMap.put("Success", "Your application " + appName + " has been deleted."); + return Response.status(Status.OK).entity(resultMap).build(); + } else { + resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid."); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MULTIPLERECORDS, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + } + + @Override + public Response updateOnboardApp(JsonOnboard jsonObj) throws Exception { + Map<String, Object> resultMap = new HashMap<>(); + ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + String aid = jsonObj.getAid(); + String appName = jsonObj.getAppname(); + String userId = jsonObj.getUserId(); + String isAAF = jsonObj.getIsAAF(); + String password = jsonObj.getPassword(); + String consistency = "eventual"; + PreparedQueryObject pQuery; + + if (aid == null) { + resultMap.put("Exception", "Please make sure Aid is present"); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + + 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, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + + if (appName != null) { + ResultSet rs = restMusicAdminRepository.getUuidFromKeySpaceMasterUsingAppName(appName); + if (!rs.all().isEmpty()) { + resultMap.put("Exception", + "Application " + appName + " has already been onboarded. Please contact admin."); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + } + + ResultType result = restMusicAdminRepository.updateKeySpaceMaster(appName, userId, password, isAAF, aid, + consistency); + + if (result == ResultType.SUCCESS) { + resultMap.put("Success", "Your application has been updated successfully"); + } else { + resultMap.put("Exception", + "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded"); + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL, + ErrorTypes.DATAERROR); + return Response.status(Status.BAD_REQUEST).entity(resultMap).build(); + } + + return Response.status(Status.OK).entity(resultMap).build(); + } + +} diff --git a/src/main/java/org/onap/music/rest/util/RestMusicAdminAPIUtil.java b/src/main/java/org/onap/music/rest/util/RestMusicAdminAPIUtil.java new file mode 100644 index 00000000..cc3a0e55 --- /dev/null +++ b/src/main/java/org/onap/music/rest/util/RestMusicAdminAPIUtil.java @@ -0,0 +1,78 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM. + * =================================================================== + * 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.util; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.onap.music.datastore.PreparedQueryObject; +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.MusicUtil; + +import com.datastax.driver.core.DataType; + +public class RestMusicAdminAPIUtil { + public static Response sendUnauthorisedResponseForEmptyParams(EELFLoggerDelegate logger, String message) + + { + Map<String, Object> resultMap = new HashMap<>(); + + logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + resultMap.put("Exception", message); + return Response.status(Status.UNAUTHORIZED).entity(resultMap).build(); + + } + + public static PreparedQueryObject getQueryString(String appName, String uuid, String isAAF) throws Exception { + PreparedQueryObject pQuery = new PreparedQueryObject(); + String cql = "select uuid, keyspace_name from admin.keyspace_master where "; + if (appName != null) + cql = cql + "application_name = ? AND "; + if (uuid != null) + cql = cql + "uuid = ? AND "; + if (isAAF != null) + cql = cql + "is_aaf = ?"; + + if (cql.endsWith("AND ")) + cql = cql.trim().substring(0, cql.length() - 4); + System.out.println("Query is: " + cql); + cql = cql + " allow filtering"; + System.out.println("Get OnboardingInfo CQL: " + cql); + pQuery.appendQueryString(cql); + if (appName != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName)); + if (uuid != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid)); + if (isAAF != null) + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), Boolean.parseBoolean(isAAF))); + return pQuery; + + } +} |