From a04fb48c3dde9b784d7875d25ffb1c7afeb26d37 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Fri, 30 Sep 2022 14:02:20 +0200 Subject: [PATCH 01/15] Introducing enums, enhancing topic request approval, ApiResponse --- .../klaw/controller/TopicController.java | 17 +- .../java/io/aiven/klaw/model/ApiResponse.java | 26 ++ .../io/aiven/klaw/model/ApiResultStatus.java | 14 + .../io/aiven/klaw/model/ClusterStatus.java | 13 + .../aiven/klaw/model/ClusterTopicRequest.java | 21 ++ .../aiven/klaw/service/ClusterApiService.java | 293 +++++++----------- .../klaw/service/TopicControllerService.java | 40 ++- src/main/resources/application.properties | 12 +- src/main/resources/static/index.html | 2 +- src/main/resources/templates/activityLog.html | 2 +- src/main/resources/templates/addCluster.html | 2 +- src/main/resources/templates/addEnv.html | 2 +- .../templates/addKafkaConnectEnv.html | 2 +- src/main/resources/templates/addRole.html | 2 +- .../resources/templates/addSchemaEnv.html | 2 +- src/main/resources/templates/addTeam.html | 2 +- src/main/resources/templates/addTenant.html | 2 +- src/main/resources/templates/addUser.html | 2 +- src/main/resources/templates/addUserLdap.html | 2 +- src/main/resources/templates/analytics.html | 2 +- src/main/resources/templates/browseAcls.html | 2 +- .../resources/templates/browseTopics.html | 2 +- src/main/resources/templates/changePwd.html | 2 +- src/main/resources/templates/clusters.html | 2 +- .../templates/connectorOverview.html | 2 +- src/main/resources/templates/envs.html | 2 +- src/main/resources/templates/execAcls.html | 2 +- .../resources/templates/execConnectors.html | 2 +- .../templates/execRegisteredUsers.html | 2 +- src/main/resources/templates/execSchemas.html | 2 +- src/main/resources/templates/execTopics.html | 2 +- src/main/resources/templates/helpwizard.html | 2 +- src/main/resources/templates/index.html | 2 +- .../resources/templates/kafkaConnectors.html | 2 +- src/main/resources/templates/kwmetrics.html | 2 +- .../resources/templates/modifyCluster.html | 2 +- src/main/resources/templates/modifyEnv.html | 2 +- src/main/resources/templates/modifyTeam.html | 2 +- src/main/resources/templates/modifyUser.html | 2 +- src/main/resources/templates/monitorEnvs.html | 2 +- .../resources/templates/myAclRequests.html | 2 +- .../templates/myConnectorRequests.html | 2 +- src/main/resources/templates/myProfile.html | 2 +- .../resources/templates/mySchemaRequests.html | 2 +- .../resources/templates/myTopicRequests.html | 2 +- src/main/resources/templates/permissions.html | 2 +- .../resources/templates/requestConnector.html | 4 +- .../resources/templates/requestSchema.html | 2 +- .../resources/templates/requestTopics.html | 2 +- src/main/resources/templates/roles.html | 2 +- .../resources/templates/serverConfig.html | 2 +- src/main/resources/templates/showTeams.html | 2 +- src/main/resources/templates/showUsers.html | 2 +- .../resources/templates/syncBackAcls.html | 2 +- .../resources/templates/syncBackTopics.html | 2 +- .../resources/templates/synchronizeAcls.html | 2 +- .../templates/synchronizeConnectors.html | 2 +- .../templates/synchronizeTopics.html | 2 +- src/main/resources/templates/tenantInfo.html | 2 +- src/main/resources/templates/tenants.html | 2 +- .../klaw/controller/TopicControllerTest.java | 10 +- .../klaw/service/ClusterApiServiceTest.java | 17 +- .../service/TopicControllerServiceTest.java | 11 +- 63 files changed, 319 insertions(+), 261 deletions(-) create mode 100644 src/main/java/io/aiven/klaw/model/ApiResponse.java create mode 100644 src/main/java/io/aiven/klaw/model/ApiResultStatus.java create mode 100644 src/main/java/io/aiven/klaw/model/ClusterStatus.java create mode 100644 src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java diff --git a/src/main/java/io/aiven/klaw/controller/TopicController.java b/src/main/java/io/aiven/klaw/controller/TopicController.java index 5276d1ca54..f9db04c556 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicController.java @@ -1,6 +1,7 @@ package io.aiven.klaw.controller; import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.TopicInfo; import io.aiven.klaw.model.TopicRequestModel; import io.aiven.klaw.service.TopicControllerService; @@ -101,10 +102,18 @@ public ResponseEntity deleteTopicRequests(@RequestParam("topicId") Strin @PostMapping( value = "/execTopicRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity approveTopicRequests(@RequestParam("topicId") String topicId) - throws KlawException { - return new ResponseEntity<>( - topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); + public ResponseEntity approveTopicRequests(@RequestParam("topicId") String topicId) { + try { + return new ResponseEntity<>( + topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); + } catch (KlawException e) { + return new ResponseEntity<>( + ApiResponse.builder() + .message(e.getMessage()) + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .build(), + HttpStatus.INTERNAL_SERVER_ERROR); + } } @PostMapping( diff --git a/src/main/java/io/aiven/klaw/model/ApiResponse.java b/src/main/java/io/aiven/klaw/model/ApiResponse.java new file mode 100644 index 0000000000..520bebb3fc --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/ApiResponse.java @@ -0,0 +1,26 @@ +package io.aiven.klaw.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.time.LocalDateTime; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.http.HttpStatus; + +@Builder +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ApiResponse { + private HttpStatus status; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") + private LocalDateTime timestamp; + + private String message; + + private String debugMessage; + + private String result; +} diff --git a/src/main/java/io/aiven/klaw/model/ApiResultStatus.java b/src/main/java/io/aiven/klaw/model/ApiResultStatus.java new file mode 100644 index 0000000000..0a4a7f7ac5 --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/ApiResultStatus.java @@ -0,0 +1,14 @@ +package io.aiven.klaw.model; + +public enum ApiResultStatus { + SUCCESS("success"), + FAILURE("failure"), + NOT_AUTHORIZED("Not Authorized"), + ERROR("error"); + + public final String value; + + ApiResultStatus(String value) { + this.value = value; + } +} diff --git a/src/main/java/io/aiven/klaw/model/ClusterStatus.java b/src/main/java/io/aiven/klaw/model/ClusterStatus.java new file mode 100644 index 0000000000..0bfaab0f67 --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/ClusterStatus.java @@ -0,0 +1,13 @@ +package io.aiven.klaw.model; + +public enum ClusterStatus { + OFFLINE("OFFLINE"), + ONLINE("ONLINE"), + NOT_KNOWN("NOT_KNOWN"); + + public final String value; + + ClusterStatus(String value) { + this.value = value; + } +} diff --git a/src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java b/src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java new file mode 100644 index 0000000000..8fef7bcc7c --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java @@ -0,0 +1,21 @@ +package io.aiven.klaw.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import lombok.Builder; + +@Builder(toBuilder = true) +public class ClusterTopicRequest implements Serializable { + + @JsonProperty private String env; + + @JsonProperty private int partitions; + + @JsonProperty private short replicationFactor; + + @JsonProperty private String protocol; + + @JsonProperty private String clusterName; + + @JsonProperty private String topicName; +} diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index ebd9377144..0b919b758f 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -2,6 +2,7 @@ import static io.aiven.klaw.service.KwConstants.CLUSTER_CONN_URL_KEY; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.AclRequests; @@ -12,6 +13,9 @@ import io.aiven.klaw.model.AclOperation; import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.AclsNativeType; +import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.ClusterStatus; +import io.aiven.klaw.model.ClusterTopicRequest; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; import java.io.File; @@ -44,7 +48,6 @@ import org.apache.http.impl.client.HttpClients; import org.apache.tomcat.util.codec.binary.Base64; import org.jasypt.util.text.BasicTextEncryptor; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; @@ -63,13 +66,7 @@ @Slf4j public class ClusterApiService { - @Autowired ManageDatabase manageDatabase; - - @Value("${server.ssl.trust-store:null}") - private String trustStore; - - @Value("${server.ssl.trust-store-password:null}") - private String trustStorePwd; + final ManageDatabase manageDatabase; @Value("${server.ssl.key-store:null}") private String keyStore; @@ -97,8 +94,8 @@ public class ClusterApiService { private static String clusterConnUrl; - public String getClusterApiUrl() { - return clusterConnUrl; + public ClusterApiService(ManageDatabase manageDatabase) { + this.manageDatabase = manageDatabase; } RestTemplate httpRestTemplate, httpsRestTemplate; @@ -127,25 +124,17 @@ public String getClusterApiStatus(String clusterApiUrl, boolean testConnection, getClusterApiProperties(tenantId); String clusterStatus; try { - String URI_CLSTR_API_STAUTS = "/topics/getApiStatus"; + String URI_CLUSTER_API_STATUS = "/topics/getApiStatus"; String uri; - if (testConnection) uri = clusterApiUrl + URI_CLSTR_API_STAUTS; - else uri = clusterConnUrl + URI_CLSTR_API_STAUTS; // from stored kw props - - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity entity = new HttpEntity<>(headers); + if (testConnection) uri = clusterApiUrl + URI_CLUSTER_API_STATUS; + else uri = clusterConnUrl + URI_CLUSTER_API_STATUS; // from stored kw props ResponseEntity resultBody = - restTemplate.exchange(uri, HttpMethod.GET, entity, String.class); + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); clusterStatus = resultBody.getBody(); } catch (Exception e) { log.error("Error from getClusterApiStatus ", e); - return "OFFLINE"; + return ClusterStatus.OFFLINE.value; } return clusterStatus; } @@ -156,20 +145,12 @@ String getSchemaClusterStatus(String host, int tenantId) { String clusterStatus; try { String uri = host + "/subjects"; - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity entity = new HttpEntity<>(headers); - ResponseEntity resultBody = - restTemplate.exchange(uri, HttpMethod.GET, entity, String.class); + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); clusterStatus = resultBody.getBody(); } catch (Exception e) { log.error("Error from getSchemaClusterStatus ", e); - return "OFFLINE"; + return ClusterStatus.OFFLINE.value; } return clusterStatus; } @@ -194,20 +175,13 @@ String getKafkaClusterStatus( + tenantId + "/" + clusterType; - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity entity = new HttpEntity<>(headers); ResponseEntity resultBody = - restTemplate.exchange(uri, HttpMethod.GET, entity, String.class); + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); clusterStatus = resultBody.getBody(); } catch (Exception e) { log.error("Error from getKafkaClusterStatus ", e); - return "NOT_KNOWN"; + return ClusterStatus.NOT_KNOWN.value; } return clusterStatus; } @@ -239,15 +213,11 @@ public List> getConsumerOffsets( + consumerGroupId + "/" + topic; - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity>> entity = new HttpEntity<>(headers); - ResponseEntity resultBody = - restTemplate.exchange(url, HttpMethod.GET, entity, List.class); + ResponseEntity>> resultBody = + getRestTemplate() + .exchange( + url, HttpMethod.GET, getHttpEntity(), new ParameterizedTypeReference<>() {}); offsetsMap = new ArrayList<>(Objects.requireNonNull(resultBody.getBody())); } catch (Exception e) { @@ -288,15 +258,11 @@ public Map getTopicEvents( + topic + "/" + offsetId; - RestTemplate restTemplate = getRestTemplate(); - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity> entity = new HttpEntity<>(headers); - ResponseEntity resultBody = - restTemplate.exchange(url, HttpMethod.GET, entity, Map.class); + ResponseEntity> resultBody = + getRestTemplate() + .exchange( + url, HttpMethod.GET, getHttpEntity(), new ParameterizedTypeReference<>() {}); eventsMap = new TreeMap<>(Objects.requireNonNull(resultBody.getBody())); } catch (Exception e) { @@ -357,17 +323,12 @@ public List> getAcls( + "/" + "na"; } - RestTemplate restTemplate = getRestTemplate(); - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity>> entity = new HttpEntity<>(headers); - - ResponseEntity resultBody = - restTemplate.exchange(uri, HttpMethod.GET, entity, Set.class); - aclListOriginal = new ArrayList(Objects.requireNonNull(resultBody.getBody())); + ResponseEntity>> resultBody = + getRestTemplate() + .exchange( + uri, HttpMethod.GET, getHttpEntity(), new ParameterizedTypeReference<>() {}); + aclListOriginal = new ArrayList<>(Objects.requireNonNull(resultBody.getBody())); } catch (Exception e) { log.error("Error from getAcls", e); throw new KlawException("Could not load topics/acls. Please contact Administrator."); @@ -392,18 +353,13 @@ public List> getAllTopics( + clusterName + "-" + tenantId; - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity> entity = new HttpEntity<>(headers); - ResponseEntity s = - restTemplate.exchange(uriGetTopicsFull, HttpMethod.GET, entity, Set.class); - - topicsList = new ArrayList(Objects.requireNonNull(s.getBody())); + HttpEntity entity = getHttpEntity(); + ResponseEntity>> s = + getRestTemplate() + .exchange( + uriGetTopicsFull, HttpMethod.GET, entity, new ParameterizedTypeReference<>() {}); + topicsList = new ArrayList<>(Objects.requireNonNull(s.getBody())); } catch (Exception e) { log.error("Error from getAllTopics", e); throw new KlawException("Could not load topics. Please contact Administrator."); @@ -422,9 +378,8 @@ public String approveConnectorRequests( throws KlawException { log.info("approveConnectorRequests {} {}", connectorConfig, kafkaConnectHost); getClusterApiProperties(tenantId); - ResponseEntity response; + ResponseEntity> response; try { - RestTemplate restTemplate = getRestTemplate(); MultiValueMap params = new LinkedMultiValueMap<>(); params.add("env", kafkaConnectHost); params.add("connectorName", connectorName); @@ -440,16 +395,13 @@ public String approveConnectorRequests( uri = clusterConnUrl + URI_GET_TOPICS + "updateConnector"; } else uri = clusterConnUrl + URI_GET_TOPICS + "deleteConnector"; - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - HttpEntity> request = new HttpEntity<>(params, headers); - response = restTemplate.postForEntity(uri, request, HashMap.class); + response = getMapResponseEntity(params, uri); - if ("success".equals(response.getBody().get("result"))) { - return "success"; + if (ApiResultStatus.SUCCESS.value.equals( + Objects.requireNonNull(response.getBody()).get("result"))) { + return ApiResultStatus.SUCCESS.value; } else { - return (String) response.getBody().get("errorText"); + return response.getBody().get("errorText"); } } catch (Exception e) { @@ -458,6 +410,19 @@ public String approveConnectorRequests( } } + private ResponseEntity> getMapResponseEntity( + MultiValueMap params, String uri) { + ResponseEntity> response; + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + HttpEntity> request = new HttpEntity<>(params, headers); + response = + getRestTemplate() + .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); + return response; + } + public ResponseEntity approveTopicRequests( String topicName, String topicRequestType, @@ -469,51 +434,42 @@ public ResponseEntity approveTopicRequests( log.info("approveTopicRequests {} {}", topicName, topicEnvId); getClusterApiProperties(tenantId); ResponseEntity response; + ClusterTopicRequest clusterTopicRequest; try { - RestTemplate restTemplate = getRestTemplate(); - - MultiValueMap params = new LinkedMultiValueMap<>(); - Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(topicEnvId, tenantId); - String bootstrapHost = - manageDatabase - .getClusters(KafkaClustersType.KAFKA.value, tenantId) - .get(envSelected.getClusterId()) - .getBootstrapServers(); - params.add("env", bootstrapHost); - params.add( - "protocol", + KwClusters kwClusters = manageDatabase .getClusters(KafkaClustersType.KAFKA.value, tenantId) - .get(envSelected.getClusterId()) - .getProtocol()); - params.add( - "clusterName", - manageDatabase - .getClusters(KafkaClustersType.KAFKA.value, tenantId) - .get(envSelected.getClusterId()) - .getClusterName() - + "-" - + tenantId); - params.add("topicName", topicName); + .get(envSelected.getClusterId()); + clusterTopicRequest = + ClusterTopicRequest.builder() + .env(kwClusters.getBootstrapServers()) + .protocol(kwClusters.getProtocol()) + .clusterName(kwClusters.getClusterName() + "-" + tenantId) + .topicName(topicName) + .build(); String uri; if ("Create".equals(topicRequestType)) { uri = clusterConnUrl + URI_CREATE_TOPICS; - params.add("partitions", "" + topicPartitions); - params.add("rf", replicationFactor); + clusterTopicRequest = + clusterTopicRequest.toBuilder() + .partitions(topicPartitions) + .replicationFactor(Short.parseShort(replicationFactor)) + .build(); } else if ("Update".equals(topicRequestType)) { uri = clusterConnUrl + URI_UPDATE_TOPICS; - params.add("partitions", "" + topicPartitions); - params.add("rf", replicationFactor); + clusterTopicRequest = + clusterTopicRequest.toBuilder() + .partitions(topicPartitions) + .replicationFactor(Short.parseShort(replicationFactor)) + .build(); } else uri = clusterConnUrl + URI_DELETE_TOPICS; HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - HttpEntity> request = new HttpEntity<>(params, headers); - - response = restTemplate.postForEntity(uri, request, String.class); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity request = new HttpEntity<>(clusterTopicRequest, headers); + response = getRestTemplate().postForEntity(uri, request, String.class); } catch (Exception e) { log.error("approveTopicRequests {}", topicName, e); throw new KlawException("Could not approve topic request. Please contact Administrator."); @@ -526,6 +482,7 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq log.info("approveAclRequests {}", aclReq); getClusterApiProperties(tenantId); ResponseEntity> response; + try { String env = aclReq.getEnvironment(); String uri; @@ -536,12 +493,8 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq if ("Create".equals(aclReq.getAclType())) uri = clusterConnUrl + URI_CREATE_ACLS; else uri = clusterConnUrl + URI_DELETE_ACLS; - RestTemplate restTemplate = getRestTemplate(); - MultiValueMap params = new LinkedMultiValueMap<>(); - Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(env, tenantId); - KwClusters kwClusters = manageDatabase .getClusters(KafkaClustersType.KAFKA.value, tenantId) @@ -562,7 +515,8 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq if (Objects.equals(AclOperation.DELETE.value, aclReq.getAclType()) && null != aclReq.getJsonParams()) { ObjectMapper objectMapper = new ObjectMapper(); - Map jsonObj = objectMapper.readValue(aclReq.getJsonParams(), Map.class); + Map jsonObj = + objectMapper.readValue(aclReq.getJsonParams(), new TypeReference<>() {}); String aivenAclKey = "aivenaclid"; if (jsonObj.containsKey(aivenAclKey)) params.add(aivenAclKey, jsonObj.get(aivenAclKey)); else { @@ -588,15 +542,7 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq params.add("isPrefixAcl", ("PREFIXED".equals(aclPatternType)) + ""); } - HttpHeaders headers = - createHeaders(clusterApiUser, clusterApiPwd); // createHeaders("user1", "pwd"); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - HttpEntity> request = new HttpEntity<>(params, headers); - - response = - restTemplate.exchange( - uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); + response = getMapResponseEntity(params, uri); } catch (Exception e) { log.error("Error from approveAclRequests", e); throw new KlawException("Could not approve acl request. Please contact Administrator."); @@ -614,9 +560,7 @@ ResponseEntity postSchema( String URI_POST_SCHEMA = "/topics/postSchema"; String uri = clusterConnUrl + URI_POST_SCHEMA; - RestTemplate restTemplate = getRestTemplate(); MultiValueMap params = new LinkedMultiValueMap<>(); - Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(env, tenantId); String bootstrapHost = manageDatabase @@ -638,7 +582,7 @@ ResponseEntity postSchema( headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity> request = new HttpEntity<>(params, headers); - response = restTemplate.postForEntity(uri, request, String.class); + response = getRestTemplate().postForEntity(uri, request, String.class); } catch (Exception e) { log.error("Error from postSchema ", e); throw new KlawException("Could not post schema. Please contact Administrator."); @@ -669,20 +613,19 @@ public TreeMap> getAvroSchema( + clusterName + "/" + topicName; - RestTemplate restTemplate = getRestTemplate(); - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity> entity = new HttpEntity<>(headers); - - ResponseEntity s = - restTemplate.exchange(uriGetTopicsFull, HttpMethod.GET, entity, TreeMap.class); - - TreeMap> schemaObjects = s.getBody(); - for (String schemaVersion : schemaObjects.keySet()) { - allVersionSchemas.put(Integer.parseInt(schemaVersion), schemaObjects.get(schemaVersion)); + ResponseEntity>> treeMapResponseEntity = + getRestTemplate() + .exchange( + uriGetTopicsFull, + HttpMethod.GET, + getHttpEntity(), + new ParameterizedTypeReference<>() {}); + + for (String schemaVersion : + Objects.requireNonNull(treeMapResponseEntity.getBody()).keySet()) { + allVersionSchemas.put( + Integer.parseInt(schemaVersion), treeMapResponseEntity.getBody().get(schemaVersion)); } return allVersionSchemas; @@ -701,16 +644,14 @@ public Map getConnectorDetails( String URI_GET_TOPICS = "/topics/getConnectorDetails/" + connectorName + "/" + kafkaConnectHost + "/" + protocol; String uriGetConnectorsFull = clusterConnUrl + URI_GET_TOPICS; - RestTemplate restTemplate = getRestTemplate(); - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity> entity = new HttpEntity<>(headers); - - ResponseEntity s = - restTemplate.exchange(uriGetConnectorsFull, HttpMethod.GET, entity, LinkedHashMap.class); + ResponseEntity> s = + getRestTemplate() + .exchange( + uriGetConnectorsFull, + HttpMethod.GET, + getHttpEntity(), + new ParameterizedTypeReference<>() {}); return s.getBody(); } catch (Exception e) { @@ -726,16 +667,14 @@ public ArrayList getAllKafkaConnectors(String kafkaConnectHost, int tena try { String URI_GET_TOPICS = "/topics/getAllConnectors/" + kafkaConnectHost; String uriGetConnectorsFull = clusterConnUrl + URI_GET_TOPICS; - RestTemplate restTemplate = getRestTemplate(); - - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); - HttpEntity> entity = new HttpEntity<>(headers); - - ResponseEntity s = - restTemplate.exchange(uriGetConnectorsFull, HttpMethod.GET, entity, ArrayList.class); + ResponseEntity> s = + getRestTemplate() + .exchange( + uriGetConnectorsFull, + HttpMethod.GET, + getHttpEntity(), + new ParameterizedTypeReference<>() {}); return s.getBody(); } catch (Exception e) { @@ -762,8 +701,9 @@ public Map retrieveMetrics(String jmxUrl, String objectName) headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity> entity = new HttpEntity<>(params, headers); - ResponseEntity s = - restTemplate.postForEntity(uriGetTopicsFull, entity, HashMap.class); + ResponseEntity> s = + restTemplate.exchange( + uriGetTopicsFull, HttpMethod.POST, entity, new ParameterizedTypeReference<>() {}); return Objects.requireNonNull(s.getBody()); @@ -815,11 +755,8 @@ private void setKwSSLContext() { protected KeyStore getStore(String secret, String storeLoc) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - // ClassPathResource resource = new ClassPathResource(storeLoc); - // File key = new File(storeLoc); File key = ResourceUtils.getFile(storeLoc); - final KeyStore store = KeyStore.getInstance(keyStoreType); try (InputStream inputStream = new FileInputStream(key)) { store.load(inputStream, secret.toCharArray()); @@ -836,4 +773,12 @@ private String decodePwd(String pwd) { } return ""; } + + private HttpEntity getHttpEntity() { + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_JSON); + + headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); + return new HttpEntity<>(headers); + } } diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index 86b15c4ff8..85a123bc55 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -16,6 +16,8 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.RequestStatus; @@ -41,6 +43,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.EnumUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -679,29 +682,44 @@ public String deleteTopicRequests(String topicId) { return "{\"result\":\"" + deleteTopicReqStatus + "\"}"; } - public String approveTopicRequests(String topicId) throws KlawException { + public ApiResponse approveTopicRequests(String topicId) throws KlawException { log.info("approveTopicRequests {}", topicId); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) - return "{\"result\":\"Not Authorized\"}"; + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) { + return ApiResponse.builder() + .result(ApiResultStatus.NOT_AUTHORIZED.value) + .status(HttpStatus.OK) + .build(); + } TopicRequest topicRequest = manageDatabase .getHandleDbRequests() .selectTopicRequestsForTopic(Integer.parseInt(topicId), tenantId); - if (Objects.equals(topicRequest.getRequestor(), userDetails)) - return "{\"result\":\"You are not allowed to approve your own topic requests.\"}"; + if (Objects.equals(topicRequest.getRequestor(), userDetails)) { + return ApiResponse.builder() + .result("You are not allowed to approve your own topic requests.") + .status(HttpStatus.OK) + .build(); + } if (!RequestStatus.created.name().equals(topicRequest.getTopicstatus())) { - return "{\"result\":\"This request does not exist anymore.\"}"; + return ApiResponse.builder() + .result("This request does not exist anymore.") + .status(HttpStatus.OK) + .build(); } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) { + return ApiResponse.builder() + .result(ApiResultStatus.NOT_AUTHORIZED.value) + .status(HttpStatus.OK) + .build(); + } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); String updateTopicReqStatus; @@ -713,7 +731,7 @@ public String approveTopicRequests(String topicId) throws KlawException { } updateTopicReqStatus = dbHandle.addToSynctopics(allTopics); - if ("success".equals(updateTopicReqStatus)) + if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) updateTopicReqStatus = dbHandle.updateTopicRequestStatus(topicRequest, userDetails); } else { ResponseEntity response = @@ -727,7 +745,7 @@ public String approveTopicRequests(String topicId) throws KlawException { updateTopicReqStatus = response.getBody(); - if ("success".equals(response.getBody())) { + if (ApiResultStatus.SUCCESS.value.equals(response.getBody())) { setTopicHistory(topicRequest, userDetails, tenantId); updateTopicReqStatus = dbHandle.updateTopicRequest(topicRequest, userDetails); mailService.sendMail( @@ -741,7 +759,7 @@ public String approveTopicRequests(String topicId) throws KlawException { } } - return "{\"result\":\"" + updateTopicReqStatus + "\"}"; + return ApiResponse.builder().result(updateTopicReqStatus).status(HttpStatus.OK).build(); } private void setTopicHistory(TopicRequest topicRequest, String userName, int tenantId) { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a2e834a9c3..2575b1459b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,12 +3,12 @@ server.port=9097 #server.servlet.context-path=/klaw # SSL Properties -#server.ssl.key-store=client.keystore.p12 -#server.ssl.trust-store=client.truststore.jks -#server.ssl.key-store-password=klaw1234 -#server.ssl.key-password=klaw1234 -#server.ssl.trust-store-password=klaw1234 -#server.ssl.key-store-type=pkcs12 +server.ssl.key-store=/Users/muralidharbasani/software/kafka_2.13-3.2.0/bin/certs/client.keystore.p12 +server.ssl.trust-store=/Users/muralidharbasani/software/kafka_2.13-3.2.0/bin/certs/client.truststore.jks +server.ssl.key-store-password=klaw1234 +server.ssl.key-password=klaw1234 +server.ssl.trust-store-password=klaw1234 +server.ssl.key-store-type=pkcs12 # klaw.db.storetype should be "rdbms" klaw.db.storetype=rdbms diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 7d16cea3d6..f565136214 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -330,7 +330,7 @@

Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/activityLog.html b/src/main/resources/templates/activityLog.html index db5dbb59a0..bd2be0181d 100644 --- a/src/main/resources/templates/activityLog.html +++ b/src/main/resources/templates/activityLog.html @@ -341,7 +341,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addCluster.html b/src/main/resources/templates/addCluster.html index f317a5ef8a..f3a4a6b499 100644 --- a/src/main/resources/templates/addCluster.html +++ b/src/main/resources/templates/addCluster.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addEnv.html b/src/main/resources/templates/addEnv.html index 875ea38bf0..10f4c0c3be 100644 --- a/src/main/resources/templates/addEnv.html +++ b/src/main/resources/templates/addEnv.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addKafkaConnectEnv.html b/src/main/resources/templates/addKafkaConnectEnv.html index f18c3ae9b0..91348c9863 100644 --- a/src/main/resources/templates/addKafkaConnectEnv.html +++ b/src/main/resources/templates/addKafkaConnectEnv.html @@ -335,7 +335,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addRole.html b/src/main/resources/templates/addRole.html index 7e4f18cd3a..1a1b951e91 100644 --- a/src/main/resources/templates/addRole.html +++ b/src/main/resources/templates/addRole.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addSchemaEnv.html b/src/main/resources/templates/addSchemaEnv.html index d6d6f2c877..b2374fcf3a 100644 --- a/src/main/resources/templates/addSchemaEnv.html +++ b/src/main/resources/templates/addSchemaEnv.html @@ -335,7 +335,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addTeam.html b/src/main/resources/templates/addTeam.html index 786ecd37b5..a057cfaa97 100644 --- a/src/main/resources/templates/addTeam.html +++ b/src/main/resources/templates/addTeam.html @@ -337,7 +337,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addTenant.html b/src/main/resources/templates/addTenant.html index 179276fe7d..b07fe51180 100644 --- a/src/main/resources/templates/addTenant.html +++ b/src/main/resources/templates/addTenant.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addUser.html b/src/main/resources/templates/addUser.html index af3384fe93..3aa97ee473 100644 --- a/src/main/resources/templates/addUser.html +++ b/src/main/resources/templates/addUser.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/addUserLdap.html b/src/main/resources/templates/addUserLdap.html index e29facf1c7..c0f925489b 100644 --- a/src/main/resources/templates/addUserLdap.html +++ b/src/main/resources/templates/addUserLdap.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/analytics.html b/src/main/resources/templates/analytics.html index 9720e1a73e..b92a668116 100644 --- a/src/main/resources/templates/analytics.html +++ b/src/main/resources/templates/analytics.html @@ -349,7 +349,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/browseAcls.html b/src/main/resources/templates/browseAcls.html index b5f7f48308..bb1765973f 100644 --- a/src/main/resources/templates/browseAcls.html +++ b/src/main/resources/templates/browseAcls.html @@ -330,7 +330,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/browseTopics.html b/src/main/resources/templates/browseTopics.html index df506cc478..8c4394e755 100644 --- a/src/main/resources/templates/browseTopics.html +++ b/src/main/resources/templates/browseTopics.html @@ -359,7 +359,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/changePwd.html b/src/main/resources/templates/changePwd.html index e860f271d0..5dbcf346bf 100644 --- a/src/main/resources/templates/changePwd.html +++ b/src/main/resources/templates/changePwd.html @@ -339,7 +339,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/clusters.html b/src/main/resources/templates/clusters.html index d6b0f13529..83c9a8679e 100644 --- a/src/main/resources/templates/clusters.html +++ b/src/main/resources/templates/clusters.html @@ -347,7 +347,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/connectorOverview.html b/src/main/resources/templates/connectorOverview.html index df3e0dbc4e..cca26792a8 100644 --- a/src/main/resources/templates/connectorOverview.html +++ b/src/main/resources/templates/connectorOverview.html @@ -330,7 +330,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/envs.html b/src/main/resources/templates/envs.html index ebbcf561dc..c54a46484d 100644 --- a/src/main/resources/templates/envs.html +++ b/src/main/resources/templates/envs.html @@ -338,7 +338,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/execAcls.html b/src/main/resources/templates/execAcls.html index 9522b33934..a1071098f9 100644 --- a/src/main/resources/templates/execAcls.html +++ b/src/main/resources/templates/execAcls.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/execConnectors.html b/src/main/resources/templates/execConnectors.html index fcae6d1751..0b89fcb444 100644 --- a/src/main/resources/templates/execConnectors.html +++ b/src/main/resources/templates/execConnectors.html @@ -334,7 +334,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/execRegisteredUsers.html b/src/main/resources/templates/execRegisteredUsers.html index 0a7cff0cf2..4d25f450bd 100644 --- a/src/main/resources/templates/execRegisteredUsers.html +++ b/src/main/resources/templates/execRegisteredUsers.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/execSchemas.html b/src/main/resources/templates/execSchemas.html index 24ba434ccd..92c3daf503 100644 --- a/src/main/resources/templates/execSchemas.html +++ b/src/main/resources/templates/execSchemas.html @@ -335,7 +335,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/execTopics.html b/src/main/resources/templates/execTopics.html index de6187e9e6..2e2117adde 100644 --- a/src/main/resources/templates/execTopics.html +++ b/src/main/resources/templates/execTopics.html @@ -334,7 +334,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/helpwizard.html b/src/main/resources/templates/helpwizard.html index 5c8cb468f2..d4c85fa30a 100644 --- a/src/main/resources/templates/helpwizard.html +++ b/src/main/resources/templates/helpwizard.html @@ -337,7 +337,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index cfacc4826a..103c9fda11 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -342,7 +342,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/kafkaConnectors.html b/src/main/resources/templates/kafkaConnectors.html index a60666dd93..646f099014 100644 --- a/src/main/resources/templates/kafkaConnectors.html +++ b/src/main/resources/templates/kafkaConnectors.html @@ -359,7 +359,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/kwmetrics.html b/src/main/resources/templates/kwmetrics.html index f7af0a3eac..597fa9c172 100644 --- a/src/main/resources/templates/kwmetrics.html +++ b/src/main/resources/templates/kwmetrics.html @@ -349,7 +349,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/modifyCluster.html b/src/main/resources/templates/modifyCluster.html index 38bd78f3cb..239cdf3889 100644 --- a/src/main/resources/templates/modifyCluster.html +++ b/src/main/resources/templates/modifyCluster.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/modifyEnv.html b/src/main/resources/templates/modifyEnv.html index 8811e5fd05..0695600032 100644 --- a/src/main/resources/templates/modifyEnv.html +++ b/src/main/resources/templates/modifyEnv.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/modifyTeam.html b/src/main/resources/templates/modifyTeam.html index b02a8eea7b..210efe4a8e 100644 --- a/src/main/resources/templates/modifyTeam.html +++ b/src/main/resources/templates/modifyTeam.html @@ -337,7 +337,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/modifyUser.html b/src/main/resources/templates/modifyUser.html index 0e100c9174..4a09d831a4 100644 --- a/src/main/resources/templates/modifyUser.html +++ b/src/main/resources/templates/modifyUser.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/monitorEnvs.html b/src/main/resources/templates/monitorEnvs.html index e899e036f5..96c936b293 100644 --- a/src/main/resources/templates/monitorEnvs.html +++ b/src/main/resources/templates/monitorEnvs.html @@ -333,7 +333,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/myAclRequests.html b/src/main/resources/templates/myAclRequests.html index fa0167e141..ed5154749f 100644 --- a/src/main/resources/templates/myAclRequests.html +++ b/src/main/resources/templates/myAclRequests.html @@ -334,7 +334,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/myConnectorRequests.html b/src/main/resources/templates/myConnectorRequests.html index 752ed6aabf..3f11478139 100644 --- a/src/main/resources/templates/myConnectorRequests.html +++ b/src/main/resources/templates/myConnectorRequests.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/myProfile.html b/src/main/resources/templates/myProfile.html index 8182ad048a..456252cdde 100644 --- a/src/main/resources/templates/myProfile.html +++ b/src/main/resources/templates/myProfile.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/mySchemaRequests.html b/src/main/resources/templates/mySchemaRequests.html index b1b5567118..350290ec33 100644 --- a/src/main/resources/templates/mySchemaRequests.html +++ b/src/main/resources/templates/mySchemaRequests.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/myTopicRequests.html b/src/main/resources/templates/myTopicRequests.html index 503171200b..982edb6b63 100644 --- a/src/main/resources/templates/myTopicRequests.html +++ b/src/main/resources/templates/myTopicRequests.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/permissions.html b/src/main/resources/templates/permissions.html index 3e4812b0e4..a09c2fa9da 100644 --- a/src/main/resources/templates/permissions.html +++ b/src/main/resources/templates/permissions.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/requestConnector.html b/src/main/resources/templates/requestConnector.html index 41bf93103d..b035bd33e8 100644 --- a/src/main/resources/templates/requestConnector.html +++ b/src/main/resources/templates/requestConnector.html @@ -331,7 +331,7 @@

    Shortcuts

  • - +
  • @@ -445,7 +445,7 @@

    Shortcuts

    + class="btn waves-effect waves-light btn-rounded btn-outline-info">Back to Apache Kafka Connect diff --git a/src/main/resources/templates/requestSchema.html b/src/main/resources/templates/requestSchema.html index 7b5e6645c3..671991632b 100644 --- a/src/main/resources/templates/requestSchema.html +++ b/src/main/resources/templates/requestSchema.html @@ -330,7 +330,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/requestTopics.html b/src/main/resources/templates/requestTopics.html index 9c1facf35c..078a79787c 100644 --- a/src/main/resources/templates/requestTopics.html +++ b/src/main/resources/templates/requestTopics.html @@ -331,7 +331,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/roles.html b/src/main/resources/templates/roles.html index 71650e6912..f8cc71a606 100644 --- a/src/main/resources/templates/roles.html +++ b/src/main/resources/templates/roles.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/serverConfig.html b/src/main/resources/templates/serverConfig.html index 9a86b53eb4..73bb9b5680 100644 --- a/src/main/resources/templates/serverConfig.html +++ b/src/main/resources/templates/serverConfig.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/showTeams.html b/src/main/resources/templates/showTeams.html index 7e92c68b71..2537ec4c5c 100644 --- a/src/main/resources/templates/showTeams.html +++ b/src/main/resources/templates/showTeams.html @@ -333,7 +333,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/showUsers.html b/src/main/resources/templates/showUsers.html index 775dfeafd6..0d3df06272 100644 --- a/src/main/resources/templates/showUsers.html +++ b/src/main/resources/templates/showUsers.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/syncBackAcls.html b/src/main/resources/templates/syncBackAcls.html index ea4c0ad212..979cd85dbe 100644 --- a/src/main/resources/templates/syncBackAcls.html +++ b/src/main/resources/templates/syncBackAcls.html @@ -363,7 +363,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/syncBackTopics.html b/src/main/resources/templates/syncBackTopics.html index 1fc1faca4a..6426c19fc5 100644 --- a/src/main/resources/templates/syncBackTopics.html +++ b/src/main/resources/templates/syncBackTopics.html @@ -363,7 +363,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/synchronizeAcls.html b/src/main/resources/templates/synchronizeAcls.html index 32b43e5bfa..331352dfdd 100644 --- a/src/main/resources/templates/synchronizeAcls.html +++ b/src/main/resources/templates/synchronizeAcls.html @@ -355,7 +355,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/synchronizeConnectors.html b/src/main/resources/templates/synchronizeConnectors.html index 89de5d3f84..1b703f5d69 100644 --- a/src/main/resources/templates/synchronizeConnectors.html +++ b/src/main/resources/templates/synchronizeConnectors.html @@ -356,7 +356,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/synchronizeTopics.html b/src/main/resources/templates/synchronizeTopics.html index 5b3af14db3..6c2f564d20 100644 --- a/src/main/resources/templates/synchronizeTopics.html +++ b/src/main/resources/templates/synchronizeTopics.html @@ -355,7 +355,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/tenantInfo.html b/src/main/resources/templates/tenantInfo.html index e12449c48a..7448241dfc 100644 --- a/src/main/resources/templates/tenantInfo.html +++ b/src/main/resources/templates/tenantInfo.html @@ -336,7 +336,7 @@

    Shortcuts

  • - +
  • diff --git a/src/main/resources/templates/tenants.html b/src/main/resources/templates/tenants.html index bd1776ba61..41735af4cc 100644 --- a/src/main/resources/templates/tenants.html +++ b/src/main/resources/templates/tenants.html @@ -329,7 +329,7 @@

    Shortcuts

  • - +
  • diff --git a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java index 80f805d654..55a7286be4 100644 --- a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java @@ -11,6 +11,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.aiven.klaw.UtilMethods; import io.aiven.klaw.dao.TopicRequest; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SyncTopicUpdates; import io.aiven.klaw.model.TopicInfo; import io.aiven.klaw.model.TopicRequestModel; @@ -27,6 +29,7 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -202,7 +205,9 @@ public void deleteTopicRequests() throws Exception { @Test @Order(7) public void approveTopicRequests() throws Exception { - when(topicControllerService.approveTopicRequests(anyString())).thenReturn("success"); + ApiResponse apiResponse = + ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).status(HttpStatus.OK).build(); + when(topicControllerService.approveTopicRequests(anyString())).thenReturn(apiResponse); String response = mvc.perform( @@ -215,7 +220,8 @@ public void approveTopicRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).isEqualTo("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index 7b59becf3c..83561e046c 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -66,12 +66,11 @@ public class ClusterApiServiceTest { @BeforeEach public void setUp() { utilMethods = new UtilMethods(); - clusterApiService = new ClusterApiService(); + clusterApiService = new ClusterApiService(manageDatabase); response = new ResponseEntity<>("success", HttpStatus.OK); this.env = new Env(); env.setName("DEV"); - ReflectionTestUtils.setField(clusterApiService, "manageDatabase", manageDatabase); ReflectionTestUtils.setField(clusterApiService, "httpRestTemplate", restTemplate); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); when(manageDatabase.getKwPropertyValue(anyString(), anyInt())).thenReturn("http://cluster"); @@ -115,14 +114,17 @@ public void getStatusFailure() { @Order(3) public void getAclsSuccess() throws KlawException { Set> aclListOriginal = utilMethods.getAclsMock(); - ResponseEntity response = new ResponseEntity<>(aclListOriginal, HttpStatus.OK); + ResponseEntity response = new ResponseEntity<>(aclListOriginal, HttpStatus.OK); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getKafkaFlavor()).thenReturn("Apache Kafka"); when(restTemplate.exchange( - Mockito.anyString(), eq(HttpMethod.GET), Mockito.any(), eq(Set.class))) + Mockito.anyString(), + eq(HttpMethod.GET), + Mockito.any(), + (ParameterizedTypeReference) any())) .thenReturn(response); List> result = clusterApiService.getAcls("", env, "PLAINTEXT", "", 1); @@ -145,10 +147,13 @@ public void getAclsFailure() { @Order(5) public void getAllTopicsSuccess() throws Exception { Set topicsList = getTopics(); - ResponseEntity response = new ResponseEntity<>(topicsList, HttpStatus.OK); + ResponseEntity response = new ResponseEntity<>(topicsList, HttpStatus.OK); when(restTemplate.exchange( - Mockito.anyString(), eq(HttpMethod.GET), Mockito.any(), eq(Set.class))) + Mockito.anyString(), + eq(HttpMethod.GET), + Mockito.any(), + (ParameterizedTypeReference) any())) .thenReturn(response); List> result = clusterApiService.getAllTopics("", "PLAINTEXT", "", 1); diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index 837c07d1b4..fbfb4e0505 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -17,6 +17,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KwTenantConfigModel; import io.aiven.klaw.model.SyncTopicUpdates; import io.aiven.klaw.model.TopicInfo; @@ -335,9 +336,9 @@ public void approveTopicRequestsSuccess() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - String result = topicControllerService.approveTopicRequests(topicId + ""); + ApiResponse apiResponse = topicControllerService.approveTopicRequests(topicId + ""); - assertThat(result).isEqualTo("{\"result\":\"success\"}"); + assertThat(apiResponse.getResult()).isEqualTo("success"); } @Test @@ -352,13 +353,13 @@ public void approveTopicRequestsFailure1() throws KlawException { when(handleDbRequests.updateTopicRequest(any(), anyString())).thenReturn("success"); when(clusterApiService.approveTopicRequests( anyString(), anyString(), anyInt(), anyString(), anyString(), anyInt())) - .thenReturn(new ResponseEntity<>("failure error", HttpStatus.OK)); + .thenReturn(new ResponseEntity<>("failure", HttpStatus.OK)); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - String result = topicControllerService.approveTopicRequests("" + topicId); + ApiResponse apiResponse = topicControllerService.approveTopicRequests("" + topicId); - assertThat(result).isEqualTo("{\"result\":\"failure error\"}"); + assertThat(apiResponse.getResult()).isEqualTo("failure"); } @Test From 99c74e87cc6499568763791addcbcb1f5751b32f Mon Sep 17 00:00:00 2001 From: muralibasani Date: Fri, 30 Sep 2022 14:04:02 +0200 Subject: [PATCH 02/15] Introducing enums, enhancing topic request approval, ApiResponse --- src/main/resources/application.properties | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2575b1459b..a2e834a9c3 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,12 +3,12 @@ server.port=9097 #server.servlet.context-path=/klaw # SSL Properties -server.ssl.key-store=/Users/muralidharbasani/software/kafka_2.13-3.2.0/bin/certs/client.keystore.p12 -server.ssl.trust-store=/Users/muralidharbasani/software/kafka_2.13-3.2.0/bin/certs/client.truststore.jks -server.ssl.key-store-password=klaw1234 -server.ssl.key-password=klaw1234 -server.ssl.trust-store-password=klaw1234 -server.ssl.key-store-type=pkcs12 +#server.ssl.key-store=client.keystore.p12 +#server.ssl.trust-store=client.truststore.jks +#server.ssl.key-store-password=klaw1234 +#server.ssl.key-password=klaw1234 +#server.ssl.trust-store-password=klaw1234 +#server.ssl.key-store-type=pkcs12 # klaw.db.storetype should be "rdbms" klaw.db.storetype=rdbms From 9151c237f8facf228d1bab02411ba1b8da4ce7cf Mon Sep 17 00:00:00 2001 From: muralibasani Date: Mon, 3 Oct 2022 13:23:55 +0200 Subject: [PATCH 03/15] - Adding requests for acls and connectors - Updating ApiResponse for topic creation - Updating with ApiResponse for acls --- .../klaw/controller/TopicController.java | 2 +- .../aiven/klaw/model/AclIPPrincipleType.java | 2 +- ...clOperation.java => AclOperationType.java} | 4 +- .../java/io/aiven/klaw/model/ApiResponse.java | 2 + .../{ => cluster}/ClusterTopicRequest.java | 2 +- .../klaw/service/AclControllerService.java | 34 +++-- .../aiven/klaw/service/ClusterApiService.java | 144 +++++++++++------- .../klaw/service/TopicControllerService.java | 92 ++++++----- src/main/resources/static/js/requestAcls.js | 6 +- .../io/aiven/klaw/TopicAclControllerIT.java | 8 +- .../klaw/controller/TopicControllerTest.java | 6 +- .../service/AclControllerServiceTest.java | 19 +-- .../klaw/service/ClusterApiServiceTest.java | 28 ++-- .../service/TopicControllerServiceTest.java | 19 +-- 14 files changed, 208 insertions(+), 160 deletions(-) rename src/main/java/io/aiven/klaw/model/{AclOperation.java => AclOperationType.java} (66%) rename src/main/java/io/aiven/klaw/model/{ => cluster}/ClusterTopicRequest.java (92%) diff --git a/src/main/java/io/aiven/klaw/controller/TopicController.java b/src/main/java/io/aiven/klaw/controller/TopicController.java index f9db04c556..3ab93b06a0 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicController.java @@ -26,7 +26,7 @@ public class TopicController { @Autowired private TopicControllerService topicControllerService; @PostMapping(value = "/createTopics") - public ResponseEntity> createTopicsRequest( + public ResponseEntity createTopicsRequest( @Valid @RequestBody TopicRequestModel addTopicRequest) throws KlawException { return new ResponseEntity<>( topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); diff --git a/src/main/java/io/aiven/klaw/model/AclIPPrincipleType.java b/src/main/java/io/aiven/klaw/model/AclIPPrincipleType.java index f2c0bb1a78..e7f4d378b2 100644 --- a/src/main/java/io/aiven/klaw/model/AclIPPrincipleType.java +++ b/src/main/java/io/aiven/klaw/model/AclIPPrincipleType.java @@ -2,6 +2,6 @@ public enum AclIPPrincipleType { IP_ADDRESS, - PRINCIPLE, + PRINCIPAL, USERNAME } diff --git a/src/main/java/io/aiven/klaw/model/AclOperation.java b/src/main/java/io/aiven/klaw/model/AclOperationType.java similarity index 66% rename from src/main/java/io/aiven/klaw/model/AclOperation.java rename to src/main/java/io/aiven/klaw/model/AclOperationType.java index af06085419..f33a4c31b1 100644 --- a/src/main/java/io/aiven/klaw/model/AclOperation.java +++ b/src/main/java/io/aiven/klaw/model/AclOperationType.java @@ -1,12 +1,12 @@ package io.aiven.klaw.model; -public enum AclOperation { +public enum AclOperationType { CREATE("Create"), DELETE("Delete"); public final String value; - AclOperation(String value) { + AclOperationType(String value) { this.value = value; } } diff --git a/src/main/java/io/aiven/klaw/model/ApiResponse.java b/src/main/java/io/aiven/klaw/model/ApiResponse.java index 520bebb3fc..99de9c0191 100644 --- a/src/main/java/io/aiven/klaw/model/ApiResponse.java +++ b/src/main/java/io/aiven/klaw/model/ApiResponse.java @@ -23,4 +23,6 @@ public class ApiResponse { private String debugMessage; private String result; + + private Object data; } diff --git a/src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java b/src/main/java/io/aiven/klaw/model/cluster/ClusterTopicRequest.java similarity index 92% rename from src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java rename to src/main/java/io/aiven/klaw/model/cluster/ClusterTopicRequest.java index 8fef7bcc7c..af822eeafe 100644 --- a/src/main/java/io/aiven/klaw/model/ClusterTopicRequest.java +++ b/src/main/java/io/aiven/klaw/model/cluster/ClusterTopicRequest.java @@ -1,4 +1,4 @@ -package io.aiven.klaw.model; +package io.aiven.klaw.model.cluster; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index 85a1f96c10..17c31b60de 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -20,7 +20,9 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.AclOperationType; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; import io.aiven.klaw.model.PermissionType; @@ -287,21 +289,20 @@ private void approveSyncBackAcls( aclReq.setAcl_ssl(aclFound.getAclssl()); aclReq.setEnvironment(syncBackAcls.getTargetEnv()); aclReq.setRequestingteam(aclFound.getTeamId()); - aclReq.setAclType("Create"); + aclReq.setAclType(AclOperationType.CREATE.value); aclReq.setUsername(getUserName()); aclReq.setTenantId(tenantId); - ResponseEntity> response = - clusterApiService.approveAclRequests(aclReq, tenantId); + ResponseEntity response = clusterApiService.approveAclRequests(aclReq, tenantId); - Map responseBody = response.getBody(); - String resultAclReq = responseBody.get("result"); - String resultAclNullCheck = Objects.requireNonNull(responseBody).get("result"); + ApiResponse responseBody = response.getBody(); + // String resultAclReq = responseBody.getResult(); + String resultAclNullCheck = Objects.requireNonNull(responseBody).getResult(); if (!Objects.requireNonNull(resultAclNullCheck).contains("success")) { log.error("Error in creating acl {} {}", aclFound, responseBody); logUpdateSyncBackTopics.add( - "Error in Acl creation. Acl:" + aclFound.getTopicname() + " " + resultAclReq); - } else if (resultAclReq.contains("Acl already exists")) { + "Error in Acl creation. Acl:" + aclFound.getTopicname() + " " + resultAclNullCheck); + } else if (resultAclNullCheck.contains("Acl already exists")) { logUpdateSyncBackTopics.add("Acl already exists " + aclFound.getTopicname()); } else { if (!Objects.equals(syncBackAcls.getSourceEnv(), syncBackAcls.getTargetEnv())) { @@ -626,7 +627,7 @@ public String approveAclRequests(String req_no) throws KlawException { String allIps = aclReq.getAcl_ip(); String allSsl = aclReq.getAcl_ssl(); if (aclReq.getReq_no() != null) { - ResponseEntity> response = null; + ResponseEntity response = null; if (aclReq.getAcl_ip() != null) { String[] aclListIp = aclReq.getAcl_ip().split(""); for (String s : aclListIp) { @@ -645,16 +646,19 @@ public String approveAclRequests(String req_no) throws KlawException { aclReq.setAcl_ip(allIps); aclReq.setAcl_ssl(allSsl); - String updateAclReqStatus; + String updateAclReqStatus = null; try { - Map responseBody = response.getBody(); - if (Objects.requireNonNull(Objects.requireNonNull(responseBody).get("result")) - .contains("success")) { + ApiResponse responseBody = Objects.requireNonNull(response).getBody(); + if (Objects.requireNonNull(responseBody).getResult().contains("success")) { String jsonParams = "", aivenAclIdKey = "aivenaclid"; - if (responseBody.containsKey(aivenAclIdKey)) - jsonParams = "{\"" + aivenAclIdKey + "\":\"" + responseBody.get(aivenAclIdKey) + "\"}"; + if (responseBody.getData() instanceof Map) { + Map dataMap = (Map) responseBody.getData(); + if (dataMap.containsKey(aivenAclIdKey)) + jsonParams = "{\"" + aivenAclIdKey + "\":\"" + dataMap.get(aivenAclIdKey) + "\"}"; + } updateAclReqStatus = dbHandle.updateAclRequest(aclReq, userDetails, jsonParams); + } else return "{\"result\":\"failure\"}"; } catch (Exception e) { log.error("Exception ", e); diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index 0b919b758f..9cbf2cc5b0 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -10,14 +10,17 @@ import io.aiven.klaw.dao.KwClusters; import io.aiven.klaw.dao.SchemaRequest; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.model.AclOperation; +import io.aiven.klaw.model.AclOperationType; import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.AclsNativeType; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.ClusterStatus; -import io.aiven.klaw.model.ClusterTopicRequest; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; +import io.aiven.klaw.model.cluster.ClusterAclRequest; +import io.aiven.klaw.model.cluster.ClusterConnectorRequest; +import io.aiven.klaw.model.cluster.ClusterTopicRequest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -280,7 +283,7 @@ public List> getAcls( List> aclListOriginal; try { - String URI_GET_ACLS = "/topics/getAcls/"; + String uriGetAcls = "/topics/getAcls/"; KwClusters kwClusters = manageDatabase .getClusters(KafkaClustersType.KAFKA.value, tenantId) @@ -291,7 +294,7 @@ public List> getAcls( if (KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value.equals(kwClusters.getKafkaFlavor())) { uri = clusterConnUrl - + URI_GET_ACLS + + uriGetAcls + bootstrapHost + "/" + AclsNativeType.AIVEN.name() @@ -308,7 +311,7 @@ public List> getAcls( } else { uri = clusterConnUrl - + URI_GET_ACLS + + uriGetAcls + bootstrapHost + "/" + AclsNativeType.NATIVE.name() @@ -380,11 +383,13 @@ public String approveConnectorRequests( getClusterApiProperties(tenantId); ResponseEntity> response; try { - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("env", kafkaConnectHost); - params.add("connectorName", connectorName); - params.add("connectorConfig", connectorConfig); - params.add("protocol", protocol); + ClusterConnectorRequest clusterConnectorRequest = + ClusterConnectorRequest.builder() + .env(kafkaConnectHost) + .connectorName(connectorName) + .connectorConfig(connectorConfig) + .protocol(protocol) + .build(); String uri; String URI_GET_TOPICS = "/topics/"; @@ -395,7 +400,14 @@ public String approveConnectorRequests( uri = clusterConnUrl + URI_GET_TOPICS + "updateConnector"; } else uri = clusterConnUrl + URI_GET_TOPICS + "deleteConnector"; - response = getMapResponseEntity(params, uri); + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity request = + new HttpEntity<>(clusterConnectorRequest, headers); + response = + getRestTemplate() + .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); if (ApiResultStatus.SUCCESS.value.equals( Objects.requireNonNull(response.getBody()).get("result"))) { @@ -410,19 +422,6 @@ public String approveConnectorRequests( } } - private ResponseEntity> getMapResponseEntity( - MultiValueMap params, String uri) { - ResponseEntity> response; - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - HttpEntity> request = new HttpEntity<>(params, headers); - response = - getRestTemplate() - .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); - return response; - } - public ResponseEntity approveTopicRequests( String topicName, String topicRequestType, @@ -477,23 +476,20 @@ public ResponseEntity approveTopicRequests( return response; } - public ResponseEntity> approveAclRequests(AclRequests aclReq, int tenantId) + public ResponseEntity approveAclRequests(AclRequests aclReq, int tenantId) throws KlawException { log.info("approveAclRequests {}", aclReq); getClusterApiProperties(tenantId); - ResponseEntity> response; + ResponseEntity response; try { String env = aclReq.getEnvironment(); String uri; - String URI_CREATE_ACLS = "/topics/createAcls"; - String URI_DELETE_ACLS = "/topics/deleteAcls"; - - if ("Create".equals(aclReq.getAclType())) uri = clusterConnUrl + URI_CREATE_ACLS; - else uri = clusterConnUrl + URI_DELETE_ACLS; + String uriCreateAcls = "/topics/createAcls"; + String uriDeleteAcls = "/topics/deleteAcls"; - MultiValueMap params = new LinkedMultiValueMap<>(); + ClusterAclRequest clusterAclRequest; Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(env, tenantId); KwClusters kwClusters = manageDatabase @@ -502,23 +498,28 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq // aiven config if (Objects.equals(KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value, kwClusters.getKafkaFlavor())) { - params.add("aclsNativeType", AclsNativeType.AIVEN.name()); - params.add("projectName", kwClusters.getProjectName()); - params.add("serviceName", kwClusters.getServiceName()); - params.add("topic", aclReq.getTopicname()); - params.add("username", aclReq.getAcl_ssl()); + clusterAclRequest = + ClusterAclRequest.builder() + .aclNativeType(AclsNativeType.AIVEN.name()) + .projectName(kwClusters.getProjectName()) + .serviceName(kwClusters.getServiceName()) + .topicName(aclReq.getTopicname()) + .username(aclReq.getAcl_ssl()) + .build(); if (Objects.equals(aclReq.getTopictype(), AclType.PRODUCER.value)) - params.add("permission", "write"); - else params.add("permission", "read"); + clusterAclRequest = clusterAclRequest.toBuilder().permission("write").build(); + else clusterAclRequest = clusterAclRequest.toBuilder().permission("read").build(); - if (Objects.equals(AclOperation.DELETE.value, aclReq.getAclType()) + if (Objects.equals(AclOperationType.DELETE.value, aclReq.getAclType()) && null != aclReq.getJsonParams()) { ObjectMapper objectMapper = new ObjectMapper(); Map jsonObj = objectMapper.readValue(aclReq.getJsonParams(), new TypeReference<>() {}); String aivenAclKey = "aivenaclid"; - if (jsonObj.containsKey(aivenAclKey)) params.add(aivenAclKey, jsonObj.get(aivenAclKey)); + if (jsonObj.containsKey(aivenAclKey)) + clusterAclRequest = + clusterAclRequest.toBuilder().aivenAclKey(jsonObj.get(aivenAclKey)).build(); else { log.error("Error from approveAclRequests : AclId - aivenaclid not found"); throw new KlawException( @@ -526,28 +527,46 @@ public ResponseEntity> approveAclRequests(AclRequests aclReq } } } else { - params.add("aclsNativeType", AclsNativeType.NATIVE.name()); - params.add("env", kwClusters.getBootstrapServers()); - params.add("protocol", kwClusters.getProtocol()); - params.add("clusterName", kwClusters.getClusterName() + "-" + tenantId); - params.add("topicName", aclReq.getTopicname()); - params.add("consumerGroup", aclReq.getConsumergroup()); - params.add("aclType", aclReq.getTopictype()); - params.add("acl_ip", aclReq.getAcl_ip()); - params.add("acl_ssl", aclReq.getAcl_ssl()); - params.add("transactionalId", aclReq.getTransactionalId()); - params.add("aclIpPrincipleType", aclReq.getAclIpPrincipleType().name()); - String aclPatternType = aclReq.getAclPatternType(); - params.add("isPrefixAcl", ("PREFIXED".equals(aclPatternType)) + ""); + clusterAclRequest = + ClusterAclRequest.builder() + .aclNativeType(AclsNativeType.NATIVE.name()) + .env(kwClusters.getBootstrapServers()) + .protocol(kwClusters.getProtocol()) + .clusterName(kwClusters.getClusterName() + "-" + tenantId) + .topicName(aclReq.getTopicname()) + .consumerGroup(aclReq.getConsumergroup()) + .aclType(aclReq.getTopictype()) + .aclIp(aclReq.getAcl_ip()) + .aclSsl(aclReq.getAcl_ssl()) + .transactionalId(aclReq.getTransactionalId()) + .aclIpPrincipleType(aclReq.getAclIpPrincipleType().name()) + .isPrefixAcl("PREFIXED".equals(aclPatternType)) + .build(); + } + + if ("Create".equals(aclReq.getAclType())) { + uri = clusterConnUrl + uriCreateAcls; + clusterAclRequest = + clusterAclRequest.toBuilder().aclOperationType(AclOperationType.CREATE).build(); + } else { + uri = clusterConnUrl + uriDeleteAcls; + clusterAclRequest = + clusterAclRequest.toBuilder().aclOperationType(AclOperationType.DELETE).build(); } - response = getMapResponseEntity(params, uri); + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity request = new HttpEntity<>(clusterAclRequest, headers); + response = + getRestTemplate() + .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); + return response; } catch (Exception e) { log.error("Error from approveAclRequests", e); throw new KlawException("Could not approve acl request. Please contact Administrator."); } - return response; } ResponseEntity postSchema( @@ -774,6 +793,19 @@ private String decodePwd(String pwd) { return ""; } + private ResponseEntity> getMapResponseEntity( + MultiValueMap params, String uri) { + ResponseEntity> response; + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + HttpEntity> request = new HttpEntity<>(params, headers); + response = + getRestTemplate() + .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); + return response; + } + private HttpEntity getHttpEntity() { HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); headers.setContentType(MediaType.APPLICATION_JSON); diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index 85a123bc55..c28fc91370 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -69,17 +69,18 @@ public class TopicControllerService { this.mailService = mailService; } - public Map createTopicsRequest(TopicRequestModel topicRequestReq) - throws KlawException { + public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws KlawException { log.info("createTopicsRequest {}", topicRequestReq); String userDetails = getUserName(); - Map hashMapTopicReqRes = new HashMap<>(); + // Map hashMapTopicReqRes = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_TOPICS)) { - hashMapTopicReqRes.put("result", "Not Authorized"); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result(ApiResultStatus.NOT_AUTHORIZED.value) + .status(HttpStatus.OK) + .build(); } topicRequestReq.setRequestor(userDetails); @@ -92,9 +93,10 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq // tenant filtering if (!getEnvsFromUserId(userDetails).contains(envSelected)) { - hashMapTopicReqRes.put( - "result", "Failure. Not authorized to request topic for this environment."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Not authorized to request topic for this environment.") + .status(HttpStatus.OK) + .build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -105,23 +107,28 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq syncCluster = manageDatabase.getTenantConfig().get(tenantId).getBaseSyncEnvironment(); } catch (Exception e) { log.error("Tenant Configuration not found. " + tenantId, e); - hashMapTopicReqRes.put( - "result", "Failure. Tenant configuration in Server config is missing. Please configure."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Tenant configuration in Server config is missing. Please configure.") + .status(HttpStatus.OK) + .build(); } String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_ENVS"); if (topicRequestReq.getTopicname() == null || topicRequestReq.getTopicname().length() == 0) { - hashMapTopicReqRes.put("result", "Failure. Please fill in topic name."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Please fill in topic name.") + .status(HttpStatus.OK) + .build(); } List topics = getTopicFromName(topicRequestReq.getTopicname(), tenantId); if (topics != null && topics.size() > 0 && !Objects.equals(topics.get(0).getTeamId(), topicRequestReq.getTeamId())) { - hashMapTopicReqRes.put("result", "Failure. This topic is owned by a different team."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. This topic is owned by a different team.") + .status(HttpStatus.OK) + .build(); } boolean promotionOrderCheck = checkInPromotionOrder( @@ -136,25 +143,30 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq .count(); if (devTopicFound != 1) { if (getEnvDetails(syncCluster) == null) { - hashMapTopicReqRes.put("result", "Failure. This topic does not exist in base cluster"); + return ApiResponse.builder() + .result("Failure. This topic does not exist in base cluster.") + .status(HttpStatus.OK) + .build(); } else { - hashMapTopicReqRes.put( - "result", - "Failure. This topic does not exist in " - + getEnvDetails(syncCluster).getName() - + " cluster."); + return ApiResponse.builder() + .result( + "Failure. This topic does not exist in " + + getEnvDetails(syncCluster).getName() + + " cluster.") + .status(HttpStatus.OK) + .build(); } - return hashMapTopicReqRes; } } } else if (!Objects.equals(topicRequestReq.getEnvironment(), syncCluster)) { if (promotionOrderCheck) { - hashMapTopicReqRes.put( - "result", - "Failure. Please request for a topic first in " - + getEnvDetails(syncCluster).getName() - + " cluster."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result( + "Failure. Please request for a topic first in " + + getEnvDetails(syncCluster).getName() + + " cluster.") + .status(HttpStatus.OK) + .build(); } } @@ -168,8 +180,10 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq tenantId) .size() > 0) { - hashMapTopicReqRes.put("result", "Failure. A topic request already exists."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. A topic request already exists.") + .status(HttpStatus.OK) + .build(); } } @@ -184,9 +198,10 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq Objects.equals(topicEx.getEnvironment(), topicRequestReq.getEnvironment())); } if (topicExists) { - hashMapTopicReqRes.put( - "result", "Failure. This topic already exists in the selected cluster."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. This topic already exists in the selected cluster.") + .status(HttpStatus.OK) + .build(); } } @@ -201,7 +216,6 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq copyProperties(topicRequestReq, topicRequestDao); topicRequestDao.setTenantId(tenantId); - hashMapTopicReqRes.put("result", dbHandle.requestForTopic(topicRequestDao).get("result")); mailService.sendMail( topicRequestReq.getTopicname(), null, @@ -210,10 +224,16 @@ public Map createTopicsRequest(TopicRequestModel topicRequestReq dbHandle, TOPIC_CREATE_REQUESTED, commonUtilsService.getLoginUrl()); + return ApiResponse.builder() + .result(dbHandle.requestForTopic(topicRequestDao).get("result")) + .status(HttpStatus.OK) + .build(); } else { - hashMapTopicReqRes.put("result", isValidTopicMap.get("error")); + return ApiResponse.builder() + .result(isValidTopicMap.get("error")) + .status(HttpStatus.OK) + .build(); } - return hashMapTopicReqRes; } private boolean checkInPromotionOrder(String topicname, String envId, String orderOfEnvs) { diff --git a/src/main/resources/static/js/requestAcls.js b/src/main/resources/static/js/requestAcls.js index 94a5a3c321..a251d4cbc8 100644 --- a/src/main/resources/static/js/requestAcls.js +++ b/src/main/resources/static/js/requestAcls.js @@ -220,7 +220,7 @@ app.controller("requestAclsCtrl", function($scope, $http, $location, $window) { $scope.disable_ip=true; $scope.acl_ipaddress=[""]; $scope.alc_ipaddresslength = $scope.acl_ipaddress.length; - $scope.selectedAclType="PRINCIPLE"; // Principle can be Username or CN certificate string + $scope.selectedAclType="PRINCIPAL"; // Principal can be Username or CN certificate string }else{ $scope.disable_ssl=true; $scope.disable_ip=false; @@ -422,7 +422,7 @@ app.controller("requestAclsCtrl", function($scope, $http, $location, $window) { for (var i = 0; i < $scope.acl_ssl.length; i++) { if($scope.acl_ssl[i].length === 0 && $scope.acl_ip_ssl === 'SSL') { - $scope.alertnote = "Please fill in a valid Principle of the Producer/Consumer client"; + $scope.alertnote = "Please fill in a valid Principal of the Producer/Consumer client"; $scope.showAlertToast(); return; } @@ -432,7 +432,7 @@ app.controller("requestAclsCtrl", function($scope, $http, $location, $window) { if(($scope.acl_ipaddress !=null) || ($scope.acl_ssl !=null)){} else { - $scope.alertnote = "Please fill in a valid IP address or Principle of the Producer/Consumer client"; + $scope.alertnote = "Please fill in a valid IP address or Principal of the Producer/Consumer client"; $scope.showAlertToast(); return; } diff --git a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java index ce4f3ab75a..9d72453251 100644 --- a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java +++ b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java @@ -18,6 +18,7 @@ import io.aiven.klaw.dao.TopicRequest; import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KwClustersModel; @@ -28,7 +29,6 @@ import io.aiven.klaw.model.UserInfoModel; import io.aiven.klaw.service.ClusterApiService; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -563,11 +563,9 @@ public void getAclResAgainAndApprove() throws Exception { Object obj = response.get(0); LinkedHashMap hMap = (LinkedHashMap) obj; - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); - + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); when(clusterApiService.approveAclRequests(any(), anyInt())) - .thenReturn(new ResponseEntity<>(resultMap, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); Integer reqNo = hMap.get("req_no"); res = diff --git a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java index 55a7286be4..728deaa557 100644 --- a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java @@ -71,9 +71,9 @@ public void setUp() throws Exception { public void createTopics() throws Exception { TopicRequestModel addTopicRequest = utilMethods.getTopicRequestModel(1001); String jsonReq = new ObjectMapper().writer().writeValueAsString(addTopicRequest); - Map resMap = new HashMap<>(); - resMap.put("result", "success"); - when(topicControllerService.createTopicsRequest(any())).thenReturn(resMap); + ApiResponse apiResponse = + ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).status(HttpStatus.OK).build(); + when(topicControllerService.createTopicsRequest(any())).thenReturn(apiResponse); String response = mvc.perform( diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index 76703b9843..934e4e4b3d 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -22,6 +22,7 @@ import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SyncAclUpdates; import java.sql.Timestamp; import java.util.ArrayList; @@ -243,10 +244,10 @@ public void approveAclRequests() throws KlawException { stubUserInfo(); when(handleDbRequests.selectAcl(anyInt(), anyInt())).thenReturn(aclReq); - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); + + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); when(clusterApiService.approveAclRequests(any(), anyInt())) - .thenReturn(new ResponseEntity<>(resultMap, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(handleDbRequests.updateAclRequest(any(), any(), anyString())).thenReturn("success"); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -264,10 +265,10 @@ public void approveAclRequestsFailure1() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(handleDbRequests.selectAcl(anyInt(), anyInt())).thenReturn(aclReq); - Map resultMap = new HashMap<>(); - resultMap.put("result", "failure"); + + ApiResponse apiResponse = ApiResponse.builder().result("failure").build(); when(clusterApiService.approveAclRequests(any(), anyInt())) - .thenReturn(new ResponseEntity<>(resultMap, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); String result = aclControllerService.approveAclRequests(req_no); assertThat(result).isEqualTo("{\"result\":\"failure\"}"); @@ -283,10 +284,10 @@ public void approveAclRequestsFailure2() throws KlawException { when(handleDbRequests.selectAcl(anyInt(), anyInt())).thenReturn(aclReq); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); + + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); when(clusterApiService.approveAclRequests(any(), anyInt())) - .thenReturn(new ResponseEntity<>(resultMap, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(handleDbRequests.updateAclRequest(any(), any(), anyString())) .thenThrow(new RuntimeException("Error")); diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index 83561e046c..243a2c5ba2 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -18,8 +18,8 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclIPPrincipleType; +import io.aiven.klaw.model.ApiResponse; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -228,10 +228,8 @@ public void approveAclRequestsSuccess1() throws KlawException { aclRequests.setAclType("Create"); aclRequests.setAclIpPrincipleType(AclIPPrincipleType.IP_ADDRESS); - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); - ResponseEntity> responseEntity = - new ResponseEntity<>(resultMap, HttpStatus.OK); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ResponseEntity responseEntity = new ResponseEntity<>(apiResponse, HttpStatus.OK); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); @@ -244,12 +242,11 @@ public void approveAclRequestsSuccess1() throws KlawException { Mockito.anyString(), any(), Mockito.any(), - (ParameterizedTypeReference>) any())) + (ParameterizedTypeReference) any())) .thenReturn(responseEntity); - ResponseEntity> response = - clusterApiService.approveAclRequests(aclRequests, 1); - assertThat(response.getBody()).containsEntry("result", "success"); + ResponseEntity response = clusterApiService.approveAclRequests(aclRequests, 1); + assertThat(response.getBody().getResult()).isEqualTo("success"); } @Test @@ -262,10 +259,8 @@ public void approveAclRequestsSuccess2() throws KlawException { aclRequests.setAclType("Delete"); aclRequests.setAclIpPrincipleType(AclIPPrincipleType.IP_ADDRESS); - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); - ResponseEntity> responseEntity = - new ResponseEntity<>(resultMap, HttpStatus.OK); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ResponseEntity responseEntity = new ResponseEntity<>(apiResponse, HttpStatus.OK); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); @@ -278,12 +273,11 @@ public void approveAclRequestsSuccess2() throws KlawException { Mockito.anyString(), any(), Mockito.any(), - (ParameterizedTypeReference>) any())) + (ParameterizedTypeReference) any())) .thenReturn(responseEntity); - ResponseEntity> response = - clusterApiService.approveAclRequests(aclRequests, 1); - assertThat(response.getBody()).containsEntry("result", "success"); + ResponseEntity response = clusterApiService.approveAclRequests(aclRequests, 1); + assertThat(response.getBody().getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index fbfb4e0505..1d1333fe6f 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -139,9 +139,9 @@ public void createTopicsSuccess() throws KlawException { when(handleDbRequests.requestForTopic(any())).thenReturn(resultMap); when(mailService.getEnvProperty(anyInt(), anyString())).thenReturn("1"); - Map result = topicControllerService.createTopicsRequest(getCorrectTopic()); + ApiResponse apiResponse = topicControllerService.createTopicsRequest(getCorrectTopic()); - assertThat(result.get("result")).isEqualTo("success"); + assertThat(apiResponse.getResult()).isEqualTo("success"); } @Test @@ -161,9 +161,9 @@ public void createTopicsSuccess1() throws KlawException { when(handleDbRequests.requestForTopic(any())).thenReturn(resultMap); when(mailService.getEnvProperty(anyInt(), anyString())).thenReturn("1"); - Map result = topicControllerService.createTopicsRequest(getFailureTopic()); + ApiResponse apiResponse = topicControllerService.createTopicsRequest(getFailureTopic()); - assertThat(result.get("result")).isEqualTo("success"); + assertThat(apiResponse.getResult()).isEqualTo("success"); } // invalid partitions @@ -184,9 +184,9 @@ public void createTopicsFailure() throws KlawException { when(handleDbRequests.requestForTopic(any())).thenReturn(resultMap); when(mailService.getEnvProperty(anyInt(), anyString())).thenReturn("1"); - Map result = topicControllerService.createTopicsRequest(getFailureTopic1()); + ApiResponse apiResponse = topicControllerService.createTopicsRequest(getFailureTopic1()); - assertThat(result).containsEntry("result", "failure"); + assertThat(apiResponse.getResult()).contains("failure"); } @Test @@ -204,17 +204,14 @@ public void createTopicsFailure1() throws KlawException { when(mailService.getEnvProperty(anyInt(), anyString())).thenReturn("1"); - Map result = topicControllerService.createTopicsRequest(getFailureTopic1()); + ApiResponse apiResponse = topicControllerService.createTopicsRequest(getFailureTopic1()); - assertThat(result).containsKey("result"); + assertThat(apiResponse.getResult()).isEqualTo(null); } @Test @Order(7) public void updateSyncTopicsSuccess() { - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); - stubUserInfo(); when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); From cbeee47f83cbca84af2c488cb528cc4e24540b03 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Mon, 3 Oct 2022 15:57:23 +0200 Subject: [PATCH 04/15] - Adding requests for schema - Updating ApiResponse for schema, acl, connector creation - Updating with ApiResponse for schemas, conenctors --- .../aiven/klaw/controller/AclController.java | 13 ++- .../controller/KafkaConnectController.java | 18 +++- .../controller/SchemaRegstryController.java | 32 ++++--- .../klaw/controller/TopicController.java | 18 +++- .../io/aiven/klaw/model/ApiResultStatus.java | 1 + .../klaw/service/AclControllerService.java | 43 +++++++--- .../aiven/klaw/service/ClusterApiService.java | 59 +++++-------- .../EnvsClustersTenantsControllerService.java | 14 +-- .../KafkaConnectControllerService.java | 26 +++--- .../KafkaConnectSyncControllerService.java | 3 +- .../RolesPermissionsControllerService.java | 7 +- .../SchemaRegstryControllerService.java | 30 ++++--- .../klaw/service/TopicControllerService.java | 3 +- .../service/TopicSyncControllerService.java | 7 +- .../service/UsersTeamsControllerService.java | 3 +- .../klaw/service/UtilControllerService.java | 85 ++++++++++--------- .../io/aiven/klaw/UsersTeamsControllerIT.java | 3 +- .../klaw/controller/AclControllerTest.java | 6 +- .../SchemaRegstryControllerTest.java | 4 +- .../klaw/controller/UtilControllerTest.java | 5 +- .../service/AclControllerServiceTest.java | 16 ++-- .../klaw/service/ClusterApiServiceTest.java | 9 +- .../SchemaRegstryControllerServiceTest.java | 43 ++++++---- 23 files changed, 260 insertions(+), 188 deletions(-) diff --git a/src/main/java/io/aiven/klaw/controller/AclController.java b/src/main/java/io/aiven/klaw/controller/AclController.java index a2248a2ef9..3a86f690d7 100644 --- a/src/main/java/io/aiven/klaw/controller/AclController.java +++ b/src/main/java/io/aiven/klaw/controller/AclController.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Map; import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -19,6 +20,7 @@ @RestController @RequestMapping("/") +@Slf4j public class AclController { @Autowired AclControllerService aclControllerService; @@ -71,9 +73,14 @@ public ResponseEntity deleteAclRequests(@RequestParam("req_no") String r } @PostMapping(value = "/execAclRequest") - public ResponseEntity approveAclRequests(@RequestParam("req_no") String req_no) - throws KlawException { - return new ResponseEntity<>(aclControllerService.approveAclRequests(req_no), HttpStatus.OK); + public ResponseEntity approveAclRequests(@RequestParam("req_no") String req_no) { + try { + return new ResponseEntity<>(aclControllerService.approveAclRequests(req_no), HttpStatus.OK); + } catch (KlawException e) { + log.error(e.getMessage()); + return new ResponseEntity<>( + ApiResponse.builder().message("Unable to approve acl request").build(), HttpStatus.OK); + } } @PostMapping(value = "/createDeleteAclSubscriptionRequest") diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java index e8f5cfa062..3b309827c6 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java @@ -1,6 +1,7 @@ package io.aiven.klaw.controller; import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ConnectorOverview; import io.aiven.klaw.model.KafkaConnectorModel; import io.aiven.klaw.model.KafkaConnectorRequestModel; @@ -8,6 +9,7 @@ import java.util.List; import java.util.Map; import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -21,6 +23,7 @@ @RestController @RequestMapping("/") +@Slf4j public class KafkaConnectController { @Autowired KafkaConnectControllerService kafkaConnectControllerService; @@ -63,10 +66,17 @@ public ResponseEntity deleteConnectorRequests( @PostMapping( value = "/execConnectorRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> approveTopicRequests( - @RequestParam("connectorId") String connectorId) throws KlawException { - return new ResponseEntity<>( - kafkaConnectControllerService.approveConnectorRequests(connectorId), HttpStatus.OK); + public ResponseEntity approveTopicRequests( + @RequestParam("connectorId") String connectorId) { + try { + return new ResponseEntity<>( + kafkaConnectControllerService.approveConnectorRequests(connectorId), HttpStatus.OK); + } catch (KlawException e) { + log.error(e.getMessage()); + return new ResponseEntity<>( + ApiResponse.builder().message("Unable to create kafka connector.").build(), + HttpStatus.INTERNAL_SERVER_ERROR); + } } @PostMapping( diff --git a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java index a894d7605e..bd20610aff 100644 --- a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java +++ b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java @@ -1,10 +1,12 @@ package io.aiven.klaw.controller; import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SchemaRequestModel; import io.aiven.klaw.service.SchemaRegstryControllerService; import java.util.List; import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -13,6 +15,7 @@ @RestController @RequestMapping("/") +@Slf4j public class SchemaRegstryController { @Autowired SchemaRegstryControllerService schemaRegstryControllerService; @@ -59,14 +62,17 @@ public ResponseEntity deleteSchemaRequests( @PostMapping( value = "/execSchemaRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity execSchemaRequests( - @RequestParam("avroSchemaReqId") String avroSchemaReqId) throws KlawException { - - String updateTopicReqStatus = - "{\"result\":\"" - + schemaRegstryControllerService.execSchemaRequests(avroSchemaReqId) - + "\"}"; - return new ResponseEntity<>(updateTopicReqStatus, HttpStatus.OK); + public ResponseEntity execSchemaRequests( + @RequestParam("avroSchemaReqId") String avroSchemaReqId) { + try { + return new ResponseEntity<>( + schemaRegstryControllerService.execSchemaRequests(avroSchemaReqId), HttpStatus.OK); + } catch (KlawException e) { + log.error(e.getMessage()); + return new ResponseEntity<>( + ApiResponse.builder().message("Unable to register schema").build(), + HttpStatus.INTERNAL_SERVER_ERROR); + } } @PostMapping( @@ -84,10 +90,12 @@ public ResponseEntity execSchemaRequestsDecline( } @PostMapping(value = "/uploadSchema") - public ResponseEntity uploadSchema( + public ResponseEntity uploadSchema( @Valid @RequestBody SchemaRequestModel addSchemaRequest) { - String schemaaddResult = - "{\"result\":\"" + schemaRegstryControllerService.uploadSchema(addSchemaRequest) + "\"}"; - return new ResponseEntity<>(schemaaddResult, HttpStatus.OK); + return new ResponseEntity<>( + ApiResponse.builder() + .result(schemaRegstryControllerService.uploadSchema(addSchemaRequest)) + .build(), + HttpStatus.OK); } } diff --git a/src/main/java/io/aiven/klaw/controller/TopicController.java b/src/main/java/io/aiven/klaw/controller/TopicController.java index 3ab93b06a0..3858691606 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicController.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -21,15 +22,23 @@ @RestController @RequestMapping("/") +@Slf4j public class TopicController { @Autowired private TopicControllerService topicControllerService; @PostMapping(value = "/createTopics") public ResponseEntity createTopicsRequest( - @Valid @RequestBody TopicRequestModel addTopicRequest) throws KlawException { - return new ResponseEntity<>( - topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); + @Valid @RequestBody TopicRequestModel addTopicRequest) { + try { + return new ResponseEntity<>( + topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); + } catch (KlawException e) { + log.error(e.getMessage()); + return new ResponseEntity<>( + ApiResponse.builder().message("Unable to create a topic request").build(), + HttpStatus.INTERNAL_SERVER_ERROR); + } } @PostMapping( @@ -107,9 +116,10 @@ public ResponseEntity approveTopicRequests(@RequestParam("topicId") return new ResponseEntity<>( topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); } catch (KlawException e) { + log.error(e.getMessage()); return new ResponseEntity<>( ApiResponse.builder() - .message(e.getMessage()) + .message("Unable to approve topics") .status(HttpStatus.INTERNAL_SERVER_ERROR) .build(), HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/io/aiven/klaw/model/ApiResultStatus.java b/src/main/java/io/aiven/klaw/model/ApiResultStatus.java index 0a4a7f7ac5..c1940a3376 100644 --- a/src/main/java/io/aiven/klaw/model/ApiResultStatus.java +++ b/src/main/java/io/aiven/klaw/model/ApiResultStatus.java @@ -3,6 +3,7 @@ public enum ApiResultStatus { SUCCESS("success"), FAILURE("failure"), + AUTHORIZED("Authorized"), NOT_AUTHORIZED("Not Authorized"), ERROR("error"); diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index 17c31b60de..9f8b06d026 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -23,6 +23,7 @@ import io.aiven.klaw.model.AclOperationType; import io.aiven.klaw.model.AclRequestsModel; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; import io.aiven.klaw.model.PermissionType; @@ -46,6 +47,7 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -242,7 +244,7 @@ public Map> updateSyncBackAcls(SyncBackAcls syncBackAcls) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { List notAuth = new ArrayList<>(); - notAuth.add("Not Authorized"); + notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); resultMap.put("result", notAuth); return resultMap; } @@ -601,28 +603,40 @@ public String createDeleteAclSubscriptionRequest(String req_no) { return "{\"result\":\"" + execRes + "\"}"; } - public String approveAclRequests(String req_no) throws KlawException { + public ApiResponse approveAclRequests(String req_no) throws KlawException { log.info("approveAclRequests {}", req_no); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { - return "{\"result\":\" Not Authorized. \"}"; + return ApiResponse.builder() + .result(ApiResultStatus.NOT_AUTHORIZED.value) + .status(HttpStatus.OK) + .build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); AclRequests aclReq = dbHandle.selectAcl(Integer.parseInt(req_no), tenantId); if (Objects.equals(aclReq.getUsername(), userDetails)) - return "{\"result\":\"You are not allowed to approve your own subscription requests.\"}"; + return ApiResponse.builder() + .result("You are not allowed to approve your own subscription requests.") + .status(HttpStatus.OK) + .build(); if (!RequestStatus.created.name().equals(aclReq.getAclstatus())) { - return "{\"result\":\"This request does not exist anymore.\"}"; + return ApiResponse.builder() + .result("This request does not exist anymore.") + .status(HttpStatus.OK) + .build(); } // tenant filtering if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder() + .result(ApiResultStatus.NOT_AUTHORIZED.value) + .status(HttpStatus.OK) + .build(); String allIps = aclReq.getAcl_ip(); String allSsl = aclReq.getAcl_ssl(); @@ -659,10 +673,17 @@ public String approveAclRequests(String req_no) throws KlawException { } updateAclReqStatus = dbHandle.updateAclRequest(aclReq, userDetails, jsonParams); - } else return "{\"result\":\"failure\"}"; + } else + return ApiResponse.builder() + .result(ApiResultStatus.FAILURE.value) + .status(HttpStatus.OK) + .build(); } catch (Exception e) { log.error("Exception ", e); - return "{\"result\":\"failure " + e.toString() + "\"}"; + return ApiResponse.builder() + .result(ApiResultStatus.FAILURE.value) + .status(HttpStatus.OK) + .build(); } mailService.sendMail( @@ -673,8 +694,10 @@ public String approveAclRequests(String req_no) throws KlawException { dbHandle, ACL_REQUEST_APPROVED, commonUtilsService.getLoginUrl()); - return "{\"result\":\"" + updateAclReqStatus + "\"}"; - } else return "{\"result\":\"Record not found !\"}"; + return ApiResponse.builder().result(updateAclReqStatus).status(HttpStatus.OK).build(); + } else { + return ApiResponse.builder().result("Record not found !").status(HttpStatus.OK).build(); + } } public String declineAclRequests(String req_no, String reasonToDecline) { diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index 9cbf2cc5b0..8152eb6914 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -20,6 +20,7 @@ import io.aiven.klaw.model.KafkaFlavors; import io.aiven.klaw.model.cluster.ClusterAclRequest; import io.aiven.klaw.model.cluster.ClusterConnectorRequest; +import io.aiven.klaw.model.cluster.ClusterSchemaRequest; import io.aiven.klaw.model.cluster.ClusterTopicRequest; import java.io.File; import java.io.FileInputStream; @@ -127,10 +128,10 @@ public String getClusterApiStatus(String clusterApiUrl, boolean testConnection, getClusterApiProperties(tenantId); String clusterStatus; try { - String URI_CLUSTER_API_STATUS = "/topics/getApiStatus"; + String uriClusterApiStatus = "/topics/getApiStatus"; String uri; - if (testConnection) uri = clusterApiUrl + URI_CLUSTER_API_STATUS; - else uri = clusterConnUrl + URI_CLUSTER_API_STATUS; // from stored kw props + if (testConnection) uri = clusterApiUrl + uriClusterApiStatus; + else uri = clusterConnUrl + uriClusterApiStatus; // from stored kw props ResponseEntity resultBody = getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); @@ -569,39 +570,34 @@ public ResponseEntity approveAclRequests(AclRequests aclReq, int te } } - ResponseEntity postSchema( + ResponseEntity postSchema( SchemaRequest schemaRequest, String env, String topicName, int tenantId) throws KlawException { log.info("postSchema {} {}", topicName, env); getClusterApiProperties(tenantId); - ResponseEntity response; + ResponseEntity response; try { - String URI_POST_SCHEMA = "/topics/postSchema"; - String uri = clusterConnUrl + URI_POST_SCHEMA; + String uriPostSchema = "/topics/postSchema"; + String uri = clusterConnUrl + uriPostSchema; - MultiValueMap params = new LinkedMultiValueMap<>(); Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(env, tenantId); - String bootstrapHost = - manageDatabase - .getClusters(KafkaClustersType.SCHEMA_REGISTRY.value, tenantId) - .get(envSelected.getClusterId()) - .getBootstrapServers(); - params.add( - "protocol", + KwClusters kwClusters = manageDatabase .getClusters(KafkaClustersType.SCHEMA_REGISTRY.value, tenantId) - .get(envSelected.getClusterId()) - .getProtocol()); - params.add("env", bootstrapHost); - params.add("topicName", topicName); - params.add("fullSchema", schemaRequest.getSchemafull()); + .get(envSelected.getClusterId()); + ClusterSchemaRequest clusterSchemaRequest = + ClusterSchemaRequest.builder() + .protocol(kwClusters.getProtocol()) + .env(kwClusters.getBootstrapServers()) + .topicName(topicName) + .fullSchema(schemaRequest.getSchemafull()) + .build(); - HttpHeaders headers = - createHeaders(clusterApiUser, clusterApiPwd); // createHeaders("user1", "pwd"); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); + headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity> request = new HttpEntity<>(params, headers); - response = getRestTemplate().postForEntity(uri, request, String.class); + HttpEntity request = new HttpEntity<>(clusterSchemaRequest, headers); + response = getRestTemplate().postForEntity(uri, request, ApiResponse.class); } catch (Exception e) { log.error("Error from postSchema ", e); throw new KlawException("Could not post schema. Please contact Administrator."); @@ -793,19 +789,6 @@ private String decodePwd(String pwd) { return ""; } - private ResponseEntity> getMapResponseEntity( - MultiValueMap params, String uri) { - ResponseEntity> response; - HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - HttpEntity> request = new HttpEntity<>(params, headers); - response = - getRestTemplate() - .exchange(uri, HttpMethod.POST, request, new ParameterizedTypeReference<>() {}); - return response; - } - private HttpEntity getHttpEntity() { HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); headers.setContentType(MediaType.APPLICATION_JSON); diff --git a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 2c4016ec21..3729fda9e7 100644 --- a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -704,7 +704,7 @@ public Map addNewCluster(KwClustersModel kwClustersModel) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_CLUSTERS)) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } @@ -831,7 +831,7 @@ public Map deleteEnvironment(String envId, String envType) { int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } @@ -976,7 +976,7 @@ public Map addTenantId(KwTenantModel kwTenantModel, boolean isEx if (isExternal && commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ADD_TENANT)) { - addTenantStatus.put("result", "Not Authorized"); + addTenantStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return addTenantStatus; } @@ -1071,12 +1071,12 @@ public Map deleteTenant() { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } int tenantId = commonUtilsService.getTenantId(getUserName()); if (tenantId == DEFAULT_TENANT_ID) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } String tenantName = manageDatabase.getTenantMap().get(tenantId); @@ -1111,7 +1111,7 @@ public Map updateTenant(String orgName) { Map resultMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -1138,7 +1138,7 @@ public Map udpateTenantExtension(String selectedTenantExtensionP Map resultMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", "Not Authorized"); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resultMap; } diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index f796addc8e..377b7d1d09 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -47,7 +47,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_CONNECTORS)) { - hashMapTopicReqRes.put("result", "Not Authorized"); + hashMapTopicReqRes.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return hashMapTopicReqRes; } @@ -460,15 +460,14 @@ private String createConnectorConfig(KafkaConnectorRequest connectorRequest) { } } - public Map approveConnectorRequests(String connectorId) throws KlawException { + public ApiResponse approveConnectorRequests(String connectorId) throws KlawException { log.info("approveConnectorRequests {}", connectorId); Map resultMap = new HashMap<>(); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { - resultMap.put("result", "Not Authorized"); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } KafkaConnectorRequest connectorRequest = @@ -482,25 +481,23 @@ public Map approveConnectorRequests(String connectorId) throws K jsonConnectorConfig = createConnectorConfig(connectorRequest); } catch (Exception e) { log.error("Exception:", e); - resultMap.put("result", "Failure " + e.getMessage()); - return resultMap; + throw new KlawException("Unable to create kafka connector."); } if (connectorRequest.getRequestor().equals(userDetails)) { - resultMap.put("result", "You are not allowed to approve your own connector requests."); - return resultMap; + return ApiResponse.builder() + .result("You are not allowed to approve your own connector requests.") + .build(); } if (!RequestStatus.created.name().equals(connectorRequest.getConnectorStatus())) { - resultMap.put("result", "This request does not exist anymore."); - return resultMap; + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(connectorRequest.getEnvironment())) { - resultMap.put("result", "Not Authorized"); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -563,8 +560,7 @@ public Map approveConnectorRequests(String connectorId) throws K } } - resultMap.put("result", updateTopicReqStatus); - return resultMap; + return ApiResponse.builder().result(updateTopicReqStatus).build(); } private void setConnectorHistory( @@ -649,7 +645,7 @@ public Map createConnectorDeleteRequest(String connectorName, St Map hashMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_CONNECTORS)) { - hashMap.put("result", "Not Authorized"); + hashMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return hashMap; } diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java index 1d05c3388a..7c8b7e8114 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java @@ -8,6 +8,7 @@ import io.aiven.klaw.dao.KwKafkaConnector; import io.aiven.klaw.dao.Team; import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaConnectorModel; import io.aiven.klaw.model.PermissionType; @@ -70,7 +71,7 @@ public Map updateSyncConnectors(List updat Map response = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_CONNECTORS)) { - response.put("result", "Not Authorized"); + response.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return response; } diff --git a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java index d124a7fddb..f8a59ec8c3 100644 --- a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java @@ -2,6 +2,7 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.KwRolesPermissions; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwRolesPermissionsModel; import io.aiven.klaw.model.PermissionType; import java.util.*; @@ -104,7 +105,7 @@ public Map updatePermissions(KwRolesPermissionsModel[] permissio Map updatedPermsMapStatus = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { - updatedPermsMapStatus.put("result", "Not Authorized"); + updatedPermsMapStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return updatedPermsMapStatus; } @@ -151,7 +152,7 @@ public Map deleteRole(String roleId) { Map deleteRoleStatus = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { - deleteRoleStatus.put("result", "Not Authorized"); + deleteRoleStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return deleteRoleStatus; } @@ -173,7 +174,7 @@ public Map addRoleId(String roleId) { Map addRoleStatus = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { - addRoleStatus.put("result", "Not Authorized"); + addRoleStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return addRoleStatus; } diff --git a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java index b9662be0ea..a6026f5917 100644 --- a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java +++ b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java @@ -10,6 +10,8 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.RequestStatus; import io.aiven.klaw.model.SchemaRequestModel; @@ -185,12 +187,12 @@ public String deleteSchemaRequests(String avroSchemaId) { } } - public String execSchemaRequests(String avroSchemaId) throws KlawException { + public ApiResponse execSchemaRequests(String avroSchemaId) throws KlawException { log.info("execSchemaRequests {}", avroSchemaId); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } SchemaRequest schemaRequest = @@ -199,21 +201,23 @@ public String execSchemaRequests(String avroSchemaId) throws KlawException { .selectSchemaRequest(Integer.parseInt(avroSchemaId), tenantId); if (Objects.equals(schemaRequest.getUsername(), userDetails)) - return "{\"result\":\"You are not allowed to approve your own schema requests.\"}"; + return ApiResponse.builder() + .result("You are not allowed to approve your own schema requests.") + .build(); List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); - ResponseEntity response = + ResponseEntity response = clusterApiService.postSchema( schemaRequest, schemaRequest.getEnvironment(), schemaRequest.getTopicname(), tenantId); - String responseDb; HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); - if (Objects.requireNonNull(response.getBody()).contains("id\":")) { + if (Objects.requireNonNull(Objects.requireNonNull(response.getBody()).getResult()) + .contains("id\":")) { try { - responseDb = dbHandle.updateSchemaRequest(schemaRequest, userDetails); + String responseDb = dbHandle.updateSchemaRequest(schemaRequest, userDetails); mailService.sendMail( schemaRequest.getTopicname(), null, @@ -222,16 +226,16 @@ public String execSchemaRequests(String avroSchemaId) throws KlawException { dbHandle, SCHEMA_REQUEST_APPROVED, commonUtilsService.getLoginUrl()); + return ApiResponse.builder().result(responseDb).build(); } catch (Exception e) { log.error("Exception:", e); - return e.getMessage(); + throw new KlawException(e.getMessage()); } - return responseDb; } else { - String errStr = response.getBody(); + String errStr = response.getBody().getResult(); if (errStr.length() > 100) errStr = errStr.substring(0, 98) + "..."; - return "Failure in uploading schema. Error : " + errStr; + return ApiResponse.builder().result("Failure in uploading schema. Error : " + errStr).build(); } } @@ -285,7 +289,7 @@ public String uploadSchema(SchemaRequestModel schemaRequest) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { - return "Not Authorized"; + return ApiResultStatus.NOT_AUTHORIZED.value; } try { diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index c28fc91370..66da170db8 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -206,7 +206,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws } Env env = getEnvDetails(envSelected); - Map isValidTopicMap = validateParameters(topicRequestReq, env, topicPartitions, topicRf); String validTopicStatus = isValidTopicMap.get("status"); @@ -299,7 +298,7 @@ public Map createTopicDeleteRequest(String topicName, String env Map hashMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_TOPICS)) { - hashMap.put("result", "Not Authorized"); + hashMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return hashMap; } diff --git a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index 212c7423cd..974fbfd248 100644 --- a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -10,6 +10,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.RequestStatus; @@ -499,7 +500,7 @@ public Map> updateSyncBackTopics(SyncBackTopics syncBackTop if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { List notAuth = new ArrayList<>(); - notAuth.add("Not Authorized"); + notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); resultMap.put("result", notAuth); return resultMap; } @@ -833,7 +834,7 @@ public Map> updateSyncTopicsBulk(SyncTopicsBulk syncTopicsB if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { List notAuth = new ArrayList<>(); - notAuth.add("Not Authorized"); + notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); resultMap.put("result", notAuth); return resultMap; } @@ -971,7 +972,7 @@ public Map updateSyncTopics(List updatedSyncTo Map response = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { - response.put("result", "Not Authorized"); + response.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return response; } diff --git a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index 57e8b0f0bb..d6fcc173ec 100644 --- a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -9,6 +9,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.EntityType; import io.aiven.klaw.model.MetadataOperationType; import io.aiven.klaw.model.PermissionType; @@ -438,7 +439,7 @@ public Map addNewUser(UserInfoModel newUser, boolean isExternal) if (isExternal && commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { - resMap.put("result", "Not Authorized"); + resMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); return resMap; } diff --git a/src/main/java/io/aiven/klaw/service/UtilControllerService.java b/src/main/java/io/aiven/klaw/service/UtilControllerService.java index 656b4fc28c..9f2dccca93 100644 --- a/src/main/java/io/aiven/klaw/service/UtilControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UtilControllerService.java @@ -5,6 +5,7 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.*; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwMetadataUpdates; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.RequestStatus; @@ -247,44 +248,44 @@ public Map getAuth() { if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) canUpdatePermissions = "NotAuthorized"; - else canUpdatePermissions = "Authorized"; + else canUpdatePermissions = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) addEditRoles = "NotAuthorized"; - else addEditRoles = "Authorized"; + else addEditRoles = ApiResultStatus.AUTHORIZED.value; String canShutdownKw; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SHUTDOWN_KLAW)) { canShutdownKw = "NotAuthorized"; - } else canShutdownKw = "Authorized"; + } else canShutdownKw = ApiResultStatus.AUTHORIZED.value; String syncBackTopics, syncBackAcls; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_BACK_TOPICS)) { syncBackTopics = "NotAuthorized"; - } else syncBackTopics = "Authorized"; + } else syncBackTopics = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { syncBackAcls = "NotAuthorized"; - } else syncBackAcls = "Authorized"; + } else syncBackAcls = ApiResultStatus.AUTHORIZED.value; String addUser, addTeams; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_USERS)) { addUser = "NotAuthorized"; - } else addUser = "Authorized"; + } else addUser = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_TEAMS)) { addTeams = "NotAuthorized"; - } else addTeams = "Authorized"; + } else addTeams = ApiResultStatus.AUTHORIZED.value; String viewKafkaConnect; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.VIEW_CONNECTORS)) { viewKafkaConnect = "NotAuthorized"; - } else viewKafkaConnect = "Authorized"; + } else viewKafkaConnect = ApiResultStatus.AUTHORIZED.value; String requestTopics; String requestAcls; @@ -294,26 +295,27 @@ public Map getAuth() { if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.REQUEST_CREATE_TOPICS)) { requestTopics = "NotAuthorized"; - } else requestTopics = "Authorized"; + } else requestTopics = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { requestAcls = "NotAuthorized"; - } else requestAcls = "Authorized"; + } else requestAcls = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.REQUEST_CREATE_SCHEMAS)) { requestSchemas = "NotAuthorized"; - } else requestSchemas = "Authorized"; + } else requestSchemas = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.REQUEST_CREATE_CONNECTORS)) { requestConnector = "NotAuthorized"; - } else requestConnector = "Authorized"; + } else requestConnector = ApiResultStatus.AUTHORIZED.value; - if ("Authorized".equals(requestTopics) - || "Authorized".equals(requestAcls) - || "Authorized".equals(requestSchemas) - || "Authorized".equals(requestConnector)) requestItems = "Authorized"; + if (ApiResultStatus.AUTHORIZED.value.equals(requestTopics) + || ApiResultStatus.AUTHORIZED.value.equals(requestAcls) + || ApiResultStatus.AUTHORIZED.value.equals(requestSchemas) + || ApiResultStatus.AUTHORIZED.value.equals(requestConnector)) + requestItems = ApiResultStatus.AUTHORIZED.value; else requestItems = "NotAuthorized"; String approveDeclineTopics; @@ -325,37 +327,42 @@ public Map getAuth() { if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_TOPICS)) { approveDeclineTopics = "NotAuthorized"; - } else approveDeclineTopics = "Authorized"; + } else approveDeclineTopics = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_SUBSCRIPTIONS)) { approveDeclineSubscriptions = "NotAuthorized"; - } else approveDeclineSubscriptions = "Authorized"; + } else approveDeclineSubscriptions = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_SCHEMAS)) { approveDeclineSchemas = "NotAuthorized"; - } else approveDeclineSchemas = "Authorized"; + } else approveDeclineSchemas = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_CONNECTORS)) { approveDeclineConnectors = "NotAuthorized"; - } else approveDeclineConnectors = "Authorized"; + } else approveDeclineConnectors = ApiResultStatus.AUTHORIZED.value; - if ("Authorized".equals(approveDeclineTopics) - || "Authorized".equals(approveDeclineSubscriptions) - || "Authorized".equals(approveDeclineSchemas) - || "Authorized".equals(approveDeclineConnectors) - || "Authorized".equals(addUser)) approveAtleastOneRequest = "Authorized"; + if (ApiResultStatus.AUTHORIZED.value.equals(approveDeclineTopics) + || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSubscriptions) + || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSchemas) + || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineConnectors) + || ApiResultStatus.AUTHORIZED.value.equals(addUser)) + approveAtleastOneRequest = ApiResultStatus.AUTHORIZED.value; String redirectionPage = ""; - if ("Authorized".equals(approveAtleastOneRequest)) { - if (outstandingTopicReqsInt > 0 && "Authorized".equals(approveDeclineTopics)) + if (ApiResultStatus.AUTHORIZED.value.equals(approveAtleastOneRequest)) { + if (outstandingTopicReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineTopics)) redirectionPage = "execTopics"; - else if (outstandingAclReqsInt > 0 && "Authorized".equals(approveDeclineSubscriptions)) + else if (outstandingAclReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSubscriptions)) redirectionPage = "execAcls"; - else if (outstandingSchemasReqsInt > 0 && "Authorized".equals(approveDeclineSchemas)) + else if (outstandingSchemasReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSchemas)) redirectionPage = "execSchemas"; - else if (outstandingConnectorReqsInt > 0 && "Authorized".equals(approveDeclineConnectors)) + else if (outstandingConnectorReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineConnectors)) redirectionPage = "execConnectors"; - else if (outstandingUserReqsInt > 0 && "Authorized".equals(addUser)) + else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(addUser)) redirectionPage = "execUsers"; } @@ -364,11 +371,11 @@ else if (outstandingUserReqsInt > 0 && "Authorized".equals(addUser)) if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_TOPICS) || commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_SUBSCRIPTIONS)) { syncTopicsAcls = "NotAuthorized"; - } else syncTopicsAcls = "Authorized"; + } else syncTopicsAcls = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_CONNECTORS)) { syncConnectors = "NotAuthorized"; - } else syncConnectors = "Authorized"; + } else syncConnectors = ApiResultStatus.AUTHORIZED.value; String addDeleteEditTenants; String addDeleteEditEnvs; @@ -378,11 +385,11 @@ else if (outstandingUserReqsInt > 0 && "Authorized".equals(addUser)) if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.UPDATE_SERVERCONFIG)) updateServerConfig = "NotAuthorized"; - else updateServerConfig = "Authorized"; + else updateServerConfig = ApiResultStatus.AUTHORIZED.value; if (tenantId == KwConstants.DEFAULT_TENANT_ID && !commonUtilsService.isNotAuthorizedUser(userName, PermissionType.UPDATE_SERVERCONFIG)) - showServerConfigEnvProperties = "Authorized"; + showServerConfigEnvProperties = ApiResultStatus.AUTHORIZED.value; else showServerConfigEnvProperties = "NotAuthorized"; if (tenantId == KwConstants.DEFAULT_TENANT_ID @@ -393,16 +400,16 @@ else if (outstandingUserReqsInt > 0 && "Authorized".equals(addUser)) .getHandleDbRequests() .getUsersInfo(userName) .getRole())) // allow adding tenants only to "default" - addDeleteEditTenants = "Authorized"; + addDeleteEditTenants = ApiResultStatus.AUTHORIZED.value; else addDeleteEditTenants = "NotAuthorized"; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_ENVS)) addDeleteEditEnvs = "NotAuthorized"; - else addDeleteEditEnvs = "Authorized"; + else addDeleteEditEnvs = ApiResultStatus.AUTHORIZED.value; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) addDeleteEditClusters = "NotAuthorized"; - else addDeleteEditClusters = "Authorized"; + else addDeleteEditClusters = ApiResultStatus.AUTHORIZED.value; if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) dashboardData.put("adAuthRoleEnabled", "true"); @@ -410,7 +417,7 @@ else if (outstandingUserReqsInt > 0 && "Authorized".equals(addUser)) if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.VIEW_TOPICS)) viewTopics = "NotAuthorized"; - else viewTopics = "Authorized"; + else viewTopics = ApiResultStatus.AUTHORIZED.value; String companyInfo = manageDatabase.getTenantFullConfig(tenantId).getOrgName(); if (companyInfo == null || companyInfo.equals("")) { diff --git a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java index 9465675c7c..75e173f55b 100644 --- a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java +++ b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.TeamModel; import io.aiven.klaw.model.UserInfoModel; import java.util.List; @@ -233,7 +234,7 @@ public void createTeamFailureNotAuthorized() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("Not Authorized"); + assertThat(response).contains(ApiResultStatus.NOT_AUTHORIZED.value); } // Delete team success diff --git a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java index 9eb3d3e922..0219a659ec 100644 --- a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java @@ -11,6 +11,7 @@ import io.aiven.klaw.UtilMethods; import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SyncAclUpdates; import io.aiven.klaw.model.TopicOverview; import io.aiven.klaw.service.AclControllerService; @@ -161,7 +162,8 @@ public void deleteAclRequests() throws Exception { @Test public void approveAclRequests() throws Exception { - when(aclControllerService.approveAclRequests(anyString())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(aclControllerService.approveAclRequests(anyString())).thenReturn(apiResponse); String response = mvc.perform( @@ -174,7 +176,7 @@ public void approveAclRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).isEqualTo("success"); + assertThat(response).contains("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java index a84fd03875..48087bd1ac 100644 --- a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.aiven.klaw.UtilMethods; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SchemaRequestModel; import io.aiven.klaw.service.SchemaRegstryControllerService; import java.util.List; @@ -91,7 +92,8 @@ public void deleteSchemaRequests() throws Exception { @Test @Order(3) public void execSchemaRequests() throws Exception { - when(schemaRegstryControllerService.execSchemaRequests(anyString())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(schemaRegstryControllerService.execSchemaRequests(anyString())).thenReturn(apiResponse); String response = mvc.perform( diff --git a/src/test/java/io/aiven/klaw/controller/UtilControllerTest.java b/src/test/java/io/aiven/klaw/controller/UtilControllerTest.java index 2c77e8bb65..67544cc6d9 100644 --- a/src/test/java/io/aiven/klaw/controller/UtilControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/UtilControllerTest.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.service.UtilControllerService; import java.util.HashMap; import org.junit.jupiter.api.*; @@ -36,7 +37,7 @@ public void setUp() { @Order(1) public void getAuth() throws Exception { HashMap hMap = new HashMap<>(); - hMap.put("status", "Authorized"); + hMap.put("status", ApiResultStatus.AUTHORIZED.value); when(utilControllerService.getAuth()).thenReturn(hMap); String res = @@ -50,7 +51,7 @@ public void getAuth() throws Exception { .getContentAsString(); HashMap response = new ObjectMapper().readValue(res, HashMap.class); - assertThat(response).containsEntry("status", "Authorized"); + assertThat(response).containsEntry("status", ApiResultStatus.AUTHORIZED.value); } @Test diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index 934e4e4b3d..90697f638d 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -252,8 +252,8 @@ public void approveAclRequests() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - String result = aclControllerService.approveAclRequests("112"); - assertThat(result).isEqualTo("{\"result\":\"success\"}"); + ApiResponse apiResp = aclControllerService.approveAclRequests("112"); + assertThat(apiResp.getResult()).isEqualTo("success"); } @Test @@ -270,8 +270,8 @@ public void approveAclRequestsFailure1() throws KlawException { when(clusterApiService.approveAclRequests(any(), anyInt())) .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); - String result = aclControllerService.approveAclRequests(req_no); - assertThat(result).isEqualTo("{\"result\":\"failure\"}"); + ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); + assertThat(apiResp.getResult()).isEqualTo("failure"); } @Test @@ -291,8 +291,8 @@ public void approveAclRequestsFailure2() throws KlawException { when(handleDbRequests.updateAclRequest(any(), any(), anyString())) .thenThrow(new RuntimeException("Error")); - String result = aclControllerService.approveAclRequests(req_no); - assertThat(result).contains("failure"); + ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); + assertThat(apiResp.getResult()).isEqualTo("failure"); } @Test @@ -307,8 +307,8 @@ public void approveAclRequestsFailure3() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - String result = aclControllerService.approveAclRequests(req_no); - assertThat(result).isEqualTo("{\"result\":\"This request does not exist anymore.\"}"); + ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); + assertThat(apiResp.getResult()).isEqualTo("This request does not exist anymore."); } @Test diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index 243a2c5ba2..c8dddd78f4 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -301,18 +301,21 @@ public void postSchemaSucess() throws KlawException { String envSel = "DEV"; String topicName = "testtopic"; + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ResponseEntity response = new ResponseEntity<>(apiResponse, HttpStatus.OK); + when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getBootstrapServers()).thenReturn("clusters"); when(kwClusters.getProtocol()).thenReturn("PLAINTEXT"); when(kwClusters.getClusterName()).thenReturn("cluster"); - when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(String.class))) + when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(ApiResponse.class))) .thenReturn(response); - ResponseEntity result = + ResponseEntity result = clusterApiService.postSchema(schemaRequest, envSel, topicName, 1); - assertThat(result.getBody()).isEqualTo("success"); + assertThat(result.getBody().getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java index 109b7cfbec..5d2e4f2822 100644 --- a/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java @@ -14,6 +14,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SchemaRequestModel; import java.sql.Timestamp; import java.util.ArrayList; @@ -140,8 +141,9 @@ public void deleteSchemaRequestsFailure() { public void execSchemaRequestsSuccess() throws KlawException { int schemaReqId = 1001; - ResponseEntity response = - new ResponseEntity<>("Schema registered id\": 215", HttpStatus.OK); + ApiResponse apiResponse = ApiResponse.builder().result("Schema registered id\": 215").build(); + + ResponseEntity response = new ResponseEntity<>(apiResponse, HttpStatus.OK); SchemaRequest schemaRequest = new SchemaRequest(); schemaRequest.setSchemafull("schema.."); schemaRequest.setUsername("kwuserb"); @@ -158,8 +160,8 @@ public void execSchemaRequestsSuccess() throws KlawException { when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - String result = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); - assertThat(result).contains("success"); + ApiResponse resultResp = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); + assertThat(resultResp.getResult()).contains("success"); } @Test @@ -167,7 +169,8 @@ public void execSchemaRequestsSuccess() throws KlawException { public void execSchemaRequestsFailure1() throws KlawException { int schemaReqId = 1001; - ResponseEntity response = new ResponseEntity<>("Schema not registered", HttpStatus.OK); + ApiResponse apiResponse = ApiResponse.builder().result("Schema not registered").build(); + ResponseEntity response = new ResponseEntity<>(apiResponse, HttpStatus.OK); SchemaRequest schemaRequest = new SchemaRequest(); schemaRequest.setSchemafull("schema.."); schemaRequest.setUsername("kwuserb"); @@ -184,17 +187,18 @@ public void execSchemaRequestsFailure1() throws KlawException { when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - String result = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); - assertThat(result).contains("Failure"); + ApiResponse resultResp = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); + assertThat(resultResp.getResult()).contains("Schema not registered"); } - @Test + @Test() @Order(6) - public void execSchemaRequestsFailure2() throws KlawException { + public void execSchemaRequestsFailure2() { int schemaReqId = 1001; - ResponseEntity response = - new ResponseEntity<>("Schema registered id\": 215", HttpStatus.OK); + ApiResponse apiResponse = ApiResponse.builder().result("Schema registered id\": 215").build(); + ResponseEntity response = new ResponseEntity<>(apiResponse, HttpStatus.OK); + SchemaRequest schemaRequest = new SchemaRequest(); schemaRequest.setSchemafull("schema.."); schemaRequest.setUsername("kwuserb"); @@ -203,17 +207,24 @@ public void execSchemaRequestsFailure2() throws KlawException { stubUserInfo(); when(handleDbRequests.selectSchemaRequest(anyInt(), anyInt())).thenReturn(schemaRequest); - when(clusterApiService.postSchema(any(), anyString(), anyString(), anyInt())) - .thenReturn(response); + try { + when(clusterApiService.postSchema(any(), anyString(), anyString(), anyInt())) + .thenReturn(response); + } catch (KlawException e) { + throw new RuntimeException(e); + } when(handleDbRequests.updateSchemaRequest(any(), anyString())) - .thenThrow(new RuntimeException("Error")); + .thenThrow(new RuntimeException("Error in registering")); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - String result = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); - assertThat(result).contains("Error"); + try { + schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); + } catch (KlawException e) { + assertThat(e.getMessage()).contains("Error in registering"); + } } @Test From 269e73296c2c2a11ca305782f0f07ef846f91349 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Mon, 3 Oct 2022 16:21:40 +0200 Subject: [PATCH 05/15] Add new req files --- .../klaw/model/cluster/ClusterAclRequest.java | 46 +++++++++++++++++++ .../cluster/ClusterConnectorRequest.java | 17 +++++++ .../model/cluster/ClusterSchemaRequest.java | 17 +++++++ 3 files changed, 80 insertions(+) create mode 100644 src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java create mode 100644 src/main/java/io/aiven/klaw/model/cluster/ClusterConnectorRequest.java create mode 100644 src/main/java/io/aiven/klaw/model/cluster/ClusterSchemaRequest.java diff --git a/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java b/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java new file mode 100644 index 0000000000..e082439bc5 --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java @@ -0,0 +1,46 @@ +package io.aiven.klaw.model.cluster; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.aiven.klaw.model.AclOperationType; +import java.io.Serializable; +import lombok.Builder; + +@Builder(toBuilder = true) +public class ClusterAclRequest implements Serializable { + + @JsonProperty private String aclNativeType; + + @JsonProperty private String projectName; + + @JsonProperty private String serviceName; + + @JsonProperty private String username; + + @JsonProperty private String permission; + + @JsonProperty private String env; + + @JsonProperty private String protocol; + + @JsonProperty private String clusterName; + + @JsonProperty private String topicName; + + @JsonProperty private String consumerGroup; + + @JsonProperty private String aclType; + + @JsonProperty private String aclIp; + + @JsonProperty private String aclSsl; + + @JsonProperty private String transactionalId; + + @JsonProperty private String aclIpPrincipleType; + + @JsonProperty private boolean isPrefixAcl; + + @JsonProperty private String aivenAclKey; + + @JsonProperty private AclOperationType aclOperationType; +} diff --git a/src/main/java/io/aiven/klaw/model/cluster/ClusterConnectorRequest.java b/src/main/java/io/aiven/klaw/model/cluster/ClusterConnectorRequest.java new file mode 100644 index 0000000000..f49ae24bfa --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/cluster/ClusterConnectorRequest.java @@ -0,0 +1,17 @@ +package io.aiven.klaw.model.cluster; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import lombok.Builder; + +@Builder(toBuilder = true) +public class ClusterConnectorRequest implements Serializable { + + @JsonProperty private String env; + + @JsonProperty private String protocol; + + @JsonProperty private String connectorConfig; + + @JsonProperty private String connectorName; +} diff --git a/src/main/java/io/aiven/klaw/model/cluster/ClusterSchemaRequest.java b/src/main/java/io/aiven/klaw/model/cluster/ClusterSchemaRequest.java new file mode 100644 index 0000000000..5ee5de9adc --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/cluster/ClusterSchemaRequest.java @@ -0,0 +1,17 @@ +package io.aiven.klaw.model.cluster; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import lombok.Builder; + +@Builder(toBuilder = true) +public class ClusterSchemaRequest implements Serializable { + + @JsonProperty private String env; + + @JsonProperty private String protocol; + + @JsonProperty private String topicName; + + @JsonProperty private String fullSchema; +} From d108681feda8656915b67422c0c64b06ec9304b5 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Tue, 4 Oct 2022 12:02:35 +0200 Subject: [PATCH 06/15] Code refactoring for acl controller, adding open api spec --- .../aiven/klaw/controller/AclController.java | 47 - .../klaw/controller/AclSyncController.java | 78 + .../klaw/service/AclControllerService.java | 446 +- .../service/AclSyncControllerService.java | 559 ++ src/main/resources/openapi_spec.json | 6346 +++++++++++++++++ .../klaw/controller/AclControllerTest.java | 51 +- .../service/AclControllerServiceTest.java | 20 +- 7 files changed, 7037 insertions(+), 510 deletions(-) create mode 100644 src/main/java/io/aiven/klaw/controller/AclSyncController.java create mode 100644 src/main/java/io/aiven/klaw/service/AclSyncControllerService.java create mode 100644 src/main/resources/openapi_spec.json diff --git a/src/main/java/io/aiven/klaw/controller/AclController.java b/src/main/java/io/aiven/klaw/controller/AclController.java index 3a86f690d7..29d61186cb 100644 --- a/src/main/java/io/aiven/klaw/controller/AclController.java +++ b/src/main/java/io/aiven/klaw/controller/AclController.java @@ -30,12 +30,6 @@ public ResponseEntity createAcl(@Valid @RequestBody AclRequestsModel add return new ResponseEntity<>(aclControllerService.createAcl(addAclRequest), HttpStatus.OK); } - @PostMapping(value = "/updateSyncAcls") - public ResponseEntity> updateSyncAcls( - @RequestBody List syncAclUpdates) { - return new ResponseEntity<>(aclControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); - } - @RequestMapping( value = "/getAclRequests", method = RequestMethod.GET, @@ -118,47 +112,6 @@ public ResponseEntity getSchemaOfTopic( aclControllerService.getSchemaOfTopic(topicNameSearch, schemaVersionSearch), HttpStatus.OK); } - @RequestMapping( - value = "/getSyncBackAcls", - method = RequestMethod.GET, - produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> getSyncBackAcls( - @RequestParam("env") String envId, - @RequestParam("pageNo") String pageNo, - @RequestParam(value = "currentPage", defaultValue = "") String currentPage, - @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, - @RequestParam(value = "teamName", required = false) String teamName) { - return new ResponseEntity<>( - aclControllerService.getSyncBackAcls(envId, pageNo, currentPage, topicNameSearch, teamName), - HttpStatus.OK); - } - - @PostMapping(value = "/updateSyncBackAcls") - public ResponseEntity>> updateSyncBackAcls( - @RequestBody SyncBackAcls syncBackAcls) { - Map> updateSyncAclsResult = - aclControllerService.updateSyncBackAcls(syncBackAcls); - return new ResponseEntity<>(updateSyncAclsResult, HttpStatus.OK); - } - - // get acls from kafka cluster - @RequestMapping( - value = "/getSyncAcls", - method = RequestMethod.GET, - produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> getSyncAcls( - @RequestParam("env") String envId, - @RequestParam("pageNo") String pageNo, - @RequestParam(value = "currentPage", defaultValue = "") String currentPage, - @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, - @RequestParam(value = "showAllAcls", defaultValue = "false", required = false) - String showAllAcls) - throws KlawException { - return new ResponseEntity<>( - aclControllerService.getSyncAcls(envId, pageNo, currentPage, topicNameSearch, showAllAcls), - HttpStatus.OK); - } - // getConsumerOffsets from kafka cluster @RequestMapping( value = "/getConsumerOffsets", diff --git a/src/main/java/io/aiven/klaw/controller/AclSyncController.java b/src/main/java/io/aiven/klaw/controller/AclSyncController.java new file mode 100644 index 0000000000..969cf5dff5 --- /dev/null +++ b/src/main/java/io/aiven/klaw/controller/AclSyncController.java @@ -0,0 +1,78 @@ +package io.aiven.klaw.controller; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.SyncAclUpdates; +import io.aiven.klaw.model.SyncBackAcls; +import io.aiven.klaw.service.AclSyncControllerService; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/") +@Slf4j +public class AclSyncController { + + @Autowired AclSyncControllerService aclSyncControllerService; + + @PostMapping(value = "/updateSyncAcls") + public ResponseEntity> updateSyncAcls( + @RequestBody List syncAclUpdates) { + return new ResponseEntity<>( + aclSyncControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); + } + + @RequestMapping( + value = "/getSyncBackAcls", + method = RequestMethod.GET, + produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity> getSyncBackAcls( + @RequestParam("env") String envId, + @RequestParam("pageNo") String pageNo, + @RequestParam(value = "currentPage", defaultValue = "") String currentPage, + @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, + @RequestParam(value = "teamName", required = false) String teamName) { + return new ResponseEntity<>( + aclSyncControllerService.getSyncBackAcls( + envId, pageNo, currentPage, topicNameSearch, teamName), + HttpStatus.OK); + } + + @PostMapping(value = "/updateSyncBackAcls") + public ResponseEntity>> updateSyncBackAcls( + @RequestBody SyncBackAcls syncBackAcls) { + Map> updateSyncAclsResult = + aclSyncControllerService.updateSyncBackAcls(syncBackAcls); + return new ResponseEntity<>(updateSyncAclsResult, HttpStatus.OK); + } + + // get acls from kafka cluster + @RequestMapping( + value = "/getSyncAcls", + method = RequestMethod.GET, + produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity> getSyncAcls( + @RequestParam("env") String envId, + @RequestParam("pageNo") String pageNo, + @RequestParam(value = "currentPage", defaultValue = "") String currentPage, + @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, + @RequestParam(value = "showAllAcls", defaultValue = "false", required = false) + String showAllAcls) + throws KlawException { + return new ResponseEntity<>( + aclSyncControllerService.getSyncAcls( + envId, pageNo, currentPage, topicNameSearch, showAllAcls), + HttpStatus.OK); + } +} diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index 9f4152ace8..d356027e1a 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -4,10 +4,10 @@ import static io.aiven.klaw.model.MailType.ACL_REQUESTED; import static io.aiven.klaw.model.MailType.ACL_REQUEST_APPROVED; import static io.aiven.klaw.model.MailType.ACL_REQUEST_DENIED; -import static io.aiven.klaw.service.KwConstants.RETRIEVE_SCHEMAS_KEY; import static org.springframework.beans.BeanUtils.copyProperties; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import io.aiven.klaw.config.ManageDatabase; @@ -15,22 +15,17 @@ import io.aiven.klaw.dao.AclRequests; import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.KwClusters; -import io.aiven.klaw.dao.Team; import io.aiven.klaw.dao.Topic; import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclInfo; -import io.aiven.klaw.model.AclOperationType; import io.aiven.klaw.model.AclRequestsModel; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; -import io.aiven.klaw.model.KafkaFlavors; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.RequestStatus; -import io.aiven.klaw.model.SyncAclUpdates; -import io.aiven.klaw.model.SyncBackAcls; import io.aiven.klaw.model.TopicHistory; import io.aiven.klaw.model.TopicInfo; import io.aiven.klaw.model.TopicOverview; @@ -165,176 +160,6 @@ public String createAcl(AclRequestsModel aclReq) { return "{\"result\":\"" + execRes + "\"}"; } - public Map updateSyncAcls(List syncAclUpdates) { - log.info("updateSyncAcls {}", syncAclUpdates); - String userDetails = getUserName(); - Map response = new HashMap<>(); - int tenantId = commonUtilsService.getTenantId(getUserName()); - - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { - response.put("result", "Not Authorized."); - return response; - } - - List listTopics = new ArrayList<>(); - Acl t; - - if (syncAclUpdates != null && syncAclUpdates.size() > 0) { - - Map stringSyncAclUpdatesHashMap = new HashMap<>(); - - // remove duplicates - for (SyncAclUpdates syncAclUpdateItem : syncAclUpdates) { - stringSyncAclUpdatesHashMap.remove(syncAclUpdateItem.getSequence()); - stringSyncAclUpdatesHashMap.put(syncAclUpdateItem.getSequence(), syncAclUpdateItem); - } - - for (Map.Entry stringSyncAclUpdatesEntry : - stringSyncAclUpdatesHashMap.entrySet()) { - SyncAclUpdates syncAclUpdateItem = stringSyncAclUpdatesEntry.getValue(); - - // tenant filtering - if (!getEnvsFromUserId(userDetails).contains(syncAclUpdateItem.getEnvSelected())) { - response.put("result", "Not Authorized."); - return response; - } - - t = new Acl(); - - if (syncAclUpdateItem.getReq_no() != null) - t.setReq_no(Integer.parseInt(syncAclUpdateItem.getReq_no())); - t.setTopicname(syncAclUpdateItem.getTopicName()); - t.setConsumergroup(syncAclUpdateItem.getConsumerGroup()); - t.setAclip(syncAclUpdateItem.getAclIp()); - t.setAclssl(syncAclUpdateItem.getAclSsl()); - t.setTeamId( - manageDatabase.getTeamIdFromTeamName(tenantId, syncAclUpdateItem.getTeamSelected())); - t.setEnvironment(syncAclUpdateItem.getEnvSelected()); - t.setTopictype(syncAclUpdateItem.getAclType()); - t.setAclPatternType("LITERAL"); - t.setTenantId(tenantId); - - listTopics.add(t); - } - } else { - response.put("result", "No record updated."); - return response; - } - - try { - if (listTopics.size() > 0) { - response.put("result", manageDatabase.getHandleDbRequests().addToSyncacls(listTopics)); - } - } catch (Exception e) { - log.error("Exception:", e); - response.put("result", "Failure." + e); - } - return response; - } - - public Map> updateSyncBackAcls(SyncBackAcls syncBackAcls) { - log.info("updateSyncBackAcls {}", syncBackAcls); - Map> resultMap = new HashMap<>(); - - List logArray = new ArrayList<>(); - int tenantId = commonUtilsService.getTenantId(getUserName()); - - logArray.add( - "Source Environment " + getEnvDetails(syncBackAcls.getSourceEnv(), tenantId).getName()); - logArray.add( - "Target Environment " + getEnvDetails(syncBackAcls.getTargetEnv(), tenantId).getName()); - logArray.add("Type of Sync " + syncBackAcls.getTypeOfSync()); - - if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { - List notAuth = new ArrayList<>(); - notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); - resultMap.put("result", notAuth); - return resultMap; - } - - List resultStatus = new ArrayList<>(); - resultStatus.add("success"); - - resultMap.put("result", resultStatus); - - if ("SELECTED_ACLS".equals(syncBackAcls.getTypeOfSync())) { - for (String aclId : syncBackAcls.getAclIds()) { - Acl acl = - manageDatabase - .getHandleDbRequests() - .selectSyncAclsFromReqNo(Integer.parseInt(aclId), tenantId); - if (acl != null) { - approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); - } - } - } else { - List acls = - manageDatabase.getHandleDbRequests().getSyncAcls(syncBackAcls.getSourceEnv(), tenantId); - for (Acl acl : acls) { - approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); - } - } - - resultMap.put("syncbacklog", logArray); - - return resultMap; - } - - private void approveSyncBackAcls( - SyncBackAcls syncBackAcls, - Map> resultMap, - List logUpdateSyncBackTopics, - Acl aclFound, - int tenantId) { - try { - AclRequests aclReq = new AclRequests(); - copyProperties(aclFound, aclReq); - aclReq.setReq_no(null); - aclReq.setAcl_ip(aclFound.getAclip()); - aclReq.setAcl_ssl(aclFound.getAclssl()); - aclReq.setEnvironment(syncBackAcls.getTargetEnv()); - aclReq.setRequestingteam(aclFound.getTeamId()); - aclReq.setAclType(AclOperationType.CREATE.value); - aclReq.setUsername(getUserName()); - aclReq.setTenantId(tenantId); - - ResponseEntity response = clusterApiService.approveAclRequests(aclReq, tenantId); - - ApiResponse responseBody = response.getBody(); - // String resultAclReq = responseBody.getResult(); - String resultAclNullCheck = Objects.requireNonNull(responseBody).getResult(); - if (!Objects.requireNonNull(resultAclNullCheck).contains("success")) { - log.error("Error in creating acl {} {}", aclFound, responseBody); - logUpdateSyncBackTopics.add( - "Error in Acl creation. Acl:" + aclFound.getTopicname() + " " + resultAclNullCheck); - } else if (resultAclNullCheck.contains("Acl already exists")) { - logUpdateSyncBackTopics.add("Acl already exists " + aclFound.getTopicname()); - } else { - if (!Objects.equals(syncBackAcls.getSourceEnv(), syncBackAcls.getTargetEnv())) { - logUpdateSyncBackTopics.add("Acl added: " + aclFound.getTopicname()); - // Create request - Map resultMapReq = - manageDatabase.getHandleDbRequests().requestForAcl(aclReq); - if (resultMapReq.containsKey("aclId")) { - Integer aclId = Integer.parseInt(resultMapReq.get("aclId")); - aclReq.setReq_no(aclId); - // Approve request - String emptyJsonParams = "{}"; - manageDatabase - .getHandleDbRequests() - .updateAclRequest(aclReq, getUserName(), emptyJsonParams); - } - } - } - } catch (KlawException e) { - log.error("Error in creating acl {} {}", e.getMessage(), aclFound); - List resultStatus = new ArrayList<>(); - resultStatus.add("Error :" + e.getMessage()); - resultMap.put("result", resultStatus); - } - } - public List getAclRequests( String pageNo, String currentPage, String requestsType) { @@ -746,60 +571,6 @@ public String declineAclRequests(String req_no, String reasonToDecline) { } else return "{\"result\":\"Record not found !\"}"; } - private List> getAclListFromCluster( - String bootstrapHost, - Env envSelected, - String protocol, - String clusterName, - String topicNameSearch, - int tenantId) - throws KlawException { - List> aclList; - aclList = - clusterApiService.getAcls(bootstrapHost, envSelected, protocol, clusterName, tenantId); - return updateConsumerGroups(groupAcls(aclList, topicNameSearch, true), aclList); - } - - private List> updateConsumerGroups( - List> groupedList, List> clusterAclList) { - List> updateList = new ArrayList<>(groupedList); - - for (Map hMapGroupItem : groupedList) { - for (Map hMapItem : clusterAclList) { - if ("READ".equals(hMapGroupItem.get("operation")) - && "READ".equals(hMapItem.get("operation")) - && "GROUP".equals(hMapItem.get("resourceType"))) { - if (Objects.equals(hMapItem.get("host"), hMapGroupItem.get("host")) - && Objects.equals(hMapItem.get("principle"), hMapGroupItem.get("principle"))) { - Map hashMap = new HashMap<>(hMapGroupItem); - hashMap.put("consumerGroup", hMapItem.get("resourceName")); - updateList.add(hashMap); - break; - } - } - } - } - return updateList; - } - - private List> groupAcls( - List> aclList, String topicNameSearch, boolean isSync) { - - return aclList.stream() - .filter( - hItem -> { - if (isSync) { - if (topicNameSearch != null) { - return "TOPIC".equals(hItem.get("resourceType")) - && hItem.get("resourceName").contains(topicNameSearch); - } else return "TOPIC".equals(hItem.get("resourceType")); - } else { - return Objects.equals(hItem.get("resourceName"), topicNameSearch); - } - }) - .collect(Collectors.toList()); - } - private List getAclsFromSOT( String env, String topicNameSearch, boolean regex, int tenantId) { List aclsFromSOT; @@ -888,8 +659,6 @@ public TopicOverview getAcls(String topicNameSearch) { String userDetails = getUserName(); HandleDbRequests handleDb = manageDatabase.getHandleDbRequests(); int tenantId = commonUtilsService.getTenantId(getUserName()); - String retrieveSchemasStr = manageDatabase.getKwPropertyValue(RETRIEVE_SCHEMAS_KEY, tenantId); - boolean retrieveSchemas = "true".equals(retrieveSchemasStr); if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); else return null; @@ -948,7 +717,8 @@ public TopicOverview getAcls(String topicNameSearch) { if (topic.getHistory() != null) { try { - topicHistoryFromTopic = OBJECT_MAPPER.readValue(topic.getHistory(), ArrayList.class); + topicHistoryFromTopic = + OBJECT_MAPPER.readValue(topic.getHistory(), new TypeReference<>() {}); topicHistoryList.addAll(topicHistoryFromTopic); } catch (JsonProcessingException e) { log.error("Unable to parse topicHistory"); @@ -1128,7 +898,8 @@ private void updateAvroSchema( schemaMap.put("nextVersion", "" + allVersionsList.get(indexOfVersion + 1)); } } else { - hashMapSchemaObj = schemaObjects.get(Integer.parseInt(schemaVersionSearch)); + hashMapSchemaObj = + schemaObjects.get(Integer.parseInt(Objects.requireNonNull(schemaVersionSearch))); schemaOfObj = (String) hashMapSchemaObj.get("schema"); schemaMap.put("isLatest", "false"); schemaMap.put("id", hashMapSchemaObj.get("id") + ""); @@ -1166,74 +937,6 @@ private void updateAvroSchema( } } - public List getSyncAcls( - String env, String pageNo, String currentPage, String topicNameSearch, String showAllAcls) - throws KlawException { - log.info( - "getSyncAcls env: {} topicNameSearch: {} showAllAcls:{}", - env, - topicNameSearch, - showAllAcls); - boolean isReconciliation = !Boolean.parseBoolean(showAllAcls); - int tenantId = commonUtilsService.getTenantId(getUserName()); - - if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); - - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) - return null; - - List> aclList; - - Env envSelected = getEnvDetails(env, tenantId); - KwClusters kwClusters = - manageDatabase - .getClusters(KafkaClustersType.KAFKA.value, tenantId) - .get(envSelected.getClusterId()); - aclList = - getAclListFromCluster( - kwClusters.getBootstrapServers(), - envSelected, - kwClusters.getProtocol(), - kwClusters.getClusterName(), - topicNameSearch, - tenantId); - - List aclsFromSOT = getAclsFromSOT(env, topicNameSearch, true, tenantId); - - topicCounter = 0; - return getAclsList( - pageNo, - currentPage, - applyFiltersAcls( - env, aclList, aclsFromSOT, isReconciliation, tenantId, kwClusters.getKafkaFlavor())); - } - - public List getSyncBackAcls( - String envId, String pageNo, String currentPage, String topicNameSearch, String teamName) { - log.info("getSyncBackAcls {} {} {} {}", envId, pageNo, topicNameSearch, teamName); - if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); - - int tenantId = commonUtilsService.getTenantId(getUserName()); - - if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) return null; - - List aclsFromSOT; - - if (topicNameSearch != null && topicNameSearch.trim().length() > 0) - aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, false, tenantId); - else aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, true, tenantId); - - List aclInfoList; - Integer loggedInUserTeam = getMyTeamId(getUserName()); - - aclInfoList = - getAclsList( - pageNo, currentPage, applyFiltersAclsForSOT(loggedInUserTeam, aclsFromSOT, tenantId)); - - return aclInfoList; - } - private List applyFiltersAclsForSOT( Integer loggedInUserTeam, List aclsFromSOT, int tenantId) { @@ -1261,145 +964,6 @@ private List applyFiltersAclsForSOT( return aclList; } - private List applyFiltersAcls( - String env, - List> aclList, - List aclsFromSOT, - boolean isReconciliation, - int tenantId, - String kafkaFlavor) { - - List aclListMap = new ArrayList<>(); - List teamList = new ArrayList<>(); - teamList = tenantFiltering(teamList); - - for (Map aclListItem : aclList) { - AclInfo mp = new AclInfo(); - mp.setEnvironment(env); - - mp.setPossibleTeams(teamList); - mp.setTeamname(""); - - String tmpPermType = aclListItem.get("operation"); - - if ("WRITE".equals(tmpPermType)) mp.setTopictype("Producer"); - else if ("READ".equals(tmpPermType)) { - mp.setTopictype("Consumer"); - if (aclListItem.get("consumerGroup") != null) - mp.setConsumergroup(aclListItem.get("consumerGroup")); - else continue; - } - - if ("topic".equalsIgnoreCase(aclListItem.get("resourceType"))) - mp.setTopicname(aclListItem.get("resourceName")); - - mp.setAcl_ip(aclListItem.get("host")); - mp.setAcl_ssl(aclListItem.get("principle")); - - for (Acl aclSotItem : aclsFromSOT) { - String acl_ssl = aclSotItem.getAclssl(); - String acl_host = aclSotItem.getAclip(); - - if (acl_ssl == null || acl_ssl.equals("")) acl_ssl = "User:*"; - else { - if (!KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value.equals(kafkaFlavor) - && !"User:*".equals(acl_ssl) - && !acl_ssl.startsWith("User:")) { - acl_ssl = "User:" + acl_ssl; - } - } - - if (acl_host == null || acl_host.equals("")) acl_host = "*"; - - if (aclSotItem.getTopicname() != null - && Objects.equals(aclListItem.get("resourceName"), aclSotItem.getTopicname()) - && Objects.equals(aclListItem.get("host"), acl_host) - && Objects.equals(aclListItem.get("principle"), acl_ssl) - && Objects.equals(aclSotItem.getTopictype(), mp.getTopictype())) { - mp.setTeamname(manageDatabase.getTeamNameFromTeamId(tenantId, aclSotItem.getTeamId())); - mp.setReq_no(aclSotItem.getReq_no() + ""); - break; - } - } - - if (mp.getTeamname() == null) mp.setTeamname("Unknown"); - - if (isReconciliation) { - if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) aclListMap.add(mp); - } else { - if (teamList.contains(mp.getTeamname())) aclListMap.add(mp); - else if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) - aclListMap.add(mp); - } - } - return aclListMap; - } - - private List tenantFiltering(List teamList) { - if (!commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS) - || !commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS) - || !commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS) - || !commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { - // tenant filtering - int tenantId = commonUtilsService.getTenantId(getUserName()); - - List teams = manageDatabase.getHandleDbRequests().selectAllTeams(tenantId); - - teams = - teams.stream() - .filter(t -> Objects.equals(t.getTenantId(), tenantId)) - .collect(Collectors.toList()); - List teamListUpdated = new ArrayList<>(); - for (Team teamsItem : teams) { - teamListUpdated.add(teamsItem.getTeamname()); - } - teamList = teamListUpdated; - } - return teamList; - } - - private List getAclsList(String pageNo, String currentPage, List aclListMap) { - List aclListMapUpdated = new ArrayList<>(); - - int totalRecs = aclListMap.size(); - int recsPerPage = 20; - int totalPages = - aclListMap.size() / recsPerPage + (aclListMap.size() % recsPerPage > 0 ? 1 : 0); - - pageNo = commonUtilsService.deriveCurrentPage(pageNo, currentPage, totalPages); - int requestPageNo = Integer.parseInt(pageNo); - int startVar = (requestPageNo - 1) * recsPerPage; - int lastVar = (requestPageNo) * (recsPerPage); - - List numList = new ArrayList<>(); - commonUtilsService.getAllPagesList(pageNo, currentPage, totalPages, numList); - - for (int i = 0; i < totalRecs; i++) { - int counterInc = counterIncrement(); - if (i >= startVar && i < lastVar) { - AclInfo mp = aclListMap.get(i); - mp.setSequence(counterInc + ""); - - mp.setTotalNoPages(totalPages + ""); - mp.setCurrentPage(pageNo); - mp.setAllPageNos(numList); - - aclListMapUpdated.add(mp); - } - } - return aclListMapUpdated; - } - - private int topicCounter = 0; - - private int counterIncrement() { - topicCounter++; - return topicCounter; - } - private String getUserName() { return mailService.getUserName( SecurityContextHolder.getContext().getAuthentication().getPrincipal()); diff --git a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java new file mode 100644 index 0000000000..63ae3fcc33 --- /dev/null +++ b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java @@ -0,0 +1,559 @@ +package io.aiven.klaw.service; + +import static org.springframework.beans.BeanUtils.copyProperties; + +import io.aiven.klaw.config.ManageDatabase; +import io.aiven.klaw.dao.Acl; +import io.aiven.klaw.dao.AclRequests; +import io.aiven.klaw.dao.Env; +import io.aiven.klaw.dao.KwClusters; +import io.aiven.klaw.dao.Team; +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.AclOperationType; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.KafkaClustersType; +import io.aiven.klaw.model.KafkaFlavors; +import io.aiven.klaw.model.PermissionType; +import io.aiven.klaw.model.SyncAclUpdates; +import io.aiven.klaw.model.SyncBackAcls; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +public class AclSyncControllerService { + + private int TOPIC_COUNTER = 0; + @Autowired ManageDatabase manageDatabase; + + @Autowired private final MailUtils mailService; + + @Autowired private final ClusterApiService clusterApiService; + + @Autowired private CommonUtilsService commonUtilsService; + + AclSyncControllerService(ClusterApiService clusterApiService, MailUtils mailService) { + this.clusterApiService = clusterApiService; + this.mailService = mailService; + } + + public Map updateSyncAcls(List syncAclUpdates) { + log.info("updateSyncAcls {}", syncAclUpdates); + String userDetails = getUserName(); + Map response = new HashMap<>(); + int tenantId = commonUtilsService.getTenantId(getUserName()); + + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { + response.put("result", "Not Authorized."); + return response; + } + + List listTopics = new ArrayList<>(); + Acl t; + + if (syncAclUpdates != null && syncAclUpdates.size() > 0) { + + Map stringSyncAclUpdatesHashMap = new HashMap<>(); + + // remove duplicates + for (SyncAclUpdates syncAclUpdateItem : syncAclUpdates) { + stringSyncAclUpdatesHashMap.remove(syncAclUpdateItem.getSequence()); + stringSyncAclUpdatesHashMap.put(syncAclUpdateItem.getSequence(), syncAclUpdateItem); + } + + for (Map.Entry stringSyncAclUpdatesEntry : + stringSyncAclUpdatesHashMap.entrySet()) { + SyncAclUpdates syncAclUpdateItem = stringSyncAclUpdatesEntry.getValue(); + + // tenant filtering + if (!getEnvsFromUserId(userDetails).contains(syncAclUpdateItem.getEnvSelected())) { + response.put("result", "Not Authorized."); + return response; + } + + t = new Acl(); + + if (syncAclUpdateItem.getReq_no() != null) + t.setReq_no(Integer.parseInt(syncAclUpdateItem.getReq_no())); + t.setTopicname(syncAclUpdateItem.getTopicName()); + t.setConsumergroup(syncAclUpdateItem.getConsumerGroup()); + t.setAclip(syncAclUpdateItem.getAclIp()); + t.setAclssl(syncAclUpdateItem.getAclSsl()); + t.setTeamId( + manageDatabase.getTeamIdFromTeamName(tenantId, syncAclUpdateItem.getTeamSelected())); + t.setEnvironment(syncAclUpdateItem.getEnvSelected()); + t.setTopictype(syncAclUpdateItem.getAclType()); + t.setAclPatternType("LITERAL"); + t.setTenantId(tenantId); + + listTopics.add(t); + } + } else { + response.put("result", "No record updated."); + return response; + } + + try { + if (listTopics.size() > 0) { + response.put("result", manageDatabase.getHandleDbRequests().addToSyncacls(listTopics)); + } + } catch (Exception e) { + log.error("Exception:", e); + response.put("result", "Failure." + e); + } + return response; + } + + public Map> updateSyncBackAcls(SyncBackAcls syncBackAcls) { + log.info("updateSyncBackAcls {}", syncBackAcls); + Map> resultMap = new HashMap<>(); + + List logArray = new ArrayList<>(); + int tenantId = commonUtilsService.getTenantId(getUserName()); + + logArray.add( + "Source Environment " + getEnvDetails(syncBackAcls.getSourceEnv(), tenantId).getName()); + logArray.add( + "Target Environment " + getEnvDetails(syncBackAcls.getTargetEnv(), tenantId).getName()); + logArray.add("Type of Sync " + syncBackAcls.getTypeOfSync()); + + if (commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { + List notAuth = new ArrayList<>(); + notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); + resultMap.put("result", notAuth); + return resultMap; + } + + List resultStatus = new ArrayList<>(); + resultStatus.add("success"); + + resultMap.put("result", resultStatus); + + if ("SELECTED_ACLS".equals(syncBackAcls.getTypeOfSync())) { + for (String aclId : syncBackAcls.getAclIds()) { + Acl acl = + manageDatabase + .getHandleDbRequests() + .selectSyncAclsFromReqNo(Integer.parseInt(aclId), tenantId); + if (acl != null) { + approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); + } + } + } else { + List acls = + manageDatabase.getHandleDbRequests().getSyncAcls(syncBackAcls.getSourceEnv(), tenantId); + for (Acl acl : acls) { + approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); + } + } + + resultMap.put("syncbacklog", logArray); + + return resultMap; + } + + private void approveSyncBackAcls( + SyncBackAcls syncBackAcls, + Map> resultMap, + List logUpdateSyncBackTopics, + Acl aclFound, + int tenantId) { + try { + AclRequests aclReq = new AclRequests(); + copyProperties(aclFound, aclReq); + aclReq.setReq_no(null); + aclReq.setAcl_ip(aclFound.getAclip()); + aclReq.setAcl_ssl(aclFound.getAclssl()); + aclReq.setEnvironment(syncBackAcls.getTargetEnv()); + aclReq.setRequestingteam(aclFound.getTeamId()); + aclReq.setAclType(AclOperationType.CREATE.value); + aclReq.setUsername(getUserName()); + aclReq.setTenantId(tenantId); + + ResponseEntity response = clusterApiService.approveAclRequests(aclReq, tenantId); + + ApiResponse responseBody = response.getBody(); + // String resultAclReq = responseBody.getResult(); + String resultAclNullCheck = Objects.requireNonNull(responseBody).getResult(); + if (!Objects.requireNonNull(resultAclNullCheck).contains("success")) { + log.error("Error in creating acl {} {}", aclFound, responseBody); + logUpdateSyncBackTopics.add( + "Error in Acl creation. Acl:" + aclFound.getTopicname() + " " + resultAclNullCheck); + } else if (resultAclNullCheck.contains("Acl already exists")) { + logUpdateSyncBackTopics.add("Acl already exists " + aclFound.getTopicname()); + } else { + if (!Objects.equals(syncBackAcls.getSourceEnv(), syncBackAcls.getTargetEnv())) { + logUpdateSyncBackTopics.add("Acl added: " + aclFound.getTopicname()); + // Create request + Map resultMapReq = + manageDatabase.getHandleDbRequests().requestForAcl(aclReq); + if (resultMapReq.containsKey("aclId")) { + Integer aclId = Integer.parseInt(resultMapReq.get("aclId")); + aclReq.setReq_no(aclId); + // Approve request + String emptyJsonParams = "{}"; + manageDatabase + .getHandleDbRequests() + .updateAclRequest(aclReq, getUserName(), emptyJsonParams); + } + } + } + } catch (KlawException e) { + log.error("Error in creating acl {} {}", e.getMessage(), aclFound); + List resultStatus = new ArrayList<>(); + resultStatus.add("Error :" + e.getMessage()); + resultMap.put("result", resultStatus); + } + } + + private List> getAclListFromCluster( + String bootstrapHost, + Env envSelected, + String protocol, + String clusterName, + String topicNameSearch, + int tenantId) + throws KlawException { + List> aclList; + aclList = + clusterApiService.getAcls(bootstrapHost, envSelected, protocol, clusterName, tenantId); + return updateConsumerGroups(groupAcls(aclList, topicNameSearch, true), aclList); + } + + private List> updateConsumerGroups( + List> groupedList, List> clusterAclList) { + List> updateList = new ArrayList<>(groupedList); + + for (Map hMapGroupItem : groupedList) { + for (Map hMapItem : clusterAclList) { + if ("READ".equals(hMapGroupItem.get("operation")) + && "READ".equals(hMapItem.get("operation")) + && "GROUP".equals(hMapItem.get("resourceType"))) { + if (Objects.equals(hMapItem.get("host"), hMapGroupItem.get("host")) + && Objects.equals(hMapItem.get("principle"), hMapGroupItem.get("principle"))) { + Map hashMap = new HashMap<>(hMapGroupItem); + hashMap.put("consumerGroup", hMapItem.get("resourceName")); + updateList.add(hashMap); + break; + } + } + } + } + return updateList; + } + + private List> groupAcls( + List> aclList, String topicNameSearch, boolean isSync) { + + return aclList.stream() + .filter( + hItem -> { + if (isSync) { + if (topicNameSearch != null) { + return "TOPIC".equals(hItem.get("resourceType")) + && hItem.get("resourceName").contains(topicNameSearch); + } else return "TOPIC".equals(hItem.get("resourceType")); + } else { + return Objects.equals(hItem.get("resourceName"), topicNameSearch); + } + }) + .collect(Collectors.toList()); + } + + private List getAclsFromSOT( + String env, String topicNameSearch, boolean regex, int tenantId) { + List aclsFromSOT; + if (!regex) + aclsFromSOT = + manageDatabase.getHandleDbRequests().getSyncAcls(env, topicNameSearch, tenantId); + else { + aclsFromSOT = manageDatabase.getHandleDbRequests().getSyncAcls(env, tenantId); + List topicFilteredList = aclsFromSOT; + // Filter topics on topic name for search + if (topicNameSearch != null && topicNameSearch.length() > 0) { + final String topicSearchFilter = topicNameSearch; + topicFilteredList = + aclsFromSOT.stream() + .filter(acl -> acl.getTopicname().contains(topicSearchFilter)) + .collect(Collectors.toList()); + } + aclsFromSOT = topicFilteredList; + } + + return aclsFromSOT; + } + + public List getSyncAcls( + String env, String pageNo, String currentPage, String topicNameSearch, String showAllAcls) + throws KlawException { + log.info( + "getSyncAcls env: {} topicNameSearch: {} showAllAcls:{}", + env, + topicNameSearch, + showAllAcls); + boolean isReconciliation = !Boolean.parseBoolean(showAllAcls); + int tenantId = commonUtilsService.getTenantId(getUserName()); + + if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); + + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) + return null; + + List> aclList; + + Env envSelected = getEnvDetails(env, tenantId); + KwClusters kwClusters = + manageDatabase + .getClusters(KafkaClustersType.KAFKA.value, tenantId) + .get(envSelected.getClusterId()); + aclList = + getAclListFromCluster( + kwClusters.getBootstrapServers(), + envSelected, + kwClusters.getProtocol(), + kwClusters.getClusterName(), + topicNameSearch, + tenantId); + + List aclsFromSOT = getAclsFromSOT(env, topicNameSearch, true, tenantId); + + TOPIC_COUNTER = 0; + return getAclsList( + pageNo, + currentPage, + applyFiltersAcls( + env, aclList, aclsFromSOT, isReconciliation, tenantId, kwClusters.getKafkaFlavor())); + } + + public List getSyncBackAcls( + String envId, String pageNo, String currentPage, String topicNameSearch, String teamName) { + log.info("getSyncBackAcls {} {} {} {}", envId, pageNo, topicNameSearch, teamName); + if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); + + int tenantId = commonUtilsService.getTenantId(getUserName()); + + if (commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) return null; + + List aclsFromSOT; + + if (topicNameSearch != null && topicNameSearch.trim().length() > 0) + aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, false, tenantId); + else aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, true, tenantId); + + List aclInfoList; + Integer loggedInUserTeam = getMyTeamId(getUserName()); + + aclInfoList = + getAclsList( + pageNo, currentPage, applyFiltersAclsForSOT(loggedInUserTeam, aclsFromSOT, tenantId)); + + return aclInfoList; + } + + private List applyFiltersAclsForSOT( + Integer loggedInUserTeam, List aclsFromSOT, int tenantId) { + + List aclList = new ArrayList<>(); + AclInfo mp; + + for (Acl aclSotItem : aclsFromSOT) { + mp = new AclInfo(); + mp.setEnvironment(aclSotItem.getEnvironment()); + mp.setEnvironmentName(getEnvDetails(aclSotItem.getEnvironment(), tenantId).getName()); + mp.setTopicname(aclSotItem.getTopicname()); + mp.setAcl_ip(aclSotItem.getAclip()); + mp.setAcl_ssl(aclSotItem.getAclssl()); + mp.setTransactionalId(aclSotItem.getTransactionalId()); + mp.setTeamname(manageDatabase.getTeamNameFromTeamId(tenantId, aclSotItem.getTeamId())); + mp.setConsumergroup(aclSotItem.getConsumergroup()); + mp.setTopictype(aclSotItem.getTopictype()); + mp.setAclPatternType(aclSotItem.getAclPatternType()); + mp.setReq_no(aclSotItem.getReq_no() + ""); + if (aclSotItem.getTeamId() != null && aclSotItem.getTeamId().equals(loggedInUserTeam)) + mp.setShowDeleteAcl(true); + + if (aclSotItem.getAclip() != null || aclSotItem.getAclssl() != null) aclList.add(mp); + } + return aclList; + } + + private List applyFiltersAcls( + String env, + List> aclList, + List aclsFromSOT, + boolean isReconciliation, + int tenantId, + String kafkaFlavor) { + + List aclListMap = new ArrayList<>(); + List teamList = new ArrayList<>(); + teamList = tenantFiltering(teamList); + + for (Map aclListItem : aclList) { + AclInfo mp = new AclInfo(); + mp.setEnvironment(env); + + mp.setPossibleTeams(teamList); + mp.setTeamname(""); + + String tmpPermType = aclListItem.get("operation"); + + if ("WRITE".equals(tmpPermType)) mp.setTopictype("Producer"); + else if ("READ".equals(tmpPermType)) { + mp.setTopictype("Consumer"); + if (aclListItem.get("consumerGroup") != null) + mp.setConsumergroup(aclListItem.get("consumerGroup")); + else continue; + } + + if ("topic".equalsIgnoreCase(aclListItem.get("resourceType"))) + mp.setTopicname(aclListItem.get("resourceName")); + + mp.setAcl_ip(aclListItem.get("host")); + mp.setAcl_ssl(aclListItem.get("principle")); + + for (Acl aclSotItem : aclsFromSOT) { + String acl_ssl = aclSotItem.getAclssl(); + String acl_host = aclSotItem.getAclip(); + + if (acl_ssl == null || acl_ssl.equals("")) acl_ssl = "User:*"; + else { + if (!KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value.equals(kafkaFlavor) + && !"User:*".equals(acl_ssl) + && !acl_ssl.startsWith("User:")) { + acl_ssl = "User:" + acl_ssl; + } + } + + if (acl_host == null || acl_host.equals("")) acl_host = "*"; + + if (aclSotItem.getTopicname() != null + && Objects.equals(aclListItem.get("resourceName"), aclSotItem.getTopicname()) + && Objects.equals(aclListItem.get("host"), acl_host) + && Objects.equals(aclListItem.get("principle"), acl_ssl) + && Objects.equals(aclSotItem.getTopictype(), mp.getTopictype())) { + mp.setTeamname(manageDatabase.getTeamNameFromTeamId(tenantId, aclSotItem.getTeamId())); + mp.setReq_no(aclSotItem.getReq_no() + ""); + break; + } + } + + if (mp.getTeamname() == null) mp.setTeamname("Unknown"); + + if (isReconciliation) { + if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) aclListMap.add(mp); + } else { + if (teamList.contains(mp.getTeamname())) aclListMap.add(mp); + else if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) + aclListMap.add(mp); + } + } + return aclListMap; + } + + private List tenantFiltering(List teamList) { + if (!commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS) + || !commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS) + || !commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS) + || !commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { + // tenant filtering + int tenantId = commonUtilsService.getTenantId(getUserName()); + + List teams = manageDatabase.getHandleDbRequests().selectAllTeams(tenantId); + + teams = + teams.stream() + .filter(t -> Objects.equals(t.getTenantId(), tenantId)) + .collect(Collectors.toList()); + List teamListUpdated = new ArrayList<>(); + for (Team teamsItem : teams) { + teamListUpdated.add(teamsItem.getTeamname()); + } + teamList = teamListUpdated; + } + return teamList; + } + + private List getAclsList(String pageNo, String currentPage, List aclListMap) { + List aclListMapUpdated = new ArrayList<>(); + + int totalRecs = aclListMap.size(); + int recsPerPage = 20; + int totalPages = + aclListMap.size() / recsPerPage + (aclListMap.size() % recsPerPage > 0 ? 1 : 0); + + pageNo = commonUtilsService.deriveCurrentPage(pageNo, currentPage, totalPages); + int requestPageNo = Integer.parseInt(pageNo); + int startVar = (requestPageNo - 1) * recsPerPage; + int lastVar = (requestPageNo) * (recsPerPage); + + List numList = new ArrayList<>(); + commonUtilsService.getAllPagesList(pageNo, currentPage, totalPages, numList); + + for (int i = 0; i < totalRecs; i++) { + int counterInc = counterIncrement(); + if (i >= startVar && i < lastVar) { + AclInfo mp = aclListMap.get(i); + mp.setSequence(counterInc + ""); + + mp.setTotalNoPages(totalPages + ""); + mp.setCurrentPage(pageNo); + mp.setAllPageNos(numList); + + aclListMapUpdated.add(mp); + } + } + return aclListMapUpdated; + } + + private int counterIncrement() { + TOPIC_COUNTER++; + return TOPIC_COUNTER; + } + + private String getUserName() { + return mailService.getUserName( + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + } + + public Env getEnvDetails(String envId, int tenantId) { + + Optional envFound = + manageDatabase.getKafkaEnvList(tenantId).stream() + .filter(env -> Objects.equals(env.getId(), envId)) + .findFirst(); + return envFound.orElse(null); + } + + // based on tenants + private List getEnvsFromUserId(String userName) { + int tenantId = commonUtilsService.getTenantId(userName); + Integer myTeamId = getMyTeamId(userName); + return manageDatabase.getTeamsAndAllowedEnvs(myTeamId, tenantId); + } + + private Object getPrincipal() { + return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + } + + private Integer getMyTeamId(String userName) { + return manageDatabase.getHandleDbRequests().getUsersInfo(userName).getTeamId(); + } +} diff --git a/src/main/resources/openapi_spec.json b/src/main/resources/openapi_spec.json new file mode 100644 index 0000000000..2dfa238607 --- /dev/null +++ b/src/main/resources/openapi_spec.json @@ -0,0 +1,6346 @@ +{ + "openapi":"3.0.1", + "info":{ + "title":"OpenAPI definition", + "version":"v0" + }, + "servers":[ + { + "url":"https://localhost:9097", + "description":"Generated server url" + } + ], + "paths":{ + "/uploadSchema":{ + "post":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"uploadSchema", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/SchemaRequestModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/updateUser":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"updateUser", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/updateTeam":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"updateTeam", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TeamModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/updateSyncTopics":{ + "post":{ + "tags":[ + "topic-sync-controller" + ], + "operationId":"updateSyncTopics", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/SyncTopicUpdates" + } + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/updateSyncTopicsBulk":{ + "post":{ + "tags":[ + "topic-sync-controller" + ], + "operationId":"updateSyncTopicsBulk", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/SyncTopicsBulk" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/updateSyncConnectors":{ + "post":{ + "tags":[ + "kafka-connect-sync-controller" + ], + "operationId":"updateSyncTopics_1", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/SyncConnectorUpdates" + } + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/updateSyncBackTopics":{ + "post":{ + "tags":[ + "topic-sync-controller" + ], + "operationId":"updateSyncBackTopics", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/SyncBackTopics" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/updateSyncBackAcls":{ + "post":{ + "tags":[ + "acl-sync-controller" + ], + "operationId":"updateSyncBackAcls", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/SyncBackAcls" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/updateSyncAcls":{ + "post":{ + "tags":[ + "acl-sync-controller" + ], + "operationId":"updateSyncAcls", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/SyncAclUpdates" + } + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/updateProfile":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"updateProfile", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/updatePermissions":{ + "post":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"updatePermissions", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KwRolesPermissionsModel" + } + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/updateKwCustomProperty":{ + "post":{ + "tags":[ + "server-config-controller" + ], + "operationId":"updateKwCustomProperty", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KwPropertiesModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/udpateTenant":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"udpateTenant", + "parameters":[ + { + "name":"orgName", + "in":"query", + "required":true, + "schema":{ + "pattern":"^[a-zA-z ]*$", + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/udpateTenantExtension":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"udpateTenantExtension", + "parameters":[ + { + "name":"selectedTenantExtensionPeriod", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/sendMessageToAdmin":{ + "post":{ + "tags":[ + "ui-config-controller" + ], + "operationId":"sendMessageToAdmin", + "parameters":[ + { + "name":"contactFormSubject", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"contactFormMessage", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/saveTopicDocumentation":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"saveTopicDocumentation", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TopicInfo" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/saveConnectorDocumentation":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"saveConnectorDocumentation", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KafkaConnectorModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/resetPassword":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"resetPassword", + "parameters":[ + { + "name":"username", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/registerUser":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"registerUser", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/RegisterUserInfoModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/registerUserSaas":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"registerUserSaas", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/RegisterSaasUserInfoModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/logout":{ + "post":{ + "tags":[ + "util-controller" + ], + "operationId":"logout", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/execTopicRequests":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"approveTopicRequests", + "parameters":[ + { + "name":"topicId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/execTopicRequestsDecline":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"declineTopicRequests", + "parameters":[ + { + "name":"topicId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"reasonForDecline", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/execSchemaRequests":{ + "post":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"execSchemaRequests", + "parameters":[ + { + "name":"avroSchemaReqId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/execSchemaRequestsDecline":{ + "post":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"execSchemaRequestsDecline", + "parameters":[ + { + "name":"avroSchemaReqId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"reasonForDecline", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/execNewUserRequestDecline":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"declineNewUserRequests", + "parameters":[ + { + "name":"username", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/execNewUserRequestApprove":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"approveNewUserRequests", + "parameters":[ + { + "name":"username", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/execConnectorRequests":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"approveTopicRequests_1", + "parameters":[ + { + "name":"connectorId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/execConnectorRequestsDecline":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"declineConnectorRequests", + "parameters":[ + { + "name":"connectorId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"reasonForDecline", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/execAclRequest":{ + "post":{ + "tags":[ + "acl-controller" + ], + "operationId":"approveAclRequests", + "parameters":[ + { + "name":"req_no", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/execAclRequestDecline":{ + "post":{ + "tags":[ + "acl-controller" + ], + "operationId":"declineAclRequests", + "parameters":[ + { + "name":"req_no", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"reasonForDecline", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteUserRequest":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"deleteUser", + "parameters":[ + { + "name":"userId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteTopicRequests":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"deleteTopicRequests", + "parameters":[ + { + "name":"topicId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteTenant":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"deleteTenant", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/deleteTeamRequest":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"deleteTeam", + "parameters":[ + { + "name":"teamId", + "in":"query", + "required":true, + "schema":{ + "type":"integer", + "format":"int32" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteSchemaRequests":{ + "post":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"deleteSchemaRequests", + "parameters":[ + { + "name":"req_no", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteRole":{ + "post":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"deleteRole", + "parameters":[ + { + "name":"roleId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/deleteEnvironmentRequest":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"deleteEnvironment", + "parameters":[ + { + "name":"envId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"envType", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/deleteConnectorRequests":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"deleteConnectorRequests", + "parameters":[ + { + "name":"connectorId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteCluster":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"deleteCluster", + "parameters":[ + { + "name":"clusterId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/deleteAclRequests":{ + "post":{ + "tags":[ + "acl-controller" + ], + "operationId":"deleteAclRequests", + "parameters":[ + { + "name":"req_no", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/createTopics":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"createTopicsRequest", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TopicRequestModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "$ref":"#/components/schemas/ApiResponse" + } + } + } + } + } + } + }, + "/createTopicDeleteRequest":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"createTopicDeleteRequest", + "parameters":[ + { + "name":"topicName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/createDeleteAclSubscriptionRequest":{ + "post":{ + "tags":[ + "acl-controller" + ], + "operationId":"deleteAclSubscriptionRequest", + "parameters":[ + { + "name":"req_no", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/createConnector":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"createConnectorRequest", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KafkaConnectorRequestModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/createConnectorDeleteRequest":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"createConnectorDeleteRequest", + "parameters":[ + { + "name":"connectorName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/createClaimTopicRequest":{ + "post":{ + "tags":[ + "topic-controller" + ], + "operationId":"createClaimTopicRequest", + "parameters":[ + { + "name":"topicName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/createClaimConnectorRequest":{ + "post":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"createClaimConnectorRequest", + "parameters":[ + { + "name":"connectorName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/createAcl":{ + "post":{ + "tags":[ + "acl-controller" + ], + "operationId":"createAcl", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/AclRequestsModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/chPwd":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"changePwd", + "parameters":[ + { + "name":"changePwd", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/addTenantId":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"addTenantId", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KwTenantModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/addRoleId":{ + "post":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"addRoleId", + "parameters":[ + { + "name":"roleId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/addNewUser":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"addNewUser", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/addNewTeam":{ + "post":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"addNewTeam", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TeamModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/addNewEnv":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"addNewEnv", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/EnvModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"string" + } + } + } + } + } + } + }, + "/addNewCluster":{ + "post":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"addNewCluster", + "requestBody":{ + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KwClustersModel" + } + } + }, + "required":true + }, + "responses":{ + "200":{ + "description":"OK", + "content":{ + "*/*":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/testClusterApiConnection":{ + "get":{ + "tags":[ + "server-config-controller" + ], + "operationId":"testClusterApiConnection", + "parameters":[ + { + "name":"clusterApiUrl", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/shutdownContext":{ + "get":{ + "tags":[ + "util-controller" + ], + "operationId":"shutdownApp", + "responses":{ + "200":{ + "description":"OK" + } + } + } + }, + "/showUserList":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"showUsers", + "parameters":[ + { + "name":"teamName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"searchUserParam", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + } + } + } + } + } + }, + "/resetMemoryCache/{tenantName}/{entityType}/{operationType}":{ + "get":{ + "tags":[ + "util-controller" + ], + "operationId":"resetMemoryCache", + "parameters":[ + { + "name":"tenantName", + "in":"path", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"entityType", + "in":"path", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"operationType", + "in":"path", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/resetCache":{ + "get":{ + "tags":[ + "server-config-controller" + ], + "operationId":"resetCache", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getUserInfoFromRegistrationId":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getRegistrationInfoFromId", + "parameters":[ + { + "name":"userRegistrationId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/RegisterUserInfoModel" + } + } + } + } + } + } + }, + "/getUserDetails":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getUserDetails", + "parameters":[ + { + "name":"userId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + } + } + } + } + }, + "/getUpdateEnvStatus":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getUpdateEnvStatus", + "parameters":[ + { + "name":"envId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getTopics":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopics", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"topicnamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"teamName", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"topicType", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicInfo" + } + } + } + } + } + } + } + } + }, + "/getTopicsRowView":{ + "get":{ + "tags":[ + "topic-sync-controller" + ], + "operationId":"getTopicsRowView", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"topicnamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"teamName", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"topicType", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicInfo" + } + } + } + } + } + } + } + }, + "/getTopicsOnly":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopicsOnly", + "parameters":[ + { + "name":"isMyTeamTopics", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"false" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getTopicsCountPerEnv":{ + "get":{ + "tags":[ + "analytics-controller" + ], + "operationId":"getTopicsCountPerEnv", + "parameters":[ + { + "name":"sourceEnvSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getTopicTeam":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopicTeam", + "parameters":[ + { + "name":"topicName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"patternType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"LITERAL" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getTopicRequests":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopicRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"all" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicRequestModel" + } + } + } + } + } + } + } + }, + "/getTopicEvents":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopicEvents", + "parameters":[ + { + "name":"envId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"topicName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"consumerGroupId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"offsetId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getTopicDetailsPerEnv":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getTopicDetailsPerEnv", + "parameters":[ + { + "name":"envSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"topicname", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"object" + } + } + } + } + } + } + } + }, + "/getTenants":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getTenants", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KwTenantModel" + } + } + } + } + } + } + } + }, + "/getTenantsInfo":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getTenantsInfo", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"integer", + "format":"int32" + } + } + } + } + } + } + } + }, + "/getTeamsOverview":{ + "get":{ + "tags":[ + "analytics-controller" + ], + "operationId":"getTeamsOverview", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TeamOverview" + } + } + } + } + } + } + } + }, + "/getTeamDetails":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getTeamDetails", + "parameters":[ + { + "name":"teamId", + "in":"query", + "required":true, + "schema":{ + "type":"integer", + "format":"int32" + } + }, + { + "name":"tenantName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TeamModel" + } + } + } + } + } + } + }, + "/getSyncTopics":{ + "get":{ + "tags":[ + "topic-sync-controller" + ], + "operationId":"getSyncTopics", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"topicnamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"showAllTopics", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"false" + } + }, + { + "name":"isBulkOption", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"false" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"object" + } + } + } + } + } + } + } + }, + "/getSyncEnv":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getSyncEnv", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/getSyncConnectors":{ + "get":{ + "tags":[ + "kafka-connect-sync-controller" + ], + "operationId":"getSyncTopics_1", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"connectornamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"isBulkOption", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"false" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KafkaConnectorModel" + } + } + } + } + } + } + } + }, + "/getSyncConnectorsEnv":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getSyncConnectorsEnv", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getSyncBackAcls":{ + "get":{ + "tags":[ + "acl-sync-controller" + ], + "operationId":"getSyncBackAcls", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"topicnamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"teamName", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclInfo" + } + } + } + } + } + } + } + }, + "/getSyncAcls":{ + "get":{ + "tags":[ + "acl-sync-controller" + ], + "operationId":"getSyncAcls", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"topicnamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"showAllAcls", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"false" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclInfo" + } + } + } + } + } + } + } + }, + "/getStandardEnvNames":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getStandardEnvNames", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getSchemaRequests":{ + "get":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"getSchemaRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"all" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/SchemaRequestModel" + } + } + } + } + } + } + } + }, + "/getSchemaRegEnvs":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getSchemaRegEnvs", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getSchemaRegEnvsStatus":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getSchemaRegEnvsStatus", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getSchemaOfTopic":{ + "get":{ + "tags":[ + "acl-controller" + ], + "operationId":"getSchemaOfTopic", + "parameters":[ + { + "name":"topicnamesearch", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"schemaVersionSearch", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TopicOverview" + } + } + } + } + } + } + }, + "/getRoles":{ + "get":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"getRoles", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getRolesFromDb":{ + "get":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"getRolesFromDb", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getRequestTypeStatuses":{ + "get":{ + "tags":[ + "ui-config-controller" + ], + "operationId":"getRequestTypeStatuses", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getPermissions":{ + "get":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"getPermissions", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"array", + "items":{ + "type":"object", + "additionalProperties":{ + "type":"boolean" + } + } + } + } + } + } + } + } + } + }, + "/getPermissionDescriptions":{ + "get":{ + "tags":[ + "roles-permissions-controller" + ], + "operationId":"getPermissionDescriptions", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getNewUserRequests":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getNewUserRequests", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/RegisterUserInfoModel" + } + } + } + } + } + } + } + }, + "/getMyTenantInfo":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getMyTenantInfo", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KwTenantModel" + } + } + } + } + } + } + }, + "/getMyProfileInfo":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getMyProfileInfo", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/UserInfoModel" + } + } + } + } + } + } + }, + "/getKwReport":{ + "get":{ + "tags":[ + "analytics-controller" + ], + "operationId":"getKwReport", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getKwPubkey":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getKwPubkey", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getKafkaConnectEnvs":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getKafkaConnectEnvs", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getExtensionPeriods":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getExtensionPeriods", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getEnvs":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvs", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getEnvsPaginated":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvsPaginated", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"envId", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"searchEnvParam", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getEnvsBaseCluster":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvsBaseCluster", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getEnvsBaseClusterFilteredForTeam":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvsBaseClusterFilteredForTeam", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + } + }, + "/getEnvParams":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvParams", + "parameters":[ + { + "name":"envSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/getEnvDetails":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getEnvDetails", + "parameters":[ + { + "name":"envSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"envType", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/EnvModel" + } + } + } + } + } + } + }, + "/getDbAuth":{ + "get":{ + "tags":[ + "ui-config-controller" + ], + "operationId":"getDbAuth", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getDashboardStats":{ + "get":{ + "tags":[ + "util-controller" + ], + "operationId":"getDashboardStats", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getCreatedTopicRequests":{ + "get":{ + "tags":[ + "topic-controller" + ], + "operationId":"getCreatedTopicRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"created" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicRequestModel" + } + } + } + } + } + } + } + }, + "/getCreatedSchemaRequests":{ + "get":{ + "tags":[ + "schema-regstry-controller" + ], + "operationId":"getCreatedSchemaRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"created" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/SchemaRequestModel" + } + } + } + } + } + } + } + }, + "/getCreatedConnectorRequests":{ + "get":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"getCreatedConnectorRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"created" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KafkaConnectorRequestModel" + } + } + } + } + } + } + } + }, + "/getCreatedAclRequests":{ + "get":{ + "tags":[ + "acl-controller" + ], + "operationId":"getCreatedAclRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"created" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclRequestsModel" + } + } + } + } + } + } + } + }, + "/getConsumerOffsets":{ + "get":{ + "tags":[ + "acl-controller" + ], + "operationId":"getConsumerOffsets", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"topicName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"consumerGroupId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/getConnectors":{ + "get":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"getTopics_1", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"connectornamesearch", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + }, + { + "name":"teamName", + "in":"query", + "required":false, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KafkaConnectorModel" + } + } + } + } + } + } + } + } + }, + "/getConnectorRequests":{ + "get":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"getConnectorRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"all" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KafkaConnectorRequestModel" + } + } + } + } + } + } + } + }, + "/getConnectorOverview":{ + "get":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"getConnectorOverview", + "parameters":[ + { + "name":"connectornamesearch", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/ConnectorOverview" + } + } + } + } + } + } + }, + "/getConnectorDetails":{ + "get":{ + "tags":[ + "kafka-connect-sync-controller" + ], + "operationId":"getConnectorDetails", + "parameters":[ + { + "name":"env", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"connectorName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getConnectorDetailsPerEnv":{ + "get":{ + "tags":[ + "kafka-connect-controller" + ], + "operationId":"getConnectorDetailsPerEnv", + "parameters":[ + { + "name":"envSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"connectorName", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"object" + } + } + } + } + } + } + } + }, + "/getClusters":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getClusters", + "parameters":[ + { + "name":"clusterType", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KwClustersModel" + } + } + } + } + } + } + } + }, + "/getClustersPaginated":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getClustersPaginated", + "parameters":[ + { + "name":"clusterType", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"clusterId", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"searchClusterParam", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KwClustersModel" + } + } + } + } + } + } + } + }, + "/getClusterInfoFromEnv":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getClusterInfoFromEnv", + "parameters":[ + { + "name":"envSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"envType", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getClusterDetails":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getClusterDetails", + "parameters":[ + { + "name":"clusterId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/KwClustersModel" + } + } + } + } + } + } + }, + "/getBrokerTopMetrics":{ + "get":{ + "tags":[ + "metrics-controller" + ], + "operationId":"getBrokerTopMetrics", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/JmxOverview" + } + } + } + } + } + } + }, + "/getBasicInfo":{ + "get":{ + "tags":[ + "util-controller" + ], + "operationId":"getBasicInfo", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getAuth":{ + "get":{ + "tags":[ + "util-controller" + ], + "operationId":"getAuth", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getAllTeamsSU":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getAllTeamsSU", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TeamModel" + } + } + } + } + } + } + } + }, + "/getAllTeamsSUOnly":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getAllTeamsSUOnly", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getAllTeamsSUFromRegisterUsers":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getAllTeamsSUFromRegisterUsers", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TeamModel" + } + } + } + } + } + } + } + }, + "/getAllServerEditableConfig":{ + "get":{ + "tags":[ + "server-config-controller" + ], + "operationId":"getAllEditableProps", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "/getAllServerConfig":{ + "get":{ + "tags":[ + "server-config-controller" + ], + "operationId":"getAllProperties", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/ServerConfigProperties" + } + } + } + } + } + } + } + }, + "/getActivityLogPerEnv":{ + "get":{ + "tags":[ + "ui-config-controller" + ], + "operationId":"showActivityLog", + "parameters":[ + { + "name":"env", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/ActivityLog" + } + } + } + } + } + } + } + }, + "/getActivityLogForTeamOverview":{ + "get":{ + "tags":[ + "analytics-controller" + ], + "operationId":"getActivityLogForTeamOverview", + "parameters":[ + { + "name":"activityLogForTeam", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TeamOverview" + } + } + } + } + } + } + }, + "/getActivationInfo":{ + "get":{ + "tags":[ + "users-teams-controller" + ], + "operationId":"getActivationInfo", + "parameters":[ + { + "name":"userActivationId", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getAcls":{ + "get":{ + "tags":[ + "acl-controller" + ], + "operationId":"getAcls", + "parameters":[ + { + "name":"topicnamesearch", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "$ref":"#/components/schemas/TopicOverview" + } + } + } + } + } + } + }, + "/getAclsCountPerEnv":{ + "get":{ + "tags":[ + "analytics-controller" + ], + "operationId":"getAclsCountPerEnv", + "parameters":[ + { + "name":"sourceEnvSelected", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + }, + "/getAclRequests":{ + "get":{ + "tags":[ + "acl-controller" + ], + "operationId":"getAclRequests", + "parameters":[ + { + "name":"pageNo", + "in":"query", + "required":true, + "schema":{ + "type":"string" + } + }, + { + "name":"currentPage", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"" + } + }, + { + "name":"requestsType", + "in":"query", + "required":false, + "schema":{ + "type":"string", + "default":"all" + } + } + ], + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclRequestsModel" + } + } + } + } + } + } + } + }, + "/getAclCommands":{ + "get":{ + "tags":[ + "envs-clusters-tenants-controller" + ], + "operationId":"getAclCommand", + "responses":{ + "200":{ + "description":"OK", + "content":{ + "application/json":{ + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + } + } + } + } + } + } + }, + "components":{ + "schemas":{ + "SchemaRequestModel":{ + "required":[ + "schemafull" + ], + "type":"object", + "properties":{ + "req_no":{ + "type":"integer", + "format":"int32" + }, + "topicname":{ + "type":"string" + }, + "environment":{ + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "schemaversion":{ + "type":"string" + }, + "teamname":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "appname":{ + "type":"string" + }, + "schemafull":{ + "maxLength":2147483647, + "minLength":8, + "type":"string" + }, + "username":{ + "type":"string" + }, + "requesttime":{ + "type":"string", + "format":"date-time" + }, + "requesttimestring":{ + "type":"string" + }, + "topicstatus":{ + "type":"string" + }, + "requesttype":{ + "type":"string" + }, + "remarks":{ + "pattern":"^$|^[a-zA-Z 0-9_.-]{3,}$", + "type":"string" + }, + "approver":{ + "type":"string" + }, + "approvingtime":{ + "type":"string", + "format":"date-time" + }, + "approvingTeamDetails":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "currentPage":{ + "type":"string" + } + } + }, + "ApiResponse":{ + "type":"object", + "properties":{ + "status":{ + "type":"string", + "enum":[ + "100 CONTINUE", + "101 SWITCHING_PROTOCOLS", + "102 PROCESSING", + "103 CHECKPOINT", + "200 OK", + "201 CREATED", + "202 ACCEPTED", + "203 NON_AUTHORITATIVE_INFORMATION", + "204 NO_CONTENT", + "205 RESET_CONTENT", + "206 PARTIAL_CONTENT", + "207 MULTI_STATUS", + "208 ALREADY_REPORTED", + "226 IM_USED", + "300 MULTIPLE_CHOICES", + "301 MOVED_PERMANENTLY", + "302 FOUND", + "302 MOVED_TEMPORARILY", + "303 SEE_OTHER", + "304 NOT_MODIFIED", + "305 USE_PROXY", + "307 TEMPORARY_REDIRECT", + "308 PERMANENT_REDIRECT", + "400 BAD_REQUEST", + "401 UNAUTHORIZED", + "402 PAYMENT_REQUIRED", + "403 FORBIDDEN", + "404 NOT_FOUND", + "405 METHOD_NOT_ALLOWED", + "406 NOT_ACCEPTABLE", + "407 PROXY_AUTHENTICATION_REQUIRED", + "408 REQUEST_TIMEOUT", + "409 CONFLICT", + "410 GONE", + "411 LENGTH_REQUIRED", + "412 PRECONDITION_FAILED", + "413 PAYLOAD_TOO_LARGE", + "413 REQUEST_ENTITY_TOO_LARGE", + "414 URI_TOO_LONG", + "414 REQUEST_URI_TOO_LONG", + "415 UNSUPPORTED_MEDIA_TYPE", + "416 REQUESTED_RANGE_NOT_SATISFIABLE", + "417 EXPECTATION_FAILED", + "418 I_AM_A_TEAPOT", + "419 INSUFFICIENT_SPACE_ON_RESOURCE", + "420 METHOD_FAILURE", + "421 DESTINATION_LOCKED", + "422 UNPROCESSABLE_ENTITY", + "423 LOCKED", + "424 FAILED_DEPENDENCY", + "425 TOO_EARLY", + "426 UPGRADE_REQUIRED", + "428 PRECONDITION_REQUIRED", + "429 TOO_MANY_REQUESTS", + "431 REQUEST_HEADER_FIELDS_TOO_LARGE", + "451 UNAVAILABLE_FOR_LEGAL_REASONS", + "500 INTERNAL_SERVER_ERROR", + "501 NOT_IMPLEMENTED", + "502 BAD_GATEWAY", + "503 SERVICE_UNAVAILABLE", + "504 GATEWAY_TIMEOUT", + "505 HTTP_VERSION_NOT_SUPPORTED", + "506 VARIANT_ALSO_NEGOTIATES", + "507 INSUFFICIENT_STORAGE", + "508 LOOP_DETECTED", + "509 BANDWIDTH_LIMIT_EXCEEDED", + "510 NOT_EXTENDED", + "511 NETWORK_AUTHENTICATION_REQUIRED" + ] + }, + "timestamp":{ + "type":"string", + "format":"date-time" + }, + "message":{ + "type":"string" + }, + "debugMessage":{ + "type":"string" + }, + "result":{ + "type":"string" + }, + "data":{ + "type":"object" + } + } + }, + "UserInfoModel":{ + "required":[ + "fullname", + "username" + ], + "type":"object", + "properties":{ + "username":{ + "maxLength":300, + "minLength":6, + "type":"string" + }, + "userPassword":{ + "type":"string" + }, + "team":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "role":{ + "type":"string" + }, + "fullname":{ + "maxLength":50, + "minLength":5, + "pattern":"^[a-zA-z ]*$", + "type":"string" + }, + "mailid":{ + "type":"string" + }, + "tenantName":{ + "type":"string" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + }, + "TeamModel":{ + "required":[ + "contactperson", + "teamname", + "teamphone" + ], + "type":"object", + "properties":{ + "teamname":{ + "pattern":"^[a-zA-z 0-9]*$", + "type":"string" + }, + "teammail":{ + "type":"string" + }, + "teamphone":{ + "pattern":"(^$|[0-9]*)", + "type":"string" + }, + "contactperson":{ + "pattern":"^[a-zA-z ]*$", + "type":"string" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "app":{ + "type":"string" + }, + "showDeleteTeam":{ + "type":"boolean" + }, + "tenantName":{ + "type":"string" + }, + "envList":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + }, + "SyncTopicUpdates":{ + "type":"object", + "properties":{ + "sequence":{ + "type":"string" + }, + "req_no":{ + "type":"string" + }, + "topicName":{ + "type":"string" + }, + "partitions":{ + "type":"integer", + "format":"int32" + }, + "replicationFactor":{ + "type":"string" + }, + "teamSelected":{ + "type":"string" + }, + "envSelected":{ + "type":"string" + } + } + }, + "SyncTopicsBulk":{ + "type":"object", + "properties":{ + "topicNames":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "sourceEnv":{ + "type":"string" + }, + "selectedTeam":{ + "type":"string" + }, + "typeOfSync":{ + "type":"string" + }, + "topicDetails":{ + "type":"array", + "items":{ + "type":"object" + } + }, + "topicSearchFilter":{ + "type":"string" + } + } + }, + "SyncConnectorUpdates":{ + "type":"object", + "properties":{ + "sequence":{ + "type":"string" + }, + "req_no":{ + "type":"string" + }, + "connectorName":{ + "type":"string" + }, + "teamSelected":{ + "type":"string" + }, + "envSelected":{ + "type":"string" + } + } + }, + "SyncBackTopics":{ + "type":"object", + "properties":{ + "topicIds":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "sourceEnv":{ + "type":"string" + }, + "targetEnv":{ + "type":"string" + }, + "typeOfSync":{ + "type":"string" + } + } + }, + "SyncBackAcls":{ + "type":"object", + "properties":{ + "aclIds":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "sourceEnv":{ + "type":"string" + }, + "targetEnv":{ + "type":"string" + }, + "typeOfSync":{ + "type":"string" + } + } + }, + "SyncAclUpdates":{ + "type":"object", + "properties":{ + "sequence":{ + "type":"string" + }, + "req_no":{ + "type":"string" + }, + "topicName":{ + "type":"string" + }, + "teamSelected":{ + "type":"string" + }, + "consumerGroup":{ + "type":"string" + }, + "aclIp":{ + "type":"string" + }, + "aclSsl":{ + "type":"string" + }, + "aclType":{ + "type":"string" + }, + "envSelected":{ + "type":"string" + } + } + }, + "KwRolesPermissionsModel":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int32" + }, + "roleId":{ + "type":"string" + }, + "permission":{ + "type":"string" + }, + "description":{ + "type":"string" + }, + "rolePermission":{ + "type":"string" + }, + "permissionEnabled":{ + "type":"string" + } + } + }, + "KwPropertiesModel":{ + "type":"object", + "properties":{ + "kwKey":{ + "type":"string" + }, + "kwValue":{ + "type":"string" + }, + "kwDesc":{ + "type":"string" + } + } + }, + "TopicInfo":{ + "type":"object", + "properties":{ + "topicid":{ + "type":"integer", + "format":"int32" + }, + "sequence":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "currentPage":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "topicName":{ + "type":"string" + }, + "noOfPartitions":{ + "type":"integer", + "format":"int32" + }, + "description":{ + "type":"string" + }, + "documentation":{ + "type":"string" + }, + "noOfReplcias":{ + "type":"string" + }, + "teamname":{ + "type":"string" + }, + "cluster":{ + "type":"string" + }, + "clusterId":{ + "type":"string" + }, + "environmentsList":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "showEditTopic":{ + "type":"boolean" + }, + "showDeleteTopic":{ + "type":"boolean" + }, + "topicDeletable":{ + "type":"boolean" + } + } + }, + "KafkaConnectorModel":{ + "type":"object", + "properties":{ + "sequence":{ + "type":"integer", + "format":"int32" + }, + "connectorId":{ + "type":"integer", + "format":"int32" + }, + "connectorName":{ + "type":"string" + }, + "connectorConfig":{ + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "environmentId":{ + "type":"string" + }, + "teamName":{ + "type":"string" + }, + "possibleTeams":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "totalNoPages":{ + "type":"string" + }, + "currentPage":{ + "type":"string" + }, + "remarks":{ + "type":"string" + }, + "documentation":{ + "type":"string" + }, + "environmentsList":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "description":{ + "type":"string" + }, + "showEditConnector":{ + "type":"boolean" + }, + "showDeleteConnector":{ + "type":"boolean" + }, + "connectorDeletable":{ + "type":"boolean" + } + } + }, + "RegisterUserInfoModel":{ + "required":[ + "fullname", + "username" + ], + "type":"object", + "properties":{ + "username":{ + "maxLength":300, + "minLength":6, + "pattern":"^[a-zA-Z0-9]{3,}$", + "type":"string" + }, + "pwd":{ + "type":"string" + }, + "team":{ + "type":"string" + }, + "role":{ + "type":"string" + }, + "fullname":{ + "maxLength":50, + "minLength":5, + "pattern":"^[a-zA-z ]*$", + "type":"string" + }, + "mailid":{ + "type":"string" + }, + "status":{ + "type":"string" + }, + "registeredTime":{ + "type":"string", + "format":"date-time" + }, + "approver":{ + "type":"string" + }, + "registrationId":{ + "type":"string" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "tenantName":{ + "type":"string" + } + } + }, + "RegisterSaasUserInfoModel":{ + "required":[ + "fullname" + ], + "type":"object", + "properties":{ + "fullname":{ + "maxLength":300, + "minLength":4, + "pattern":"^[a-zA-z ]*$", + "type":"string" + }, + "mailid":{ + "type":"string" + }, + "recaptchaStr":{ + "type":"string" + }, + "status":{ + "type":"string" + }, + "registeredTime":{ + "type":"string", + "format":"date-time" + }, + "approver":{ + "type":"string" + }, + "registrationId":{ + "type":"string" + }, + "tenantName":{ + "type":"string" + } + } + }, + "TopicRequestModel":{ + "required":[ + "description", + "environment", + "replicationfactor", + "teamname", + "topicname", + "topicpartitions" + ], + "type":"object", + "properties":{ + "topicname":{ + "pattern":"^[a-zA-Z0-9._-]{3,}$", + "type":"string" + }, + "environment":{ + "type":"string" + }, + "topicpartitions":{ + "minimum":1, + "type":"integer", + "format":"int32" + }, + "teamname":{ + "type":"string" + }, + "remarks":{ + "pattern":"^$|^[a-zA-Z 0-9_.,-]{3,}$", + "type":"string" + }, + "description":{ + "pattern":"^[a-zA-Z 0-9_.,-]{3,}$", + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "topicid":{ + "type":"integer", + "format":"int32" + }, + "replicationfactor":{ + "type":"string" + }, + "appname":{ + "type":"string" + }, + "topictype":{ + "type":"string" + }, + "requestor":{ + "type":"string" + }, + "requesttime":{ + "type":"string", + "format":"date-time" + }, + "requesttimestring":{ + "type":"string" + }, + "topicstatus":{ + "type":"string" + }, + "approver":{ + "type":"string" + }, + "approvingtime":{ + "type":"string", + "format":"date-time" + }, + "sequence":{ + "type":"string" + }, + "username":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "approvingTeamDetails":{ + "type":"string" + }, + "otherParams":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "possibleTeams":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "currentPage":{ + "type":"string" + } + } + }, + "KafkaConnectorRequestModel":{ + "required":[ + "connectorName", + "description", + "environment", + "teamName" + ], + "type":"object", + "properties":{ + "connectorName":{ + "pattern":"^[a-zA-Z0-9._-]{3,}$", + "type":"string" + }, + "connectorConfig":{ + "type":"string" + }, + "environment":{ + "type":"string" + }, + "teamName":{ + "type":"string" + }, + "remarks":{ + "pattern":"^$|^[a-zA-Z 0-9_.,-]{3,}$", + "type":"string" + }, + "description":{ + "pattern":"^[a-zA-Z 0-9_.,-]{3,}$", + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "connectorId":{ + "type":"integer", + "format":"int32" + }, + "connectortype":{ + "type":"string" + }, + "requestor":{ + "type":"string" + }, + "requesttime":{ + "type":"string", + "format":"date-time" + }, + "requesttimestring":{ + "type":"string" + }, + "connectorStatus":{ + "type":"string" + }, + "approver":{ + "type":"string" + }, + "approvingtime":{ + "type":"string", + "format":"date-time" + }, + "sequence":{ + "type":"string" + }, + "username":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "approvingTeamDetails":{ + "type":"string" + }, + "otherParams":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "possibleTeams":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "currentPage":{ + "type":"string" + } + } + }, + "AclRequestsModel":{ + "required":[ + "aclPatternType" + ], + "type":"object", + "properties":{ + "remarks":{ + "pattern":"^$|^[a-zA-Z 0-9_.,-]{3,}$", + "type":"string" + }, + "consumergroup":{ + "pattern":"^$|^[a-zA-Z0-9_.-]{3,}$", + "type":"string" + }, + "acl_ip":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "acl_ssl":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "aclPatternType":{ + "type":"string" + }, + "transactionalId":{ + "pattern":"^$|^[a-zA-Z0-9_.-]{3,}$", + "type":"string" + }, + "req_no":{ + "type":"integer", + "format":"int32" + }, + "topicname":{ + "type":"string" + }, + "environment":{ + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "teamname":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "requestingteam":{ + "type":"integer", + "format":"int32" + }, + "appname":{ + "type":"string" + }, + "topictype":{ + "type":"string" + }, + "username":{ + "type":"string" + }, + "requesttime":{ + "type":"string", + "format":"date-time" + }, + "requesttimestring":{ + "type":"string" + }, + "aclstatus":{ + "type":"string" + }, + "approver":{ + "type":"string" + }, + "approvingtime":{ + "type":"string", + "format":"date-time" + }, + "aclType":{ + "type":"string" + }, + "aclIpPrincipleType":{ + "type":"string", + "enum":[ + "IP_ADDRESS", + "PRINCIPAL", + "USERNAME" + ] + }, + "aclResourceType":{ + "type":"string" + }, + "currentPage":{ + "type":"string" + }, + "otherParams":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "approvingTeamDetails":{ + "type":"string" + } + } + }, + "KwTenantModel":{ + "required":[ + "tenantDesc", + "tenantName" + ], + "type":"object", + "properties":{ + "tenantName":{ + "maxLength":25, + "minLength":12, + "pattern":"^[a-zA-Z0-9]{3,}$", + "type":"string" + }, + "tenantDesc":{ + "maxLength":25, + "minLength":6, + "pattern":"^[a-zA-Z 0-9]{3,}$", + "type":"string" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "licenseExpiryDate":{ + "type":"string" + }, + "contactPerson":{ + "type":"string" + }, + "inTrialPhase":{ + "type":"boolean" + }, + "numberOfDays":{ + "type":"string" + }, + "numberOfHours":{ + "type":"string" + }, + "orgName":{ + "type":"string" + }, + "authorizedToDelete":{ + "type":"boolean" + }, + "emailId":{ + "type":"string" + }, + "activeTenant":{ + "type":"boolean" + } + } + }, + "EnvModel":{ + "required":[ + "clusterId", + "name", + "type" + ], + "type":"object", + "properties":{ + "id":{ + "type":"string" + }, + "name":{ + "maxLength":7, + "minLength":3, + "pattern":"^[a-zA-Z0-9_-]{3,}$", + "type":"string" + }, + "type":{ + "type":"string" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "topicprefix":{ + "pattern":"^$|^[a-zA-Z0-9_.-]{3,}$", + "type":"string" + }, + "topicsuffix":{ + "pattern":"^$|^[a-zA-Z0-9_.-]{3,}$", + "type":"string" + }, + "clusterId":{ + "type":"integer", + "format":"int32" + }, + "tenantName":{ + "type":"string" + }, + "clusterName":{ + "type":"string" + }, + "envStatus":{ + "type":"string" + }, + "otherParams":{ + "type":"string" + }, + "defaultPartitions":{ + "type":"string" + }, + "maxPartitions":{ + "type":"string" + }, + "defaultReplicationFactor":{ + "type":"string" + }, + "maxReplicationFactor":{ + "type":"string" + }, + "showDeleteEnv":{ + "type":"boolean" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + }, + "KwClustersModel":{ + "required":[ + "bootstrapServers", + "clusterName", + "clusterType", + "kafkaFlavor", + "protocol" + ], + "type":"object", + "properties":{ + "clusterId":{ + "type":"integer", + "format":"int32" + }, + "clusterName":{ + "pattern":"^[a-zA-Z0-9._-]{3,}$", + "type":"string" + }, + "bootstrapServers":{ + "maxLength":2147483647, + "minLength":6, + "pattern":"^[a-zA-Z0-9._:,-]{3,}$", + "type":"string" + }, + "protocol":{ + "type":"string" + }, + "clusterType":{ + "type":"string" + }, + "kafkaFlavor":{ + "type":"string" + }, + "projectName":{ + "type":"string" + }, + "serviceName":{ + "type":"string" + }, + "publicKey":{ + "type":"string" + }, + "showDeleteCluster":{ + "type":"boolean" + }, + "clusterStatus":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + }, + "ChartsJsOverview":{ + "type":"object", + "properties":{ + "data":{ + "type":"array", + "items":{ + "type":"integer", + "format":"int32" + } + }, + "labels":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "colors":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "options":{ + "$ref":"#/components/schemas/Options" + }, + "series":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "titleForReport":{ + "type":"string" + }, + "xaxisLabel":{ + "type":"string" + }, + "yaxisLabel":{ + "type":"string" + } + } + }, + "Options":{ + "type":"object", + "properties":{ + "title":{ + "$ref":"#/components/schemas/Title" + }, + "scales":{ + "$ref":"#/components/schemas/Scales" + } + } + }, + "Scales":{ + "type":"object", + "properties":{ + "yaxes":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/YAx" + } + }, + "xaxes":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/YAx" + } + } + } + }, + "TeamOverview":{ + "type":"object", + "properties":{ + "producerAclsPerTeamsOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "consumerAclsPerTeamsOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "aclsPerEnvOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "topicsPerTeamsOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "topicsPerTeamPerEnvOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "topicsPerEnvOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "partitionsPerEnvOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "activityLogOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + }, + "tenantName":{ + "type":"string" + } + } + }, + "Title":{ + "type":"object", + "properties":{ + "display":{ + "type":"boolean" + }, + "text":{ + "type":"string" + }, + "position":{ + "type":"string" + }, + "fontColor":{ + "type":"string" + }, + "fontFamily":{ + "type":"string" + }, + "fontStyle":{ + "type":"string" + } + } + }, + "YAx":{ + "type":"object", + "properties":{ + "id":{ + "type":"string" + }, + "type":{ + "type":"string" + }, + "display":{ + "type":"boolean" + }, + "position":{ + "type":"string" + } + } + }, + "AclInfo":{ + "type":"object", + "properties":{ + "sequence":{ + "type":"string" + }, + "req_no":{ + "type":"string" + }, + "acl_ip":{ + "type":"string" + }, + "acl_ssl":{ + "type":"string" + }, + "topicname":{ + "type":"string" + }, + "topictype":{ + "type":"string" + }, + "consumergroup":{ + "type":"string" + }, + "environment":{ + "type":"string" + }, + "environmentName":{ + "type":"string" + }, + "teamname":{ + "type":"string" + }, + "teamid":{ + "type":"integer", + "format":"int32" + }, + "operation":{ + "type":"string" + }, + "permission":{ + "type":"string" + }, + "transactionalId":{ + "type":"string" + }, + "aclPatternType":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "possibleTeams":{ + "type":"array", + "items":{ + "type":"string" + } + }, + "currentPage":{ + "type":"string" + }, + "showDeleteAcl":{ + "type":"boolean" + } + } + }, + "TopicHistory":{ + "type":"object", + "properties":{ + "environmentName":{ + "type":"string" + }, + "teamName":{ + "type":"string" + }, + "requestedBy":{ + "type":"string" + }, + "requestedTime":{ + "type":"string" + }, + "approvedBy":{ + "type":"string" + }, + "approvedTime":{ + "type":"string" + }, + "remarks":{ + "type":"string" + } + } + }, + "TopicOverview":{ + "type":"object", + "properties":{ + "topicInfoList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicInfo" + } + }, + "aclInfoList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclInfo" + } + }, + "prefixedAclInfoList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclInfo" + } + }, + "transactionalAclInfoList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/AclInfo" + } + }, + "topicHistoryList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicHistory" + } + }, + "promotionDetails":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + }, + "topicExists":{ + "type":"boolean" + }, + "schemaDetails":{ + "type":"array", + "items":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + } + }, + "schemaExists":{ + "type":"boolean" + }, + "prefixAclsExists":{ + "type":"boolean" + }, + "txnAclsExists":{ + "type":"boolean" + }, + "topicDocumentation":{ + "type":"string" + }, + "topicIdForDocumentation":{ + "type":"integer", + "format":"int32" + } + } + }, + "ConnectorOverview":{ + "type":"object", + "properties":{ + "topicInfoList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/KafkaConnectorModel" + } + }, + "topicHistoryList":{ + "type":"array", + "items":{ + "$ref":"#/components/schemas/TopicHistory" + } + }, + "promotionDetails":{ + "type":"object", + "additionalProperties":{ + "type":"string" + } + }, + "connectorExists":{ + "type":"boolean" + }, + "topicDocumentation":{ + "type":"string" + }, + "topicIdForDocumentation":{ + "type":"integer", + "format":"int32" + } + } + }, + "JmxOverview":{ + "type":"object", + "properties":{ + "brokerTopMetricsOverview":{ + "$ref":"#/components/schemas/ChartsJsOverview" + } + } + }, + "ServerConfigProperties":{ + "type":"object", + "properties":{ + "id":{ + "type":"string" + }, + "key":{ + "type":"string" + }, + "value":{ + "type":"string" + } + } + }, + "ActivityLog":{ + "type":"object", + "properties":{ + "req_no":{ + "type":"integer", + "format":"int32" + }, + "tenantId":{ + "type":"integer", + "format":"int32" + }, + "activityName":{ + "type":"string" + }, + "activityType":{ + "type":"string" + }, + "activityTime":{ + "type":"string", + "format":"date-time" + }, + "activityTimeString":{ + "type":"string" + }, + "details":{ + "type":"string" + }, + "user":{ + "type":"string" + }, + "teamId":{ + "type":"integer", + "format":"int32" + }, + "env":{ + "type":"string" + }, + "envName":{ + "type":"string" + }, + "team":{ + "type":"string" + }, + "totalNoPages":{ + "type":"string" + }, + "currentPage":{ + "type":"string" + }, + "allPageNos":{ + "type":"array", + "items":{ + "type":"string" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java index 0313c0c4d7..5c96533ab2 100644 --- a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java @@ -15,6 +15,7 @@ import io.aiven.klaw.model.SyncAclUpdates; import io.aiven.klaw.model.TopicOverview; import io.aiven.klaw.service.AclControllerService; +import io.aiven.klaw.service.AclSyncControllerService; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,21 +36,31 @@ public class AclControllerTest { public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @MockBean private AclControllerService aclControllerService; + @MockBean private AclSyncControllerService aclSyncControllerService; + private UtilMethods utilMethods; - private MockMvc mvc; + private MockMvc mvcAcls; private AclController aclController; + private MockMvc mvcAclsSync; + + private AclSyncController aclSyncController; + private static final String topicName = "testtopic"; private static final int topicId = 1001; @BeforeEach public void setup() { aclController = new AclController(); + aclSyncController = new AclSyncController(); utilMethods = new UtilMethods(); - mvc = MockMvcBuilders.standaloneSetup(aclController).dispatchOptions(true).build(); + mvcAcls = MockMvcBuilders.standaloneSetup(aclController).dispatchOptions(true).build(); ReflectionTestUtils.setField(aclController, "aclControllerService", aclControllerService); + mvcAclsSync = MockMvcBuilders.standaloneSetup(aclSyncController).dispatchOptions(true).build(); + ReflectionTestUtils.setField( + aclSyncController, "aclSyncControllerService", aclSyncControllerService); } @Test @@ -60,7 +71,8 @@ public void createAcl() throws Exception { when(aclControllerService.createAcl(any())).thenReturn("success"); String response = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.post("/createAcl") .content(jsonReq) .contentType(MediaType.APPLICATION_JSON) @@ -80,10 +92,11 @@ public void updateSyncAcls() throws Exception { String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(syncUpdates); Map result = new HashMap<>(); result.put("result", "success"); - when(aclControllerService.updateSyncAcls(any())).thenReturn(result); + when(aclSyncControllerService.updateSyncAcls(any())).thenReturn(result); String response = - mvc.perform( + mvcAclsSync + .perform( MockMvcRequestBuilders.post("/updateSyncAcls") .content(jsonReq) .contentType(MediaType.APPLICATION_JSON) @@ -94,7 +107,7 @@ public void updateSyncAcls() throws Exception { .getContentAsString(); Map actualResult = - new ObjectMapper().readValue(response, new TypeReference>() {}); + new ObjectMapper().readValue(response, new TypeReference<>() {}); assertThat(actualResult).containsEntry("result", "success"); } @@ -107,7 +120,8 @@ public void getAclRequests() throws Exception { when(aclControllerService.getAclRequests("1", "", "all")).thenReturn(aclRequests); String res = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.get("/getAclRequests") .contentType(MediaType.APPLICATION_JSON) .param("pageNo", "1") @@ -129,7 +143,8 @@ public void getCreatedAclRequests() throws Exception { when(aclControllerService.getCreatedAclRequests("1", "", "created")).thenReturn(aclRequests); String res = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.get("/getCreatedAclRequests") .param("pageNo", "1") .contentType(MediaType.APPLICATION_JSON) @@ -148,7 +163,8 @@ public void deleteAclRequests() throws Exception { when(aclControllerService.deleteAclRequests(anyString())).thenReturn("success"); String response = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.post("/deleteAclRequests") .param("req_no", "fsda32FSDw") .contentType(MediaType.APPLICATION_JSON) @@ -167,7 +183,8 @@ public void approveAclRequests() throws Exception { when(aclControllerService.approveAclRequests(anyString())).thenReturn(apiResponse); String response = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.post("/execAclRequest") .param("req_no", "reqno") .contentType(MediaType.APPLICATION_JSON) @@ -185,7 +202,8 @@ public void declineAclRequests() throws Exception { when(aclControllerService.declineAclRequests(anyString(), anyString())).thenReturn("success"); String response = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.post("/execAclRequestDecline") .param("req_no", "reqno") .param("reasonForDecline", "reason") @@ -206,7 +224,8 @@ public void getAcls1() throws Exception { when(aclControllerService.getAcls("testtopic")).thenReturn(topicOverview); String res = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.get("/getAcls") .param("topicnamesearch", "testtopic") .contentType(MediaType.APPLICATION_JSON) @@ -227,7 +246,8 @@ public void getAcls2() throws Exception { when(aclControllerService.getAcls(null)).thenReturn(topicOverview); String res = - mvc.perform( + mvcAcls + .perform( MockMvcRequestBuilders.get("/getAcls") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) @@ -241,11 +261,12 @@ public void getAcls2() throws Exception { public void getSyncAcls() throws Exception { List aclInfo = utilMethods.getAclInfoList(); - when(aclControllerService.getSyncAcls(anyString(), anyString(), anyString(), any(), any())) + when(aclSyncControllerService.getSyncAcls(anyString(), anyString(), anyString(), any(), any())) .thenReturn(aclInfo); String res = - mvc.perform( + mvcAclsSync + .perform( MockMvcRequestBuilders.get("/getSyncAcls") .param("env", "DEV") .param("pageNo", "1") diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index 90697f638d..ed409fa5ab 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -74,18 +74,24 @@ public class AclControllerServiceTest { @Mock private UserInfo userInfo; private AclControllerService aclControllerService; + + private AclSyncControllerService aclSyncControllerService; private Env env; @BeforeEach public void setUp() throws Exception { utilMethods = new UtilMethods(); this.aclControllerService = new AclControllerService(clusterApiService, mailService); + this.aclSyncControllerService = new AclSyncControllerService(clusterApiService, mailService); this.env = new Env(); env.setName("DEV"); env.setId("1"); ReflectionTestUtils.setField(aclControllerService, "manageDatabase", manageDatabase); ReflectionTestUtils.setField(aclControllerService, "commonUtilsService", commonUtilsService); + ReflectionTestUtils.setField(aclSyncControllerService, "manageDatabase", manageDatabase); + ReflectionTestUtils.setField( + aclSyncControllerService, "commonUtilsService", commonUtilsService); ReflectionTestUtils.setField( aclControllerService, "rolesPermissionsControllerService", @@ -130,7 +136,7 @@ public void updateSyncAcls() { .thenReturn(Collections.singletonList("1")); Map result = - aclControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); assertThat(result).containsEntry("result", "success"); } @@ -141,7 +147,7 @@ public void updateSyncAclsFailure1() { when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); Map result = - aclControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); assertThat(result).containsEntry("result", "Not Authorized."); } @@ -155,7 +161,7 @@ public void updateSyncAclsFailure2() { .thenReturn(Collections.singletonList("1")); Map result = - aclControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); assertThat(result.get("result")).contains("Failure"); } @@ -173,7 +179,7 @@ public void updateSyncAclsFailure3() { when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = aclControllerService.updateSyncAcls(updates); + Map result = aclSyncControllerService.updateSyncAcls(updates); assertThat(result).containsEntry("result", "No record updated."); } @@ -187,7 +193,7 @@ public void updateSyncAclsFailure4() { .thenReturn(Collections.singletonList("1")); Map result = - aclControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); assertThat(result.get("result")).contains("Failure"); } @@ -421,7 +427,7 @@ public void getAclsSyncTrue1() throws KlawException { when(commonUtilsService.deriveCurrentPage(anyString(), anyString(), anyInt())).thenReturn("1"); List aclList = - aclControllerService.getSyncAcls(envSelected, pageNo, "", topicNameSearch, ""); + aclSyncControllerService.getSyncAcls(envSelected, pageNo, "", topicNameSearch, ""); assertThat(aclList).isEmpty(); } @@ -447,7 +453,7 @@ public void getAclsSyncTrue2() throws KlawException { when(commonUtilsService.deriveCurrentPage(anyString(), anyString(), anyInt())).thenReturn("1"); List aclList = - aclControllerService.getSyncAcls(envSelected, pageNo, "", topicNameSearch, ""); + aclSyncControllerService.getSyncAcls(envSelected, pageNo, "", topicNameSearch, ""); assertThat(aclList).isEmpty(); } From 3255de72d5c4adf257c35a4f7c9b8bba12180593 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Tue, 4 Oct 2022 18:05:00 +0200 Subject: [PATCH 07/15] Updating response with ApiResponse for a few apis --- .../aiven/klaw/controller/AclController.java | 45 ++++--- .../klaw/controller/AclSyncController.java | 26 ++-- .../EnvsClustersTenantsController.java | 16 ++- .../controller/KafkaConnectController.java | 2 +- .../KafkaConnectSyncController.java | 19 +-- .../controller/ResourceClientController.java | 9 +- .../RolesPermissionsController.java | 35 ++++-- .../klaw/service/AclControllerService.java | 116 ++++++++---------- .../service/AclSyncControllerService.java | 65 +++++----- .../service/AnalyticsControllerService.java | 3 +- .../EnvsClustersTenantsControllerService.java | 35 +++--- .../KafkaConnectControllerService.java | 82 ++++++------- .../KafkaConnectSyncControllerService.java | 71 ++++++----- .../RolesPermissionsControllerService.java | 96 ++++++++------- .../klaw/service/UtilControllerService.java | 13 ++ src/main/resources/static/js/syncBackAcls.js | 2 +- .../klaw/controller/AclControllerTest.java | 34 ++--- .../service/AclControllerServiceTest.java | 61 ++++----- 18 files changed, 397 insertions(+), 333 deletions(-) diff --git a/src/main/java/io/aiven/klaw/controller/AclController.java b/src/main/java/io/aiven/klaw/controller/AclController.java index 29d61186cb..8e1e6603dd 100644 --- a/src/main/java/io/aiven/klaw/controller/AclController.java +++ b/src/main/java/io/aiven/klaw/controller/AclController.java @@ -1,5 +1,7 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.*; import io.aiven.klaw.service.AclControllerService; @@ -26,8 +28,12 @@ public class AclController { @Autowired AclControllerService aclControllerService; @PostMapping(value = "/createAcl") - public ResponseEntity createAcl(@Valid @RequestBody AclRequestsModel addAclRequest) { - return new ResponseEntity<>(aclControllerService.createAcl(addAclRequest), HttpStatus.OK); + public ResponseEntity createAcl(@Valid @RequestBody AclRequestsModel addAclRequest) { + try { + return new ResponseEntity<>(aclControllerService.createAcl(addAclRequest), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -62,8 +68,12 @@ public ResponseEntity> getCreatedAclRequests( value = "/deleteAclRequests", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteAclRequests(@RequestParam("req_no") String req_no) { - return new ResponseEntity<>(aclControllerService.deleteAclRequests(req_no), HttpStatus.OK); + public ResponseEntity deleteAclRequests(@RequestParam("req_no") String req_no) { + try { + return new ResponseEntity<>(aclControllerService.deleteAclRequests(req_no), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/execAclRequest") @@ -71,25 +81,31 @@ public ResponseEntity approveAclRequests(@RequestParam("req_no") St try { return new ResponseEntity<>(aclControllerService.approveAclRequests(req_no), HttpStatus.OK); } catch (KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder().message("Unable to approve acl request").build(), HttpStatus.OK); + return handleException(e); } } @PostMapping(value = "/createDeleteAclSubscriptionRequest") - public ResponseEntity deleteAclSubscriptionRequest( + public ResponseEntity deleteAclSubscriptionRequest( @RequestParam("req_no") String req_no) { - return new ResponseEntity<>( - aclControllerService.createDeleteAclSubscriptionRequest(req_no), HttpStatus.OK); + try { + return new ResponseEntity<>( + aclControllerService.createDeleteAclSubscriptionRequest(req_no), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/execAclRequestDecline") - public ResponseEntity declineAclRequests( + public ResponseEntity declineAclRequests( @RequestParam("req_no") String req_no, @RequestParam("reasonForDecline") String reasonForDecline) { - return new ResponseEntity<>( - aclControllerService.declineAclRequests(req_no, reasonForDecline), HttpStatus.OK); + try { + return new ResponseEntity<>( + aclControllerService.declineAclRequests(req_no, reasonForDecline), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -120,8 +136,7 @@ public ResponseEntity getSchemaOfTopic( public ResponseEntity>> getConsumerOffsets( @RequestParam("env") String envId, @RequestParam("topicName") String topicName, - @RequestParam(value = "consumerGroupId") String consumerGroupId) - throws KlawException { + @RequestParam(value = "consumerGroupId") String consumerGroupId) { return new ResponseEntity<>( aclControllerService.getConsumerOffsets(envId, consumerGroupId, topicName), HttpStatus.OK); } diff --git a/src/main/java/io/aiven/klaw/controller/AclSyncController.java b/src/main/java/io/aiven/klaw/controller/AclSyncController.java index 969cf5dff5..36195d4120 100644 --- a/src/main/java/io/aiven/klaw/controller/AclSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/AclSyncController.java @@ -1,12 +1,14 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SyncAclUpdates; import io.aiven.klaw.model.SyncBackAcls; import io.aiven.klaw.service.AclSyncControllerService; import java.util.List; -import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -27,10 +29,14 @@ public class AclSyncController { @Autowired AclSyncControllerService aclSyncControllerService; @PostMapping(value = "/updateSyncAcls") - public ResponseEntity> updateSyncAcls( + public ResponseEntity updateSyncAcls( @RequestBody List syncAclUpdates) { - return new ResponseEntity<>( - aclSyncControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); + try { + return new ResponseEntity<>( + aclSyncControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -50,11 +56,13 @@ public ResponseEntity> getSyncBackAcls( } @PostMapping(value = "/updateSyncBackAcls") - public ResponseEntity>> updateSyncBackAcls( - @RequestBody SyncBackAcls syncBackAcls) { - Map> updateSyncAclsResult = - aclSyncControllerService.updateSyncBackAcls(syncBackAcls); - return new ResponseEntity<>(updateSyncAclsResult, HttpStatus.OK); + public ResponseEntity updateSyncBackAcls(@RequestBody SyncBackAcls syncBackAcls) { + try { + return new ResponseEntity<>( + aclSyncControllerService.updateSyncBackAcls(syncBackAcls), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } // get acls from kafka cluster diff --git a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java index 3cefdbea16..2a6bf6d77e 100644 --- a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java +++ b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java @@ -1,5 +1,9 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.KwClustersModel; import io.aiven.klaw.model.KwTenantModel; @@ -75,13 +79,17 @@ public ResponseEntity> getEnvsBaseClusterFilteredForTeam() { } @PostMapping(value = "/deleteCluster") - public ResponseEntity deleteCluster(@RequestParam("clusterId") String clusterId) { - return new ResponseEntity<>( - envsClustersTenantsControllerService.deleteCluster(clusterId), HttpStatus.OK); + public ResponseEntity deleteCluster(@RequestParam("clusterId") String clusterId) { + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.deleteCluster(clusterId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/addNewCluster") - public ResponseEntity> addNewCluster( + public ResponseEntity addNewCluster( @Valid @RequestBody KwClustersModel kwClustersModel) { return new ResponseEntity<>( envsClustersTenantsControllerService.addNewCluster(kwClustersModel), HttpStatus.OK); diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java index 3b309827c6..9a783b16fa 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java @@ -29,7 +29,7 @@ public class KafkaConnectController { @Autowired KafkaConnectControllerService kafkaConnectControllerService; @PostMapping(value = "/createConnector") - public ResponseEntity> createConnectorRequest( + public ResponseEntity createConnectorRequest( @Valid @RequestBody KafkaConnectorRequestModel addTopicRequest) throws KlawException { return new ResponseEntity<>( kafkaConnectControllerService.createConnectorRequest(addTopicRequest), HttpStatus.OK); diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java index 6c112408ee..0e45f04268 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java @@ -1,6 +1,9 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KafkaConnectorModel; import io.aiven.klaw.model.SyncConnectorUpdates; import io.aiven.klaw.service.KafkaConnectSyncControllerService; @@ -24,11 +27,14 @@ public class KafkaConnectSyncController { @Autowired KafkaConnectSyncControllerService kafkaConnectControllerService; @PostMapping(value = "/updateSyncConnectors") - public ResponseEntity> updateSyncTopics( + public ResponseEntity updateSyncConnectors( @RequestBody List syncConnectorUpdates) { - Map updateSyncConnectorsResult = - kafkaConnectControllerService.updateSyncConnectors(syncConnectorUpdates); - return new ResponseEntity<>(updateSyncConnectorsResult, HttpStatus.OK); + try { + return new ResponseEntity<>( + kafkaConnectControllerService.updateSyncConnectors(syncConnectorUpdates), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -54,14 +60,9 @@ public ResponseEntity> getSyncTopics( @RequestParam(value = "isBulkOption", defaultValue = "false", required = false) String isBulkOption) throws Exception { - // if(Boolean.parseBoolean(showAllTopics)) return new ResponseEntity<>( kafkaConnectControllerService.getSyncConnectors( envId, pageNo, currentPage, connectorNameSearch, Boolean.parseBoolean(isBulkOption)), HttpStatus.OK); - // else - // return new ResponseEntity<>(topicSyncControllerService.getReconTopics(envId, - // pageNo, currentPage, topicNameSearch, - // showAllTopics, Boolean.parseBoolean(isBulkOption)), HttpStatus.OK); } } diff --git a/src/main/java/io/aiven/klaw/controller/ResourceClientController.java b/src/main/java/io/aiven/klaw/controller/ResourceClientController.java index 9d61e9ef18..16d0bc5bf1 100644 --- a/src/main/java/io/aiven/klaw/controller/ResourceClientController.java +++ b/src/main/java/io/aiven/klaw/controller/ResourceClientController.java @@ -33,10 +33,14 @@ public class ResourceClientController { @Value("${spring.security.oauth2.client.provider.klaw.user-info-uri:testResourceUrl}") private String userInfoUri; + private static final String authorizationRequestBaseUri = "oauth2/authorize-client"; + Map oauth2AuthenticationUrls = new HashMap<>(); @Autowired private OAuth2AuthorizedClientService authorizedClientService; @Autowired private WebClient webClient; + @Autowired private ClientRegistrationRepository clientRegistrationRepository; + @GetMapping("/resources") public String getFoos( Model model, @@ -73,11 +77,6 @@ private String checkAnonymousLogin( } } - private static final String authorizationRequestBaseUri = "oauth2/authorize-client"; - Map oauth2AuthenticationUrls = new HashMap<>(); - - @Autowired private ClientRegistrationRepository clientRegistrationRepository; - @GetMapping("/oauthLogin") public String getLoginPage( Model model, OAuth2AuthenticationToken authentication, HttpServletResponse response) { diff --git a/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java b/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java index 4320155a28..e140cc377f 100644 --- a/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java +++ b/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java @@ -1,5 +1,9 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KwRolesPermissionsModel; import io.aiven.klaw.service.RolesPermissionsControllerService; import java.util.List; @@ -56,21 +60,34 @@ public ResponseEntity>>> getPermissions() } @PostMapping(value = "/deleteRole") - public ResponseEntity> deleteRole(@RequestParam("roleId") String roleId) { - return new ResponseEntity<>( - rolesPermissionsControllerService.deleteRole(roleId), HttpStatus.OK); + public ResponseEntity deleteRole(@RequestParam("roleId") String roleId) { + try { + return new ResponseEntity<>( + rolesPermissionsControllerService.deleteRole(roleId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/addRoleId") - public ResponseEntity> addRoleId(@RequestParam("roleId") String roleId) { - return new ResponseEntity<>(rolesPermissionsControllerService.addRoleId(roleId), HttpStatus.OK); + public ResponseEntity addRoleId(@RequestParam("roleId") String roleId) { + try { + return new ResponseEntity<>( + rolesPermissionsControllerService.addRoleId(roleId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/updatePermissions") - public ResponseEntity> updatePermissions( + public ResponseEntity updatePermissions( @RequestBody KwRolesPermissionsModel[] kwRolesPermissionsModels) { - return new ResponseEntity<>( - rolesPermissionsControllerService.updatePermissions(kwRolesPermissionsModels), - HttpStatus.OK); + try { + return new ResponseEntity<>( + rolesPermissionsControllerService.updatePermissions(kwRolesPermissionsModels), + HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } } diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index d356027e1a..a03630ccf2 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -43,7 +43,6 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -69,7 +68,7 @@ public class AclControllerService { this.mailService = mailService; } - public String createAcl(AclRequestsModel aclReq) { + public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { log.info("createAcl {}", aclReq); String userDetails = getUserName(); aclReq.setAclType("Create"); @@ -81,7 +80,7 @@ public String createAcl(AclRequestsModel aclReq) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } List topics = @@ -97,18 +96,18 @@ public String createAcl(AclRequestsModel aclReq) { } } result = "Failure : Topic not found on target environment."; - if (!topicFound) return "{\"result\":\"" + result + "\"}"; + if (!topicFound) return ApiResponse.builder().result(result).build(); } if ("Consumer".equals(aclReq.getTopictype())) { if ("PREFIXED".equals(aclReq.getAclPatternType())) { result = "Failure : Please change the pattern to LITERAL for topic type."; - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); } if (validateTeamConsumerGroup( aclReq.getRequestingteam(), aclReq.getConsumergroup(), tenantId)) { result = "Failure : Consumer group " + aclReq.getConsumergroup() + " used by another team."; - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); } } @@ -121,12 +120,12 @@ public String createAcl(AclRequestsModel aclReq) { AclRequests aclRequestsDao = new AclRequests(); copyProperties(aclReq, aclRequestsDao); StringBuilder aclStr = new StringBuilder(); - String seperatorAcl = ""; + String separatorAcl = ""; if (aclReq.getAcl_ip() != null) { for (int i = 0; i < aclReq.getAcl_ip().size(); i++) { if (i == 0) { aclStr.append(aclReq.getAcl_ip().get(i)); - } else aclStr = new StringBuilder(aclStr + seperatorAcl + aclReq.getAcl_ip().get(i)); + } else aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ip().get(i)); } aclRequestsDao.setAcl_ip(aclStr.toString()); } @@ -135,7 +134,7 @@ public String createAcl(AclRequestsModel aclReq) { for (int i = 0; i < aclReq.getAcl_ssl().size(); i++) { if (i == 0) { aclStr.append(aclReq.getAcl_ssl().get(i)); - } else aclStr = new StringBuilder(aclStr + seperatorAcl + aclReq.getAcl_ssl().get(i)); + } else aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ssl().get(i)); } aclRequestsDao.setAcl_ssl(aclStr.toString()); } @@ -144,20 +143,24 @@ public String createAcl(AclRequestsModel aclReq) { aclRequestsDao.setAcl_ssl("User:*"); aclRequestsDao.setTenantId(tenantId); - String execRes = - manageDatabase.getHandleDbRequests().requestForAcl(aclRequestsDao).get("result"); + try { + String execRes = + manageDatabase.getHandleDbRequests().requestForAcl(aclRequestsDao).get("result"); - if ("success".equals(execRes)) { - mailService.sendMail( - aclReq.getTopicname(), - aclReq.getTopictype(), - "", - userDetails, - manageDatabase.getHandleDbRequests(), - ACL_REQUESTED, - commonUtilsService.getLoginUrl()); + if ("success".equals(execRes)) { + mailService.sendMail( + aclReq.getTopicname(), + aclReq.getTopictype(), + "", + userDetails, + manageDatabase.getHandleDbRequests(), + ACL_REQUESTED, + commonUtilsService.getLoginUrl()); + } + return ApiResponse.builder().result(execRes).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); } - return "{\"result\":\"" + execRes + "\"}"; } public List getAclRequests( @@ -370,32 +373,32 @@ private List updateCreatAclReqsList( return aclRequestsModels; } - public String deleteAclRequests(String req_no) { + public ApiResponse deleteAclRequests(String req_no) throws KlawException { try { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { - return "{\"result\":\" Not Authorized. \"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } log.info("deleteAclRequests {}", req_no); - return "{\"result\":\"" - + manageDatabase + String result = + manageDatabase .getHandleDbRequests() .deleteAclRequest( - Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())) - + "\"}"; + Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())); + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception ", e); - return "{\"result\":\"failure " + e.toString() + "\"}"; + throw new KlawException(e.getMessage()); } } // this will create a delete subscription request - public String createDeleteAclSubscriptionRequest(String req_no) { + public ApiResponse createDeleteAclSubscriptionRequest(String req_no) throws KlawException { log.info("createDeleteAclSubscriptionRequest {}", req_no); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_SUBSCRIPTIONS)) { - return "{\"result\":\" Not Authorized. \"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -405,7 +408,7 @@ public String createDeleteAclSubscriptionRequest(String req_no) { Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())); if (!getEnvsFromUserId(userDetails).contains(acl.getEnvironment())) - return "{\"result\":\"failure\"}"; + return ApiResponse.builder().result("failure").build(); AclRequests aclReq = new AclRequests(); @@ -429,7 +432,7 @@ public String createDeleteAclSubscriptionRequest(String req_no) { ACL_DELETE_REQUESTED, commonUtilsService.getLoginUrl()); } - return "{\"result\":\"" + execRes + "\"}"; + return ApiResponse.builder().result(execRes).build(); } public ApiResponse approveAclRequests(String req_no) throws KlawException { @@ -438,10 +441,7 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { - return ApiResponse.builder() - .result(ApiResultStatus.NOT_AUTHORIZED.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -450,22 +450,15 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { if (Objects.equals(aclReq.getUsername(), userDetails)) return ApiResponse.builder() .result("You are not allowed to approve your own subscription requests.") - .status(HttpStatus.OK) .build(); if (!RequestStatus.created.name().equals(aclReq.getAclstatus())) { - return ApiResponse.builder() - .result("This request does not exist anymore.") - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) - return ApiResponse.builder() - .result(ApiResultStatus.NOT_AUTHORIZED.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); String allIps = aclReq.getAcl_ip(); String allSsl = aclReq.getAcl_ssl(); @@ -502,17 +495,10 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { } updateAclReqStatus = dbHandle.updateAclRequest(aclReq, userDetails, jsonParams); - } else - return ApiResponse.builder() - .result(ApiResultStatus.FAILURE.value) - .status(HttpStatus.OK) - .build(); + } else return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); } catch (Exception e) { log.error("Exception ", e); - return ApiResponse.builder() - .result(ApiResultStatus.FAILURE.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); } mailService.sendMail( @@ -523,19 +509,20 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { dbHandle, ACL_REQUEST_APPROVED, commonUtilsService.getLoginUrl()); - return ApiResponse.builder().result(updateAclReqStatus).status(HttpStatus.OK).build(); + return ApiResponse.builder().result(updateAclReqStatus).build(); } else { - return ApiResponse.builder().result("Record not found !").status(HttpStatus.OK).build(); + return ApiResponse.builder().result("Record not found !").build(); } } - public String declineAclRequests(String req_no, String reasonToDecline) { + public ApiResponse declineAclRequests(String req_no, String reasonToDecline) + throws KlawException { log.info("declineAclRequests {}", req_no); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { - return "{\"result\":\" Not Authorized. \"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -543,12 +530,12 @@ public String declineAclRequests(String req_no, String reasonToDecline) { dbHandle.selectAcl(Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())); if (!RequestStatus.created.name().equals(aclReq.getAclstatus())) { - return "{\"result\":\"This request does not exist anymore.\"}"; + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); String updateAclReqStatus; @@ -564,11 +551,14 @@ public String declineAclRequests(String req_no, String reasonToDecline) { ACL_REQUEST_DENIED, commonUtilsService.getLoginUrl()); - return "{\"result\":\"" + updateAclReqStatus + "\"}"; + return ApiResponse.builder().result(updateAclReqStatus).build(); } catch (Exception e) { - return "{\"result\":\"failure " + e.toString() + "\"}"; + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); } - } else return "{\"result\":\"Record not found !\"}"; + } else { + return ApiResponse.builder().result("Record not found !").build(); + } } private List getAclsFromSOT( diff --git a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java index 63ae3fcc33..d2fa553dfa 100644 --- a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java @@ -49,15 +49,13 @@ public class AclSyncControllerService { this.mailService = mailService; } - public Map updateSyncAcls(List syncAclUpdates) { + public ApiResponse updateSyncAcls(List syncAclUpdates) throws KlawException { log.info("updateSyncAcls {}", syncAclUpdates); String userDetails = getUserName(); - Map response = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } List listTopics = new ArrayList<>(); @@ -79,8 +77,7 @@ public Map updateSyncAcls(List syncAclUpdates) { // tenant filtering if (!getEnvsFromUserId(userDetails).contains(syncAclUpdateItem.getEnvSelected())) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } t = new Acl(); @@ -101,22 +98,23 @@ public Map updateSyncAcls(List syncAclUpdates) { listTopics.add(t); } } else { - response.put("result", "No record updated."); - return response; + return ApiResponse.builder().result("No record updated.").build(); } try { - if (listTopics.size() > 0) { - response.put("result", manageDatabase.getHandleDbRequests().addToSyncacls(listTopics)); + if (!listTopics.isEmpty()) { + return ApiResponse.builder() + .result(manageDatabase.getHandleDbRequests().addToSyncacls(listTopics)) + .build(); } + return ApiResponse.builder().result("No record updated.").build(); } catch (Exception e) { log.error("Exception:", e); - response.put("result", "Failure." + e); + throw new KlawException(e.getMessage()); } - return response; } - public Map> updateSyncBackAcls(SyncBackAcls syncBackAcls) { + public ApiResponse updateSyncBackAcls(SyncBackAcls syncBackAcls) throws KlawException { log.info("updateSyncBackAcls {}", syncBackAcls); Map> resultMap = new HashMap<>(); @@ -131,38 +129,37 @@ public Map> updateSyncBackAcls(SyncBackAcls syncBackAcls) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { - List notAuth = new ArrayList<>(); - notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); - resultMap.put("result", notAuth); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } List resultStatus = new ArrayList<>(); resultStatus.add("success"); resultMap.put("result", resultStatus); - - if ("SELECTED_ACLS".equals(syncBackAcls.getTypeOfSync())) { - for (String aclId : syncBackAcls.getAclIds()) { - Acl acl = - manageDatabase - .getHandleDbRequests() - .selectSyncAclsFromReqNo(Integer.parseInt(aclId), tenantId); - if (acl != null) { + try { + if ("SELECTED_ACLS".equals(syncBackAcls.getTypeOfSync())) { + for (String aclId : syncBackAcls.getAclIds()) { + Acl acl = + manageDatabase + .getHandleDbRequests() + .selectSyncAclsFromReqNo(Integer.parseInt(aclId), tenantId); + if (acl != null) { + approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); + } + } + } else { + List acls = + manageDatabase.getHandleDbRequests().getSyncAcls(syncBackAcls.getSourceEnv(), tenantId); + for (Acl acl : acls) { approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); } } - } else { - List acls = - manageDatabase.getHandleDbRequests().getSyncAcls(syncBackAcls.getSourceEnv(), tenantId); - for (Acl acl : acls) { - approveSyncBackAcls(syncBackAcls, resultMap, logArray, acl, tenantId); - } + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); } - resultMap.put("syncbacklog", logArray); - - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).data(logArray).build(); } private void approveSyncBackAcls( diff --git a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java index 923f9241a1..3098eb81b6 100644 --- a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java @@ -4,6 +4,7 @@ import io.aiven.klaw.dao.Acl; import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.Topic; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.charts.ChartsJsOverview; import io.aiven.klaw.model.charts.TeamOverview; @@ -95,7 +96,7 @@ public Map getAclsCountPerEnv(String sourceEnvSelected) { .collect(Collectors.toList()); if (aclsPerEnvList.size() == 1) { - resultMap.put("status", "success"); + resultMap.put("status", ApiResultStatus.SUCCESS.value); resultMap.put("aclsCount", aclsPerEnvList.get(0).get("aclscount")); } } catch (Exception e) { diff --git a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 3729fda9e7..6622d35cfb 100644 --- a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -9,6 +9,7 @@ import io.aiven.klaw.dao.KwClusters; import io.aiven.klaw.dao.KwTenants; import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.*; import java.io.*; @@ -696,7 +697,7 @@ public String addNewEnv(EnvModel newEnv) { } } - public Map addNewCluster(KwClustersModel kwClustersModel) { + public ApiResponse addNewCluster(KwClustersModel kwClustersModel) { log.info("addNewCluster {}", kwClustersModel.getClusterName()); Map resultMap = new HashMap<>(); @@ -704,8 +705,7 @@ public Map addNewCluster(KwClustersModel kwClustersModel) { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_CLUSTERS)) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } AtomicBoolean clusterNameAlreadyExists = new AtomicBoolean(false); @@ -721,9 +721,9 @@ public Map addNewCluster(KwClustersModel kwClustersModel) { }); if (clusterNameAlreadyExists.get()) { - resultMap.put( - "result", "Failure. Please choose a different name. This cluster name already exists."); - return resultMap; + return ApiResponse.builder() + .result("Failure. Please choose a different name. This cluster name already exists.") + .build(); } } KwClusters kwCluster = new KwClusters(); @@ -736,17 +736,15 @@ public Map addNewCluster(KwClustersModel kwClustersModel) { && kwCluster.getClusterId() == null && "saas".equals(kwInstallationType)) { if (!savePublicKey(kwClustersModel, resultMap, tenantId, kwCluster)) { - resultMap.put("result", "Failure. Unable to save public key."); - return resultMap; + return ApiResponse.builder().result("Failure. Unable to save public key.").build(); } } String result = manageDatabase.getHandleDbRequests().addNewCluster(kwCluster); - if (result.equals("success")) { + if (result.equals(ApiResultStatus.SUCCESS.value)) { commonUtilsService.updateMetadata(tenantId, EntityType.CLUSTER, MetadataOperationType.CREATE); } - resultMap.put("result", result); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } private boolean savePublicKey( @@ -799,28 +797,31 @@ private boolean createPublicKeyFile(String clusterName, int tenantId, String pub return true; } - public String deleteCluster(String clusterId) { + public ApiResponse deleteCluster(String clusterId) throws KlawException { log.info("deleteCluster {}", clusterId); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_CLUSTERS)) - return "{\"result\":\"Not Authorized\"}"; + getPrincipal(), PermissionType.ADD_EDIT_DELETE_CLUSTERS)) { + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } List allEnvList = manageDatabase.getAllEnvList(tenantId); if (allEnvList.stream() .anyMatch(env -> Objects.equals(env.getClusterId(), Integer.parseInt(clusterId)))) { - return "{\"result\":\"Not allowed to delete this cluster, as there are associated environments.\"}"; + return ApiResponse.builder() + .result("Not allowed to delete this cluster, as there are associated environments.") + .build(); } try { String result = manageDatabase.getHandleDbRequests().deleteCluster(Integer.parseInt(clusterId), tenantId); commonUtilsService.updateMetadata(tenantId, EntityType.CLUSTER, MetadataOperationType.DELETE); - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index 8ac579be92..6a338763e0 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -69,16 +69,14 @@ public class KafkaConnectControllerService { @Autowired private RolesPermissionsControllerService rolesPermissionsControllerService; - public Map createConnectorRequest(KafkaConnectorRequestModel topicRequestReq) { + public ApiResponse createConnectorRequest(KafkaConnectorRequestModel topicRequestReq) + throws KlawException { log.info("createConnectorRequest {}", topicRequestReq); String userDetails = getUserName(); - Map hashMapTopicReqRes = new HashMap<>(); - if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_CONNECTORS)) { - hashMapTopicReqRes.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return hashMapTopicReqRes; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } try { @@ -86,15 +84,17 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top && topicRequestReq.getConnectorConfig().trim().length() > 0) { JsonNode jsonNode = OBJECT_MAPPER.readTree(topicRequestReq.getConnectorConfig().trim()); if (!jsonNode.has("tasks.max")) { - hashMapTopicReqRes.put("result", "Failure. Invalid config. tasks.max is not configured"); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Invalid config. tasks.max is not configured") + .build(); } else if (!jsonNode.has("connector.class")) { - hashMapTopicReqRes.put( - "result", "Failure. Invalid config. connector.class is not configured"); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Invalid config. connector.class is not configured") + .build(); } else if (!jsonNode.has("topic")) { - hashMapTopicReqRes.put("result", "Failure. Invalid config. topic is not configured"); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Invalid config. topic is not configured") + .build(); } Map resultMap = @@ -104,8 +104,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top } } catch (JsonProcessingException e) { log.error("Exception:", e); - hashMapTopicReqRes.put("result", "Failure. Invalid config."); - return hashMapTopicReqRes; + throw new KlawException(e.getMessage()); } topicRequestReq.setRequestor(userDetails); @@ -118,9 +117,9 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top // tenant filtering if (!getEnvsFromUserId(userDetails).contains(envSelected)) { - hashMapTopicReqRes.put( - "result", "Failure. Not authorized to request connector for this environment."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. Not authorized to request connector for this environment.") + .build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -131,7 +130,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top syncCluster = manageDatabase.getTenantConfig().get(tenantId).getBaseSyncKafkaConnectCluster(); } catch (Exception e) { log.error("Tenant Configuration not found. " + tenantId, e); - return new HashMap<>(); + throw new KlawException(e.getMessage()); } String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_KAFKA_CONNECT_ENVS"); @@ -141,8 +140,9 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top if (kafkaConnectorList != null && kafkaConnectorList.size() > 0 && !Objects.equals(kafkaConnectorList.get(0).getTeamId(), topicRequestReq.getTeamId())) { - hashMapTopicReqRes.put("result", "Failure. This connector is owned by a different team."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. This connector is owned by a different team.") + .build(); } boolean promotionOrderCheck = checkInPromotionOrder( @@ -157,26 +157,27 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top .count(); if (devTopicFound != 1) { if (getKafkaConnectEnvDetails(syncCluster) == null) { - hashMapTopicReqRes.put( - "result", "Failure. This connector does not exist in base cluster"); + return ApiResponse.builder() + .result("Failure. This connector does not exist in base cluster") + .build(); } else { - hashMapTopicReqRes.put( - "result", - "Failure. This connector does not exist in " - + getKafkaConnectEnvDetails(syncCluster).getName() - + " cluster."); + return ApiResponse.builder() + .result( + "Failure. This connector does not exist in " + + getKafkaConnectEnvDetails(syncCluster).getName() + + " cluster.") + .build(); } - return hashMapTopicReqRes; } } } else if (!Objects.equals(topicRequestReq.getEnvironment(), syncCluster)) { if (promotionOrderCheck) { - hashMapTopicReqRes.put( - "result", - "Failure. Please request for a connector first in " - + getKafkaConnectEnvDetails(syncCluster).getName() - + " cluster."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result( + "Failure. Please request for a connector first in " + + getKafkaConnectEnvDetails(syncCluster).getName() + + " cluster.") + .build(); } } @@ -190,8 +191,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top tenantId) .size() > 0) { - hashMapTopicReqRes.put("result", "Failure. A connector request already exists."); - return hashMapTopicReqRes; + return ApiResponse.builder().result("Failure. A connector request already exists.").build(); } } @@ -206,9 +206,9 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top Objects.equals(topicEx.getEnvironment(), topicRequestReq.getEnvironment())); } if (topicExists) { - hashMapTopicReqRes.put( - "result", "Failure. This connector already exists in the selected cluster."); - return hashMapTopicReqRes; + return ApiResponse.builder() + .result("Failure. This connector already exists in the selected cluster.") + .build(); } } @@ -216,7 +216,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top copyProperties(topicRequestReq, topicRequestDao); topicRequestDao.setTenantId(tenantId); - hashMapTopicReqRes.put("result", dbHandle.requestForConnector(topicRequestDao).get("result")); + String result = dbHandle.requestForConnector(topicRequestDao).get("result"); mailService.sendMail( topicRequestReq.getConnectorName(), null, @@ -226,7 +226,7 @@ public Map createConnectorRequest(KafkaConnectorRequestModel top CONNECTOR_CREATE_REQUESTED, commonUtilsService.getLoginUrl()); - return hashMapTopicReqRes; + return ApiResponse.builder().result(result).build(); } public List> getConnectors( diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java index c8327e91c6..7ac8757800 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java @@ -9,6 +9,7 @@ import io.aiven.klaw.dao.KwKafkaConnector; import io.aiven.klaw.dao.Team; import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaConnectorModel; @@ -68,14 +69,14 @@ public Map getConnectorDetails(String connectorName, String envI return response; } - public Map updateSyncConnectors(List updatedSyncTopics) { + public ApiResponse updateSyncConnectors(List updatedSyncTopics) + throws KlawException { log.info("updateSyncConnectors {}", updatedSyncTopics); String userDetails = getUserName(); Map response = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_CONNECTORS)) { - response.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } // tenant filtering @@ -103,8 +104,7 @@ public Map updateSyncConnectors(List updat for (SyncConnectorUpdates topicUpdate : updatedSyncTopics) { // tenant filtering if (!getEnvsFromUserId(userDetails).contains(topicUpdate.getEnvSelected())) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } existingTopics = getConnectorsFromName(topicUpdate.getConnectorName(), tenantId); @@ -135,10 +135,9 @@ public Map updateSyncConnectors(List updat topicUpdate.getConnectorName(), topicUpdate.getEnvSelected(), tenantId); } catch (KlawException | JsonProcessingException e) { log.error("Exception:", e); - response.put( - "result", - topicUpdate.getConnectorName() + " Connector config could not be retrieved."); - return response; + return ApiResponse.builder() + .result(topicUpdate.getConnectorName() + " Connector config could not be retrieved.") + .build(); } boolean topicAdded = false; @@ -211,40 +210,44 @@ public Map updateSyncConnectors(List updat } if (updatedSyncTopics.size() == 0 && updatedSyncTopicsDelete.size() > 0) { - response.put("result", "success"); - return response; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } if (topicsDontExistInMainCluster) { - response.put( - "result", - "Failure. Please sync up the team of the following connector(s) first in" - + " main Sync cluster (klaw.syncdata.cluster)" - + " :" - + syncCluster - + ". \n Topics : " - + erroredTopicsExist); - return response; + return ApiResponse.builder() + .result( + "Failure. Please sync up the team of the following connector(s) first in" + + " main Sync cluster (klaw.syncdata.cluster)" + + " :" + + syncCluster + + ". \n Topics : " + + erroredTopicsExist) + .build(); } if (topicsWithDiffTeams) { - response.put( - "result", - "Failure. The following connectors are being synchronized with" - + " a different team, when compared to main Sync cluster (klaw.syncdata.cluster)" - + " :" - + syncCluster - + ". \n Topics : " - + erroredTopics); - return response; + return ApiResponse.builder() + .result( + "Failure. The following connectors are being synchronized with" + + " a different team, when compared to main Sync cluster (klaw.syncdata.cluster)" + + " :" + + syncCluster + + ". \n Topics : " + + erroredTopics) + .build(); } if (kafkaConnectorList.size() > 0) { - response.put( - "result", manageDatabase.getHandleDbRequests().addToSyncConnectors(kafkaConnectorList)); - } else response.put("result", "No record updated."); - - return response; + try { + String result = + manageDatabase.getHandleDbRequests().addToSyncConnectors(kafkaConnectorList); + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } + } else { + return ApiResponse.builder().result("No record updated.").build(); + } } private String getConnectorConfiguration(String connectorName, String environmentId, int tenantId) diff --git a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java index f8a59ec8c3..19e93b6293 100644 --- a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java @@ -2,6 +2,8 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.KwRolesPermissions; +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwRolesPermissionsModel; import io.aiven.klaw.model.PermissionType; @@ -101,12 +103,10 @@ public Map getPermissionDescriptions() { return hMap; } - public Map updatePermissions(KwRolesPermissionsModel[] permissionsSet) { - Map updatedPermsMapStatus = new HashMap<>(); - + public ApiResponse updatePermissions(KwRolesPermissionsModel[] permissionsSet) + throws KlawException { if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { - updatedPermsMapStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return updatedPermsMapStatus; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } Map uniqueMap = new HashMap<>(); @@ -124,58 +124,60 @@ public Map updatePermissions(KwRolesPermissionsModel[] permissio int indexOfDelimiter; String isPermEnabled; - for (String permKey : uniqueMap.keySet()) { - isPermEnabled = uniqueMap.get(permKey); - indexOfDelimiter = permKey.indexOf(delimiter); + try { + for (String permKey : uniqueMap.keySet()) { + isPermEnabled = uniqueMap.get(permKey); + indexOfDelimiter = permKey.indexOf(delimiter); - tmpKwRolePermModel = new KwRolesPermissions(); - tmpKwRolePermModel.setRoleId(permKey.substring(0, indexOfDelimiter)); - tmpKwRolePermModel.setPermission(permKey.substring(indexOfDelimiter + 5)); + tmpKwRolePermModel = new KwRolesPermissions(); + tmpKwRolePermModel.setRoleId(permKey.substring(0, indexOfDelimiter)); + tmpKwRolePermModel.setPermission(permKey.substring(indexOfDelimiter + 5)); - if ("true".equals(isPermEnabled)) kwRolesPermissionsAdd.add(tmpKwRolePermModel); - else if ("false".equals(isPermEnabled)) kwRolesPermissionsDelete.add(tmpKwRolePermModel); - } - - if (kwRolesPermissionsAdd.size() > 0) - manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsAdd, "ADD"); - if (kwRolesPermissionsDelete.size() > 0) - manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsDelete, "DELETE"); + if ("true".equals(isPermEnabled)) kwRolesPermissionsAdd.add(tmpKwRolePermModel); + else if ("false".equals(isPermEnabled)) kwRolesPermissionsDelete.add(tmpKwRolePermModel); + } - if (kwRolesPermissionsAdd.size() > 0 || kwRolesPermissionsDelete.size() > 0) - manageDatabase.loadRolesForAllTenants(); + if (kwRolesPermissionsAdd.size() > 0) + manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsAdd, "ADD"); + if (kwRolesPermissionsDelete.size() > 0) + manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsDelete, "DELETE"); - updatedPermsMapStatus.put("result", "success"); - return updatedPermsMapStatus; + if (kwRolesPermissionsAdd.size() > 0 || kwRolesPermissionsDelete.size() > 0) + manageDatabase.loadRolesForAllTenants(); + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } - public Map deleteRole(String roleId) { - Map deleteRoleStatus = new HashMap<>(); + public ApiResponse deleteRole(String roleId) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { - deleteRoleStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return deleteRoleStatus; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } if (KwConstants.USER_ROLE.equals(roleId) || KwConstants.SUPERADMIN_ROLE.equals(roleId)) { - deleteRoleStatus.put("result", "Not Allowed"); - return deleteRoleStatus; + return ApiResponse.builder().result("Not Allowed").build(); } - String status = - manageDatabase - .getHandleDbRequests() - .deleteRole(roleId, commonUtilsService.getTenantId(getUserName())); - deleteRoleStatus.put("result", status); - manageDatabase.loadRolesForAllTenants(); - return deleteRoleStatus; + try { + String status = + manageDatabase + .getHandleDbRequests() + .deleteRole(roleId, commonUtilsService.getTenantId(getUserName())); + manageDatabase.loadRolesForAllTenants(); + return ApiResponse.builder().result(status).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } - public Map addRoleId(String roleId) { - Map addRoleStatus = new HashMap<>(); + public ApiResponse addRoleId(String roleId) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { - addRoleStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return addRoleStatus; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } List kwRolesPermissionsAdd = new ArrayList<>(); @@ -186,11 +188,15 @@ public Map addRoleId(String roleId) { kwRolesPermissionsAdd.add(tmpKwRolePermModel); - String status = - manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsAdd, "ADD"); - addRoleStatus.put("result", status); - manageDatabase.loadRolesForAllTenants(); - return addRoleStatus; + try { + String status = + manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsAdd, "ADD"); + manageDatabase.loadRolesForAllTenants(); + return ApiResponse.builder().result(status).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } private Object getPrincipal() { diff --git a/src/main/java/io/aiven/klaw/service/UtilControllerService.java b/src/main/java/io/aiven/klaw/service/UtilControllerService.java index 9f2dccca93..281bb4aef3 100644 --- a/src/main/java/io/aiven/klaw/service/UtilControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UtilControllerService.java @@ -4,7 +4,9 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.*; +import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwMetadataUpdates; import io.aiven.klaw.model.PermissionType; @@ -24,6 +26,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; @@ -33,6 +37,9 @@ @Slf4j public class UtilControllerService { + public static final String ERROR_MSG = + "Unable to process the request. Please contact our Administrator !!"; + @Autowired ManageDatabase manageDatabase; @Autowired MailUtils mailService; @@ -564,4 +571,10 @@ public void resetCache(String tenantName, String entityType, String operationTyp log.error("Error from resetCache ", e); } } + + public static ResponseEntity handleException(KlawException e) { + log.error(e.getMessage()); + return new ResponseEntity<>( + ApiResponse.builder().message(ERROR_MSG).build(), HttpStatus.INTERNAL_SERVER_ERROR); + } } diff --git a/src/main/resources/static/js/syncBackAcls.js b/src/main/resources/static/js/syncBackAcls.js index 5ed9461867..49ea11adff 100644 --- a/src/main/resources/static/js/syncBackAcls.js +++ b/src/main/resources/static/js/syncBackAcls.js @@ -293,7 +293,7 @@ app.controller("syncBackAclsCtrl", function($scope, $http, $location, $window) { $scope.alert = "Sync back acls request : "+ output.result[0]; if(output.result[0] == "success"){ $scope.resetCheckBoxes(); - $scope.syncbacklog = output.syncbacklog; + $scope.syncbacklog = output.data; $scope.alert = $scope.alert + ". Please verify logs."; swal({ diff --git a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java index 5c96533ab2..dd1f1d8507 100644 --- a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java @@ -16,9 +16,7 @@ import io.aiven.klaw.model.TopicOverview; import io.aiven.klaw.service.AclControllerService; import io.aiven.klaw.service.AclSyncControllerService; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.mock.mockito.MockBean; @@ -68,7 +66,8 @@ public void setup() { public void createAcl() throws Exception { AclRequestsModel addAclRequest = utilMethods.getAclRequestModel(topicName + topicId); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(addAclRequest); - when(aclControllerService.createAcl(any())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(aclControllerService.createAcl(any())).thenReturn(apiResponse); String response = mvcAcls @@ -81,8 +80,9 @@ public void createAcl() throws Exception { .andReturn() .getResponse() .getContentAsString(); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(response).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test @@ -90,9 +90,9 @@ public void updateSyncAcls() throws Exception { List syncUpdates = utilMethods.getSyncAclsUpdates(); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(syncUpdates); - Map result = new HashMap<>(); - result.put("result", "success"); - when(aclSyncControllerService.updateSyncAcls(any())).thenReturn(result); + + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(aclSyncControllerService.updateSyncAcls(any())).thenReturn(apiResponse); String response = mvcAclsSync @@ -106,10 +106,9 @@ public void updateSyncAcls() throws Exception { .getResponse() .getContentAsString(); - Map actualResult = - new ObjectMapper().readValue(response, new TypeReference<>() {}); + ApiResponse actualResult = new ObjectMapper().readValue(response, new TypeReference<>() {}); - assertThat(actualResult).containsEntry("result", "success"); + assertThat(actualResult.getResult()).isEqualTo("success"); } @Test @@ -160,8 +159,8 @@ public void getCreatedAclRequests() throws Exception { @Test public void deleteAclRequests() throws Exception { - when(aclControllerService.deleteAclRequests(anyString())).thenReturn("success"); - + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(aclControllerService.deleteAclRequests(anyString())).thenReturn(apiResponse); String response = mvcAcls .perform( @@ -173,8 +172,8 @@ public void deleteAclRequests() throws Exception { .andReturn() .getResponse() .getContentAsString(); - - assertThat(response).isEqualTo("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test @@ -199,8 +198,8 @@ public void approveAclRequests() throws Exception { @Test public void declineAclRequests() throws Exception { - when(aclControllerService.declineAclRequests(anyString(), anyString())).thenReturn("success"); - + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(aclControllerService.declineAclRequests(anyString(), anyString())).thenReturn(apiResponse); String response = mvcAcls .perform( @@ -213,8 +212,9 @@ public void declineAclRequests() throws Exception { .andReturn() .getResponse() .getContentAsString(); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(response).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index ed409fa5ab..39fc2df4c1 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -23,6 +23,7 @@ import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SyncAclUpdates; import java.sql.Timestamp; import java.util.ArrayList; @@ -110,59 +111,60 @@ private void loginMock() { @Test @Order(1) - public void createAcl() { + public void createAcl() throws KlawException { AclRequests aclRequestsDao = new AclRequests(); AclRequestsModel aclRequests = getAclRequest(); copyProperties(aclRequests, aclRequestsDao); List topicList = utilMethods.getTopics(); - Map hashMap = new HashMap<>(); hashMap.put("result", "success"); when(handleDbRequests.getTopics(anyString(), anyInt())).thenReturn(topicList); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); stubUserInfo(); - String result = aclControllerService.createAcl(aclRequests); - assertThat(result).isEqualTo("{\"result\":\"success\"}"); + ApiResponse resultResp = aclControllerService.createAcl(aclRequests); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @Order(2) - public void updateSyncAcls() { + public void updateSyncAcls() throws KlawException { stubUserInfo(); when(handleDbRequests.addToSyncacls(anyList())).thenReturn("success"); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = + ApiResponse resultResp = aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); - assertThat(result).containsEntry("result", "success"); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @Order(3) - public void updateSyncAclsFailure1() { + public void updateSyncAclsFailure1() throws KlawException { stubUserInfo(); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - Map result = + ApiResponse resultResp = aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); - assertThat(result).containsEntry("result", "Not Authorized."); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); } @Test @Order(4) - public void updateSyncAclsFailure2() { + public void updateSyncAclsFailure2() throws KlawException { stubUserInfo(); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(handleDbRequests.addToSyncacls(anyList())).thenThrow(new RuntimeException("Error")); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = - aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); - assertThat(result.get("result")).contains("Failure"); + try { + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + } catch (KlawException e) { + assertThat(e.getMessage()).isEqualTo("Error"); + } } private void stubUserInfo() { @@ -173,28 +175,30 @@ private void stubUserInfo() { @Test @Order(5) - public void updateSyncAclsFailure3() { + public void updateSyncAclsFailure3() throws KlawException { List updates = new ArrayList<>(); stubUserInfo(); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = aclSyncControllerService.updateSyncAcls(updates); - assertThat(result).containsEntry("result", "No record updated."); + ApiResponse resultResp = aclSyncControllerService.updateSyncAcls(updates); + assertThat(resultResp.getResult()).isEqualTo("No record updated."); } @Test @Order(6) - public void updateSyncAclsFailure4() { + public void updateSyncAclsFailure4() throws KlawException { when(handleDbRequests.addToSyncacls(anyList())).thenThrow(new RuntimeException("Error")); stubUserInfo(); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = - aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); - assertThat(result.get("result")).contains("Failure"); + try { + aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); + } catch (KlawException e) { + assertThat(e.getMessage()).isEqualTo("Error"); + } } @Test @@ -226,19 +230,19 @@ public void getCreatedAclRequests() { @Test @Order(9) - public void deleteAclRequests() { + public void deleteAclRequests() throws KlawException { String req_no = "1001"; when(handleDbRequests.deleteAclRequest(Integer.parseInt(req_no), 1)).thenReturn("success"); - String result = aclControllerService.deleteAclRequests(req_no); + ApiResponse result = aclControllerService.deleteAclRequests(req_no); // assertThat(result).isEqualTo("{\"result\":\"null\"}"); } @Test @Order(10) - public void deleteAclRequestsFailure() { + public void deleteAclRequestsFailure() throws KlawException { String req_no = "1001"; when(handleDbRequests.deleteAclRequest(Integer.parseInt(req_no), 1)).thenReturn("failure"); - String result = aclControllerService.deleteAclRequests(req_no); + ApiResponse result = aclControllerService.deleteAclRequests(req_no); // assertThat(result).isEqualTo("{\"result\":\"null\"}"); } @@ -329,8 +333,8 @@ public void declineAclRequests() throws KlawException { .thenReturn(Collections.singletonList("1")); when(handleDbRequests.declineAclRequest(any(), any())).thenReturn("success"); - String result = aclControllerService.declineAclRequests(req_no, ""); - assertThat(result).isEqualTo("{\"result\":\"success\"}"); + ApiResponse resultResp = aclControllerService.declineAclRequests(req_no, ""); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @@ -344,7 +348,8 @@ public void declineAclRequestsFailure() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - String result = aclControllerService.declineAclRequests(req_no, "Reason"); + ApiResponse result = aclControllerService.declineAclRequests(req_no, "Reason"); + // assertThat(result).isEqualTo("{\"result\":\"null\"}"); } From a42d5b5bb783e8d5622c66a6e8a5c2903c314e26 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Tue, 4 Oct 2022 22:58:27 +0200 Subject: [PATCH 08/15] Updating response with ApiResponse for a few apis --- .../controller/SchemaRegstryController.java | 49 ++-- .../controller/ServerConfigController.java | 14 +- .../klaw/controller/TopicController.java | 80 ++++--- .../SchemaRegstryControllerService.java | 68 +++--- .../klaw/service/ServerConfigService.java | 54 +++-- .../klaw/service/TopicControllerService.java | 225 ++++++++---------- src/main/resources/static/js/serverConfig.js | 4 +- .../SchemaRegstryControllerTest.java | 7 +- .../klaw/controller/TopicControllerTest.java | 12 +- ... SchemaRegistryControllerServiceTest.java} | 33 ++- .../service/TopicControllerServiceTest.java | 10 +- 11 files changed, 286 insertions(+), 270 deletions(-) rename src/test/java/io/aiven/klaw/service/{SchemaRegstryControllerServiceTest.java => SchemaRegistryControllerServiceTest.java} (91%) diff --git a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java index bd20610aff..a05e015d59 100644 --- a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java +++ b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java @@ -1,5 +1,7 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SchemaRequestModel; @@ -49,14 +51,14 @@ public ResponseEntity> getCreatedSchemaRequests( @PostMapping( value = "/deleteSchemaRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteSchemaRequests( + public ResponseEntity deleteSchemaRequests( @RequestParam("req_no") String avroSchemaReqId) { - - String deleteTopicReqStatus = - schemaRegstryControllerService.deleteSchemaRequests(avroSchemaReqId); - - deleteTopicReqStatus = "{\"result\":\"" + deleteTopicReqStatus + "\"}"; - return new ResponseEntity<>(deleteTopicReqStatus, HttpStatus.OK); + try { + return new ResponseEntity<>( + schemaRegstryControllerService.deleteSchemaRequests(avroSchemaReqId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping( @@ -68,34 +70,35 @@ public ResponseEntity execSchemaRequests( return new ResponseEntity<>( schemaRegstryControllerService.execSchemaRequests(avroSchemaReqId), HttpStatus.OK); } catch (KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder().message("Unable to register schema").build(), - HttpStatus.INTERNAL_SERVER_ERROR); + return handleException(e); } } @PostMapping( value = "/execSchemaRequestsDecline", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity execSchemaRequestsDecline( + public ResponseEntity execSchemaRequestsDecline( @RequestParam("avroSchemaReqId") String avroSchemaReqId, @RequestParam("reasonForDecline") String reasonForDecline) { - String updateTopicReqStatus = - "{\"result\":\"" - + schemaRegstryControllerService.execSchemaRequestsDecline( - avroSchemaReqId, reasonForDecline) - + "\"}"; - return new ResponseEntity<>(updateTopicReqStatus, HttpStatus.OK); + + try { + return new ResponseEntity<>( + schemaRegstryControllerService.execSchemaRequestsDecline( + avroSchemaReqId, reasonForDecline), + HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/uploadSchema") public ResponseEntity uploadSchema( @Valid @RequestBody SchemaRequestModel addSchemaRequest) { - return new ResponseEntity<>( - ApiResponse.builder() - .result(schemaRegstryControllerService.uploadSchema(addSchemaRequest)) - .build(), - HttpStatus.OK); + try { + return new ResponseEntity<>( + schemaRegstryControllerService.uploadSchema(addSchemaRequest), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } } diff --git a/src/main/java/io/aiven/klaw/controller/ServerConfigController.java b/src/main/java/io/aiven/klaw/controller/ServerConfigController.java index f769ded1d9..56918b458e 100644 --- a/src/main/java/io/aiven/klaw/controller/ServerConfigController.java +++ b/src/main/java/io/aiven/klaw/controller/ServerConfigController.java @@ -1,5 +1,9 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KwPropertiesModel; import io.aiven.klaw.model.ServerConfigProperties; import io.aiven.klaw.service.ServerConfigService; @@ -47,10 +51,14 @@ public ResponseEntity> resetCache() { } @PostMapping(value = "/updateKwCustomProperty") - public ResponseEntity> updateKwCustomProperty( + public ResponseEntity updateKwCustomProperty( @RequestBody KwPropertiesModel kwPropertiesModel) { - return new ResponseEntity<>( - serverConfigService.updateKwCustomProperty(kwPropertiesModel), HttpStatus.OK); + try { + return new ResponseEntity<>( + serverConfigService.updateKwCustomProperty(kwPropertiesModel), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/controller/TopicController.java b/src/main/java/io/aiven/klaw/controller/TopicController.java index 3858691606..30edf6a4b0 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicController.java @@ -1,5 +1,7 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.TopicInfo; @@ -34,29 +36,34 @@ public ResponseEntity createTopicsRequest( return new ResponseEntity<>( topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); } catch (KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder().message("Unable to create a topic request").build(), - HttpStatus.INTERNAL_SERVER_ERROR); + return handleException(e); } } @PostMapping( value = "/createTopicDeleteRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> createTopicDeleteRequest( + public ResponseEntity createTopicDeleteRequest( @RequestParam("topicName") String topicName, @RequestParam("env") String envId) { - return new ResponseEntity<>( - topicControllerService.createTopicDeleteRequest(topicName, envId), HttpStatus.OK); + try { + return new ResponseEntity<>( + topicControllerService.createTopicDeleteRequest(topicName, envId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping( value = "/createClaimTopicRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> createClaimTopicRequest( + public ResponseEntity createClaimTopicRequest( @RequestParam("topicName") String topicName, @RequestParam("env") String envId) { - return new ResponseEntity<>( - topicControllerService.createClaimTopicRequest(topicName, envId), HttpStatus.OK); + try { + return new ResponseEntity<>( + topicControllerService.createClaimTopicRequest(topicName, envId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -104,8 +111,13 @@ public ResponseEntity> getCreatedTopicRequests( value = "/deleteTopicRequests", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteTopicRequests(@RequestParam("topicId") String topicId) { - return new ResponseEntity<>(topicControllerService.deleteTopicRequests(topicId), HttpStatus.OK); + public ResponseEntity deleteTopicRequests(@RequestParam("topicId") String topicId) { + try { + return new ResponseEntity<>( + topicControllerService.deleteTopicRequests(topicId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping( @@ -116,26 +128,22 @@ public ResponseEntity approveTopicRequests(@RequestParam("topicId") return new ResponseEntity<>( topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); } catch (KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder() - .message("Unable to approve topics") - .status(HttpStatus.INTERNAL_SERVER_ERROR) - .build(), - HttpStatus.INTERNAL_SERVER_ERROR); + return handleException(e); } } @PostMapping( value = "/execTopicRequestsDecline", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity declineTopicRequests( + public ResponseEntity declineTopicRequests( @RequestParam("topicId") String topicId, - @RequestParam("reasonForDecline") String reasonForDecline) - throws KlawException { - - return new ResponseEntity<>( - topicControllerService.declineTopicRequests(topicId, reasonForDecline), HttpStatus.OK); + @RequestParam("reasonForDecline") String reasonForDecline) { + try { + return new ResponseEntity<>( + topicControllerService.declineTopicRequests(topicId, reasonForDecline), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -148,8 +156,7 @@ public ResponseEntity>> getTopics( @RequestParam(value = "currentPage", defaultValue = "") String currentPage, @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, @RequestParam(value = "teamName", required = false) String teamName, - @RequestParam(value = "topicType", required = false) String topicType) - throws Exception { + @RequestParam(value = "topicType", required = false) String topicType) { return new ResponseEntity<>( topicControllerService.getTopics( @@ -162,8 +169,7 @@ public ResponseEntity>> getTopics( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity> getTopicsOnly( - @RequestParam(value = "isMyTeamTopics", defaultValue = "false") String isMyTeamTopics) - throws Exception { + @RequestParam(value = "isMyTeamTopics", defaultValue = "false") String isMyTeamTopics) { return new ResponseEntity<>( topicControllerService.getAllTopics(Boolean.parseBoolean(isMyTeamTopics)), HttpStatus.OK); } @@ -173,19 +179,19 @@ public ResponseEntity> getTopicsOnly( method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity> getTopicDetailsPerEnv( - @RequestParam("envSelected") String envId, @RequestParam("topicname") String topicName) - throws Exception { - + @RequestParam("envSelected") String envId, @RequestParam("topicname") String topicName) { return new ResponseEntity<>( topicControllerService.getTopicDetailsPerEnv(envId, topicName), HttpStatus.OK); } @PostMapping(value = "/saveTopicDocumentation") - public ResponseEntity> saveTopicDocumentation( - @RequestBody TopicInfo topicInfo) { - Map saveTopicDocumentationResult = - topicControllerService.saveTopicDocumentation(topicInfo); - return new ResponseEntity<>(saveTopicDocumentationResult, HttpStatus.OK); + public ResponseEntity saveTopicDocumentation(@RequestBody TopicInfo topicInfo) { + try { + return new ResponseEntity<>( + topicControllerService.saveTopicDocumentation(topicInfo), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } // getTopic Events from kafka cluster diff --git a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java index a6026f5917..ca0ace725b 100644 --- a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java +++ b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java @@ -168,22 +168,24 @@ private List getSchemaRequestsPaged( return newList; } - public String deleteSchemaRequests(String avroSchemaId) { + public ApiResponse deleteSchemaRequests(String avroSchemaId) throws KlawException { log.info("deleteSchemaRequests {}", avroSchemaId); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_SCHEMAS)) { - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } try { - return manageDatabase - .getHandleDbRequests() - .deleteSchemaRequest( - Integer.parseInt(avroSchemaId), commonUtilsService.getTenantId(getUserName())); + String result = + manageDatabase + .getHandleDbRequests() + .deleteSchemaRequest( + Integer.parseInt(avroSchemaId), commonUtilsService.getTenantId(getUserName())); + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.toString() + "\"}"; + throw new KlawException(e.getMessage()); } } @@ -239,11 +241,12 @@ public ApiResponse execSchemaRequests(String avroSchemaId) throws KlawException } } - public String execSchemaRequestsDecline(String avroSchemaId, String reasonForDecline) { + public ApiResponse execSchemaRequestsDecline(String avroSchemaId, String reasonForDecline) + throws KlawException { log.info("execSchemaRequestsDecline {}", avroSchemaId); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } int tenantId = commonUtilsService.getTenantId(getUserName()); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -252,19 +255,22 @@ public String execSchemaRequestsDecline(String avroSchemaId, String reasonForDec List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; - - String responseDb = dbHandle.updateSchemaRequestDecline(schemaRequest, userDetails); - mailService.sendMail( - schemaRequest.getTopicname(), - null, - reasonForDecline, - schemaRequest.getUsername(), - dbHandle, - SCHEMA_REQUEST_DENIED, - commonUtilsService.getLoginUrl()); - - return responseDb; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + + try { + String responseDb = dbHandle.updateSchemaRequestDecline(schemaRequest, userDetails); + mailService.sendMail( + schemaRequest.getTopicname(), + null, + reasonForDecline, + schemaRequest.getUsername(), + dbHandle, + SCHEMA_REQUEST_DENIED, + commonUtilsService.getLoginUrl()); + return ApiResponse.builder().result(responseDb).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } private List getFilteredTopicsForTenant(List topicsFromSOT) { @@ -283,20 +289,20 @@ private List getFilteredTopicsForTenant(List topicsFromSOT) { return topicsFromSOT; } - public String uploadSchema(SchemaRequestModel schemaRequest) { + public ApiResponse uploadSchema(SchemaRequestModel schemaRequest) throws KlawException { log.info("uploadSchema {}", schemaRequest); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { - return ApiResultStatus.NOT_AUTHORIZED.value; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } try { new ObjectMapper().readValue(schemaRequest.getSchemafull(), Object.class); } catch (IOException e) { log.error("Exception:", e); - return "Failure. Invalid json"; + return ApiResponse.builder().result("Failure. Invalid json").build(); } Integer userTeamId = getMyTeamId(userDetails); @@ -308,7 +314,9 @@ public String uploadSchema(SchemaRequestModel schemaRequest) { Integer topicOwnerTeam = getFilteredTopicsForTenant(topicsSearchList).get(0).getTeamId(); if (!Objects.equals(userTeamId, topicOwnerTeam)) { - return "No topic selected Or Not authorized to register schema for this topic."; + return ApiResponse.builder() + .result("No topic selected Or Not authorized to register schema for this topic.") + .build(); } List schemaReqs = @@ -333,7 +341,9 @@ public String uploadSchema(SchemaRequestModel schemaRequest) { schemaRequest1.getTopicname(), schemaRequest.getTopicname())) .collect(Collectors.toList()); if (schemaReqs.size() > 0) { - return "Failure. A request already exists for this topic."; + return ApiResponse.builder() + .result("Failure. A request already exists for this topic.") + .build(); } } @@ -354,10 +364,10 @@ public String uploadSchema(SchemaRequestModel schemaRequest) { SCHEMA_REQUESTED, commonUtilsService.getLoginUrl()); - return responseDb; + return ApiResponse.builder().result(responseDb).build(); } catch (Exception e) { log.error("Exception:", e); - return "failure " + e; + throw new KlawException(e.getMessage()); } } diff --git a/src/main/java/io/aiven/klaw/service/ServerConfigService.java b/src/main/java/io/aiven/klaw/service/ServerConfigService.java index 5fa88a9e63..cd2b08e226 100644 --- a/src/main/java/io/aiven/klaw/service/ServerConfigService.java +++ b/src/main/java/io/aiven/klaw/service/ServerConfigService.java @@ -7,6 +7,7 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.KwProperties; +import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.*; import java.io.IOException; import java.util.ArrayList; @@ -150,25 +151,23 @@ public List> getAllEditableProps() { else return listMap; } - public Map updateKwCustomProperty(KwPropertiesModel kwPropertiesModel) { + public ApiResponse updateKwCustomProperty(KwPropertiesModel kwPropertiesModel) + throws KlawException { log.info("updateKwCustomProperty {}", kwPropertiesModel); - Map response = new HashMap<>(); + // Map response = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); String kwKey = kwPropertiesModel.getKwKey(); String kwVal = kwPropertiesModel.getKwValue().trim(); - response.put("resultkey", kwKey); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } // SUPERADMINS filter if (tenantId != KwConstants.DEFAULT_TENANT_ID) { if (!KwConstants.allowConfigForAdmins.contains(kwKey)) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } } @@ -181,32 +180,39 @@ public Map updateKwCustomProperty(KwPropertiesModel kwProperties updateEnvIdValues(dynamicObj); kwPropertiesModel.setKwValue(OBJECT_MAPPER.writeValueAsString(dynamicObj)); } else { - response.put( - "result", - "Failure. Invalid json / incorrect name values. Check tenant and env details."); - return response; + return ApiResponse.builder() + .result( + "Failure. Invalid json / incorrect name values. Check tenant and env details.") + .build(); } } catch (IOException e) { log.error("Exception:", e); - response.put( - "result", "Failure. Invalid json values. Please check if tenant/environments exist."); - return response; + return ApiResponse.builder() + .result("Failure. Invalid json values. Please check if tenant/environments exist.") + .build(); } } } catch (Exception e) { log.error("Exception:", e); - response.put("result", "Failure. Please check if the environment names exist."); - return response; + return ApiResponse.builder() + .result("Failure. Please check if the environment names exist.") + .build(); } - KwProperties kwProperties = new KwProperties(); - copyProperties(kwPropertiesModel, kwProperties); - String res = manageDatabase.getHandleDbRequests().updateKwProperty(kwProperties, tenantId); - if ("success".equals(res)) - commonUtilsService.updateMetadata( - tenantId, EntityType.PROPERTIES, MetadataOperationType.CREATE); - response.put("result", "success"); - return response; + try { + KwProperties kwProperties = new KwProperties(); + copyProperties(kwPropertiesModel, kwProperties); + String res = manageDatabase.getHandleDbRequests().updateKwProperty(kwProperties, tenantId); + if (ApiResultStatus.SUCCESS.value.equals(res)) { + commonUtilsService.updateMetadata( + tenantId, EntityType.PROPERTIES, MetadataOperationType.CREATE); + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).data(kwKey).build(); + } else { + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } private void updateEnvNameValues(TenantConfig dynamicObj, int tenantId) { diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index ca63571fbc..90916d2fbb 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -43,7 +43,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.EnumUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -74,14 +73,9 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws log.info("createTopicsRequest {}", topicRequestReq); String userDetails = getUserName(); - // Map hashMapTopicReqRes = new HashMap<>(); - if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_TOPICS)) { - return ApiResponse.builder() - .result(ApiResultStatus.NOT_AUTHORIZED.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } topicRequestReq.setRequestor(userDetails); @@ -96,7 +90,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws if (!getEnvsFromUserId(userDetails).contains(envSelected)) { return ApiResponse.builder() .result("Failure. Not authorized to request topic for this environment.") - .status(HttpStatus.OK) .build(); } @@ -110,16 +103,12 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws log.error("Tenant Configuration not found. " + tenantId, e); return ApiResponse.builder() .result("Failure. Tenant configuration in Server config is missing. Please configure.") - .status(HttpStatus.OK) .build(); } String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_ENVS"); if (topicRequestReq.getTopicname() == null || topicRequestReq.getTopicname().length() == 0) { - return ApiResponse.builder() - .result("Failure. Please fill in topic name.") - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result("Failure. Please fill in topic name.").build(); } List topics = getTopicFromName(topicRequestReq.getTopicname(), tenantId); @@ -128,7 +117,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws && !Objects.equals(topics.get(0).getTeamId(), topicRequestReq.getTeamId())) { return ApiResponse.builder() .result("Failure. This topic is owned by a different team.") - .status(HttpStatus.OK) .build(); } boolean promotionOrderCheck = @@ -146,7 +134,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws if (getEnvDetails(syncCluster) == null) { return ApiResponse.builder() .result("Failure. This topic does not exist in base cluster.") - .status(HttpStatus.OK) .build(); } else { return ApiResponse.builder() @@ -154,7 +141,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws "Failure. This topic does not exist in " + getEnvDetails(syncCluster).getName() + " cluster.") - .status(HttpStatus.OK) .build(); } } @@ -166,7 +152,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws "Failure. Please request for a topic first in " + getEnvDetails(syncCluster).getName() + " cluster.") - .status(HttpStatus.OK) .build(); } } @@ -181,10 +166,7 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws tenantId) .size() > 0) { - return ApiResponse.builder() - .result("Failure. A topic request already exists.") - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result("Failure. A topic request already exists.").build(); } } @@ -201,7 +183,6 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws if (topicExists) { return ApiResponse.builder() .result("Failure. This topic already exists in the selected cluster.") - .status(HttpStatus.OK) .build(); } } @@ -226,13 +207,9 @@ public ApiResponse createTopicsRequest(TopicRequestModel topicRequestReq) throws commonUtilsService.getLoginUrl()); return ApiResponse.builder() .result(dbHandle.requestForTopic(topicRequestDao).get("result")) - .status(HttpStatus.OK) .build(); } else { - return ApiResponse.builder() - .result(isValidTopicMap.get("error")) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(isValidTopicMap.get("error")).build(); } } @@ -292,15 +269,13 @@ private Map validateParameters( } // create a request to delete topic. - public Map createTopicDeleteRequest(String topicName, String envId) { + public ApiResponse createTopicDeleteRequest(String topicName, String envId) throws KlawException { log.info("createTopicDeleteRequest {} {}", topicName, envId); String userDetails = getUserName(); - Map hashMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_TOPICS)) { - hashMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return hashMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -313,10 +288,9 @@ public Map createTopicDeleteRequest(String topicName, String env if (topics != null && topics.size() > 0 && !Objects.equals(topics.get(0).getTeamId(), userTeamId)) { - hashMap.put( - "result", - "Failure. Sorry, you cannot delete this topic, as you are not part of this team."); - return hashMap; + return ApiResponse.builder() + .result("Failure. Sorry, you cannot delete this topic, as you are not part of this team.") + .build(); } topicRequestReq.setRequestor(userDetails); @@ -342,54 +316,55 @@ public Map createTopicDeleteRequest(String topicName, String env tenantId) .size() > 0) { - hashMap.put("result", "Failure. A delete topic request already exists."); - return hashMap; + return ApiResponse.builder() + .result("Failure. A delete topic request already exists.") + .build(); } if (topicOb.isPresent()) { - // Check if any existing subscriptions for this topic - List acls = manageDatabase .getHandleDbRequests() .getSyncAcls( topicRequestReq.getEnvironment(), topicRequestReq.getTopicname(), tenantId); if (acls.size() > 0) { - hashMap.put( - "result", - "Failure. There are existing subscriptions for topic. Please get them deleted before."); - return hashMap; + return ApiResponse.builder() + .result( + "Failure. There are existing subscriptions for topic. Please get them deleted before.") + .build(); } topicRequestReq.setTopicpartitions(topicOb.get().getNoOfPartitions()); topicRequestReq.setReplicationfactor(topicOb.get().getNoOfReplcias()); - mailService.sendMail( - topicRequestReq.getTopicname(), - null, - "", - userDetails, - dbHandle, - TOPIC_DELETE_REQUESTED, - commonUtilsService.getLoginUrl()); - hashMap.put( - "result", - manageDatabase.getHandleDbRequests().requestForTopic(topicRequestReq).get("result")); + try { + mailService.sendMail( + topicRequestReq.getTopicname(), + null, + "", + userDetails, + dbHandle, + TOPIC_DELETE_REQUESTED, + commonUtilsService.getLoginUrl()); + + String result = + manageDatabase.getHandleDbRequests().requestForTopic(topicRequestReq).get("result"); + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } else { log.error("Topic not found : {}", topicName); - hashMap.put("result", "failure"); + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); } - - return hashMap; } - public Map createClaimTopicRequest(String topicName, String env) { + public ApiResponse createClaimTopicRequest(String topicName, String env) throws KlawException { log.info("createClaimTopicRequest {}", topicName); String userDetails = getUserName(); - Map resultMap = new HashMap<>(); - HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); TopicRequest topicRequestReq = new TopicRequest(); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -403,26 +378,24 @@ public Map createClaimTopicRequest(String topicName, String env) tenantId) .size() > 0) { - resultMap.put("result", "Failure. A request already exists for this topic."); - return resultMap; + return ApiResponse.builder() + .result("Failure. A request already exists for this topic.") + .build(); } List topics = getTopicFromName(topicName, tenantId); - // String topicOwnerTeam = topics.get(0).getTeamname(); Integer topicOwnerTeamId = topics.get(0).getTeamId(); Optional topicOwnerContact = manageDatabase.getHandleDbRequests().selectAllUsersInfo(tenantId).stream() .filter(user -> Objects.equals(user.getTeamId(), topicOwnerTeamId)) .findFirst(); - // String userTeam = dbHandle.getUsersInfo(userDetails).getTeam(); Integer userTeamId = getMyTeamId(userDetails); topicRequestReq.setRequestor(userDetails); topicRequestReq.setUsername(userDetails); topicRequestReq.setTeamId(userTeamId); topicRequestReq.setTenantId(tenantId); - // topicRequestReq.setTeamname(topicOwnerTeam); topicRequestReq.setEnvironment(getEnvDetailsFromName(env, tenantId).getId()); topicRequestReq.setTopicname(topicName); topicRequestReq.setTopictype(TopicRequestTypes.Claim.name()); @@ -449,11 +422,14 @@ public Map createClaimTopicRequest(String topicName, String env) TOPIC_CLAIM_REQUESTED, commonUtilsService.getLoginUrl())); - resultMap.put( - "result", - manageDatabase.getHandleDbRequests().requestForTopic(topicRequestReq).get("result")); - - return resultMap; + try { + String result = + manageDatabase.getHandleDbRequests().requestForTopic(topicRequestReq).get("result"); + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } public List getTopicRequests( @@ -559,7 +535,6 @@ public Map getTopicTeamOnly(String topicName, String patternType } List stringTeamsFound = new ArrayList<>(); - alltopicsStartingWithPattern.forEach(top -> stringTeamsFound.add(top.getTeamId())); List updatedTeamList = @@ -573,7 +548,6 @@ public Map getTopicTeamOnly(String topicName, String patternType return teamMap; } else { List topics = manageDatabase.getHandleDbRequests().getTopicTeam(topicName, tenantId); - // tenant filtering topics = getFilteredTopicsForTenant(topics); @@ -607,7 +581,6 @@ public List getCreatedTopicRequests( .getCreatedTopicRequests(userDetails, requestsType, true, tenantId); createdTopicReqList = getTopicRequestsFilteredForTenant(createdTopicReqList); - createdTopicReqList = getTopicRequestsPaged(createdTopicReqList, pageNo, currentPage); return updateCreateTopicReqsList(createdTopicReqList, tenantId); @@ -685,21 +658,25 @@ private String updateApproverInfo( return String.valueOf(approvingInfo); } - public String deleteTopicRequests(String topicId) { + public ApiResponse deleteTopicRequests(String topicId) throws KlawException { log.info("deleteTopicRequests {}", topicId); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_TOPICS)) { - String res = "Not Authorized."; - return "{\"result\":\"" + res + "\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } - String deleteTopicReqStatus = - manageDatabase - .getHandleDbRequests() - .deleteTopicRequest( - Integer.parseInt(topicId), commonUtilsService.getTenantId(getUserName())); + try { + String deleteTopicReqStatus = + manageDatabase + .getHandleDbRequests() + .deleteTopicRequest( + Integer.parseInt(topicId), commonUtilsService.getTenantId(getUserName())); - return "{\"result\":\"" + deleteTopicReqStatus + "\"}"; + return ApiResponse.builder().result(deleteTopicReqStatus).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } public ApiResponse approveTopicRequests(String topicId) throws KlawException { @@ -707,10 +684,7 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) { - return ApiResponse.builder() - .result(ApiResultStatus.NOT_AUTHORIZED.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } TopicRequest topicRequest = @@ -721,24 +695,17 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { if (Objects.equals(topicRequest.getRequestor(), userDetails)) { return ApiResponse.builder() .result("You are not allowed to approve your own topic requests.") - .status(HttpStatus.OK) .build(); } if (!RequestStatus.created.name().equals(topicRequest.getTopicstatus())) { - return ApiResponse.builder() - .result("This request does not exist anymore.") - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) { - return ApiResponse.builder() - .result(ApiResultStatus.NOT_AUTHORIZED.value) - .status(HttpStatus.OK) - .build(); + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -779,7 +746,7 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { } } - return ApiResponse.builder().result(updateTopicReqStatus).status(HttpStatus.OK).build(); + return ApiResponse.builder().result(updateTopicReqStatus).build(); } private void setTopicHistory(TopicRequest topicRequest, String userName, int tenantId) { @@ -818,11 +785,12 @@ private void setTopicHistory(TopicRequest topicRequest, String userName, int ten } } - public String declineTopicRequests(String topicId, String reasonForDecline) { + public ApiResponse declineTopicRequests(String topicId, String reasonForDecline) + throws KlawException { log.info("declineTopicRequests {} {}", topicId, reasonForDecline); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); TopicRequest topicRequest = @@ -830,25 +798,29 @@ public String declineTopicRequests(String topicId, String reasonForDecline) { Integer.parseInt(topicId), commonUtilsService.getTenantId(getUserName())); if (!RequestStatus.created.name().equals(topicRequest.getTopicstatus())) { - return "{\"result\":\"This request does not exist anymore.\"}"; + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); - String result = dbHandle.declineTopicRequest(topicRequest, userDetails); - mailService.sendMail( - topicRequest.getTopicname(), - null, - reasonForDecline, - topicRequest.getRequestor(), - dbHandle, - TOPIC_REQUEST_DENIED, - commonUtilsService.getLoginUrl()); + try { + String result = dbHandle.declineTopicRequest(topicRequest, userDetails); + mailService.sendMail( + topicRequest.getTopicname(), + null, + reasonForDecline, + topicRequest.getRequestor(), + dbHandle, + TOPIC_REQUEST_DENIED, + commonUtilsService.getLoginUrl()); - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } public List getAllTopics(boolean isMyTeamTopics) { @@ -877,9 +849,7 @@ public List getAllTopics(boolean isMyTeamTopics) { return topicsList.stream().distinct().collect(Collectors.toList()); } - public Map saveTopicDocumentation(TopicInfo topicInfo) { - Map saveResult = new HashMap<>(); - + public ApiResponse saveTopicDocumentation(TopicInfo topicInfo) throws KlawException { Topic topic = new Topic(); topic.setTenantId(commonUtilsService.getTenantId(getUserName())); topic.setTopicid(topicInfo.getTopicid()); @@ -890,18 +860,20 @@ public Map saveTopicDocumentation(TopicInfo topicInfo) { List topicsSearchList = manageDatabase.getHandleDbRequests().getTopicTeam(topicInfo.getTopicName(), tenantId); - // tenant filtering - Integer topicOwnerTeamId = getFilteredTopicsForTenant(topicsSearchList).get(0).getTeamId(); - - // String loggedInUserTeam = handleDb.selectAllTeamsOfUsers(getUserName(), - // tenantId).get(0).getTeamname(); - Integer loggedInUserTeamId = getMyTeamId(getUserName()); - if (Objects.equals(topicOwnerTeamId, loggedInUserTeamId)) { - saveResult.put( - "result", manageDatabase.getHandleDbRequests().updateTopicDocumentation(topic)); - } else saveResult.put("result", "failure"); - - return saveResult; + try { + // tenant filtering + Integer topicOwnerTeamId = getFilteredTopicsForTenant(topicsSearchList).get(0).getTeamId(); + Integer loggedInUserTeamId = getMyTeamId(getUserName()); + if (Objects.equals(topicOwnerTeamId, loggedInUserTeamId)) { + return ApiResponse.builder() + .result(manageDatabase.getHandleDbRequests().updateTopicDocumentation(topic)) + .build(); + } else { + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } public Map getTopicDetailsPerEnv(String envId, String topicName) { @@ -992,8 +964,7 @@ public List> getTopics( String currentPage, String topicNameSearch, String teamName, - String topicType) - throws Exception { + String topicType) { log.debug("getTopics {}", topicNameSearch); List topicListUpdated = getTopicsPaginated( diff --git a/src/main/resources/static/js/serverConfig.js b/src/main/resources/static/js/serverConfig.js index a267c8885a..f10b2cc337 100644 --- a/src/main/resources/static/js/serverConfig.js +++ b/src/main/resources/static/js/serverConfig.js @@ -182,12 +182,12 @@ app.controller("serverConfigCtrl", function($scope, $http, $location, $window) { params: {'kwPropertiesModel' : serviceInput }, data: serviceInput }).success(function(output) { - $scope.alert = "Property ("+ output.resultkey +") update status : " + output.result; + $scope.alert = "Property ("+ output.data +") update status : " + output.result; if(output.result == 'success'){ swal({ title: "", - text: "Property Update status. ("+ output.resultkey +") " + output.result, + text: "Property Update status. ("+ output.data +") " + output.result, timer: 2000, showConfirmButton: false }); diff --git a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java index 6902f6ea2f..b72dd822eb 100644 --- a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java @@ -74,7 +74,8 @@ public void getSchemaRequests() throws Exception { @Test @Order(2) public void deleteSchemaRequests() throws Exception { - when(schemaRegstryControllerService.deleteSchemaRequests(anyString())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(schemaRegstryControllerService.deleteSchemaRequests(anyString())).thenReturn(apiResponse); String response = mvc.perform( @@ -115,8 +116,8 @@ public void execSchemaRequests() throws Exception { public void uploadSchema() throws Exception { SchemaRequestModel schemaRequest = utilMethods.getSchemaRequests().get(0); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(schemaRequest); - - when(schemaRegstryControllerService.uploadSchema(any())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(schemaRegstryControllerService.uploadSchema(any())).thenReturn(apiResponse); String response = mvc.perform( diff --git a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java index 19e04f7a94..6eaaaac752 100644 --- a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java @@ -187,7 +187,8 @@ public void getCreatedTopicRequests() throws Exception { @Test @Order(6) public void deleteTopicRequests() throws Exception { - when(topicControllerService.deleteTopicRequests(anyString())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(topicControllerService.deleteTopicRequests(anyString())).thenReturn(apiResponse); String response = mvc.perform( @@ -199,8 +200,9 @@ public void deleteTopicRequests() throws Exception { .andReturn() .getResponse() .getContentAsString(); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(response).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test @@ -228,8 +230,9 @@ public void approveTopicRequests() throws Exception { @Test @Order(8) public void declineTopicRequests() throws Exception { + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); when(topicControllerService.declineTopicRequests(anyString(), anyString())) - .thenReturn("success"); + .thenReturn(apiResponse); String response = mvc.perform( @@ -243,7 +246,8 @@ public void declineTopicRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).isEqualTo("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java similarity index 91% rename from src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java rename to src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java index 5d2e4f2822..56edd187d7 100644 --- a/src/test/java/io/aiven/klaw/service/SchemaRegstryControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java @@ -40,7 +40,7 @@ @ExtendWith(SpringExtension.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class SchemaRegstryControllerServiceTest { +public class SchemaRegistryControllerServiceTest { @Mock private UserDetails userDetails; @@ -115,13 +115,13 @@ public void getSchemaRequests() { @Test @Order(2) - public void deleteSchemaRequestsSuccess() { + public void deleteSchemaRequestsSuccess() throws KlawException { int schemaReqId = 1001; stubUserInfo(); when(handleDbRequests.deleteSchemaRequest(anyInt(), anyInt())).thenReturn("success"); - String result = schemaRegstryControllerService.deleteSchemaRequests("" + schemaReqId); - assertThat(result).isEqualTo("success"); + ApiResponse resultResp = schemaRegstryControllerService.deleteSchemaRequests("" + schemaReqId); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @@ -131,9 +131,12 @@ public void deleteSchemaRequestsFailure() { stubUserInfo(); when(handleDbRequests.deleteSchemaRequest(anyInt(), anyInt())) - .thenThrow(new RuntimeException("Error")); - String result = schemaRegstryControllerService.deleteSchemaRequests("" + schemaReqId); - assertThat(result).contains("failure"); + .thenThrow(new RuntimeException("Error from Schema upload")); + try { + schemaRegstryControllerService.deleteSchemaRequests("" + schemaReqId); + } catch (KlawException e) { + assertThat(e.getMessage()).contains("Error from Schema upload"); + } } @Test @@ -229,7 +232,7 @@ public void execSchemaRequestsFailure2() { @Test @Order(7) - public void uploadSchemaSuccess() { + public void uploadSchemaSuccess() throws KlawException { SchemaRequestModel schemaRequest = new SchemaRequestModel(); schemaRequest.setSchemafull("{}"); schemaRequest.setUsername("kwuserb"); @@ -247,8 +250,8 @@ public void uploadSchemaSuccess() { when(handleDbRequests.requestForSchema(any())).thenReturn("success"); when(handleDbRequests.getTopicTeam(anyString(), anyInt())).thenReturn(List.of(topic)); - String result = schemaRegstryControllerService.uploadSchema(schemaRequest); - assertThat(result).isEqualTo("success"); + ApiResponse resultResp = schemaRegstryControllerService.uploadSchema(schemaRequest); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @@ -268,11 +271,15 @@ public void uploadSchemaFailure() { .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - when(handleDbRequests.requestForSchema(any())).thenThrow(new RuntimeException("Error")); + when(handleDbRequests.requestForSchema(any())) + .thenThrow(new RuntimeException("Error from schema upload")); when(handleDbRequests.getTopicTeam(anyString(), anyInt())).thenReturn(List.of(topic)); - String result = schemaRegstryControllerService.uploadSchema(schemaRequest); - assertThat(result).contains("failure"); + try { + schemaRegstryControllerService.uploadSchema(schemaRequest); + } catch (KlawException e) { + assertThat(e.getMessage()).contains("Error from schema upload"); + } } private List getSchemasReqs() { diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index 1d1333fe6f..29931841ef 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -310,11 +310,11 @@ public void getCreatedTopicRequests2() { @Test @Order(12) - public void deleteTopicRequests() { + public void deleteTopicRequests() throws KlawException { when(handleDbRequests.deleteTopicRequest(anyInt(), anyInt())).thenReturn("success"); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - String result = topicControllerService.deleteTopicRequests("1001"); - assertThat(result).isEqualTo("{\"result\":\"success\"}"); + ApiResponse resultResp = topicControllerService.deleteTopicRequests("1001"); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test @@ -451,9 +451,9 @@ public void declineTopicRequests() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(handleDbRequests.declineTopicRequest(any(), anyString())).thenReturn("success"); - String result = topicControllerService.declineTopicRequests(topicId + "", "Reason"); + ApiResponse resultResp = topicControllerService.declineTopicRequests(topicId + "", "Reason"); - assertThat(result).isEqualTo("{\"result\":\"" + "success" + "\"}"); + assertThat(resultResp.getResult()).isEqualTo("success"); } @Test From 5b6abd637c96faa1f19ebb7605c5e0203b4c7a98 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Wed, 5 Oct 2022 10:32:26 +0200 Subject: [PATCH 09/15] Updating response with ApiResponse for a few apis Users/Envs/Tenants/Teams --- .../klaw/controller/TopicSyncController.java | 33 +-- .../klaw/controller/UiConfigController.java | 3 +- .../klaw/controller/UsersTeamsController.java | 125 ++++++----- .../EnvsClustersTenantsControllerService.java | 9 +- .../KafkaConnectSyncControllerService.java | 2 - .../io/aiven/klaw/service/SaasService.java | 60 +++--- .../klaw/service/ServerConfigService.java | 1 - .../service/TopicSyncControllerService.java | 107 +++++----- .../service/UiConfigControllerService.java | 10 +- .../service/UsersTeamsControllerService.java | 195 +++++++++--------- .../resources/static/js/syncBackTopics.js | 2 +- .../resources/static/js/syncConnectors.js | 2 +- .../resources/static/js/synchronizeTopics.js | 2 +- .../io/aiven/klaw/UsersTeamsControllerIT.java | 4 +- .../klaw/controller/AclControllerTest.java | 3 +- .../klaw/controller/TopicControllerTest.java | 10 +- .../controller/UiConfigControllerTest.java | 28 ++- .../service/TopicControllerServiceTest.java | 19 +- 18 files changed, 316 insertions(+), 299 deletions(-) diff --git a/src/main/java/io/aiven/klaw/controller/TopicSyncController.java b/src/main/java/io/aiven/klaw/controller/TopicSyncController.java index bb8dba3cef..10e5411a74 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicSyncController.java @@ -1,5 +1,9 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SyncBackTopics; import io.aiven.klaw.model.SyncTopicUpdates; import io.aiven.klaw.model.SyncTopicsBulk; @@ -25,19 +29,25 @@ public class TopicSyncController { @Autowired private TopicSyncControllerService topicSyncControllerService; @PostMapping(value = "/updateSyncTopics") - public ResponseEntity> updateSyncTopics( + public ResponseEntity updateSyncTopics( @RequestBody List syncTopicUpdates) { - Map updateSyncTopicsResult = - topicSyncControllerService.updateSyncTopics(syncTopicUpdates); - return new ResponseEntity<>(updateSyncTopicsResult, HttpStatus.OK); + try { + return new ResponseEntity<>( + topicSyncControllerService.updateSyncTopics(syncTopicUpdates), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/updateSyncTopicsBulk") - public ResponseEntity>> updateSyncTopicsBulk( + public ResponseEntity updateSyncTopicsBulk( @RequestBody SyncTopicsBulk syncTopicsBulk) { - Map> updateSyncTopicsBulkResult = - topicSyncControllerService.updateSyncTopicsBulk(syncTopicsBulk); - return new ResponseEntity<>(updateSyncTopicsBulkResult, HttpStatus.OK); + try { + return new ResponseEntity<>( + topicSyncControllerService.updateSyncTopicsBulk(syncTopicsBulk), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } // sync back topics @@ -61,11 +71,10 @@ public ResponseEntity> getTopicsRowView( } @PostMapping(value = "/updateSyncBackTopics") - public ResponseEntity>> updateSyncBackTopics( + public ResponseEntity updateSyncBackTopics( @RequestBody SyncBackTopics syncBackTopics) { - Map> updateSyncTopicsResult = - topicSyncControllerService.updateSyncBackTopics(syncBackTopics); - return new ResponseEntity<>(updateSyncTopicsResult, HttpStatus.OK); + return new ResponseEntity<>( + topicSyncControllerService.updateSyncBackTopics(syncBackTopics), HttpStatus.OK); } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/controller/UiConfigController.java b/src/main/java/io/aiven/klaw/controller/UiConfigController.java index 9d4d70be85..3024195e73 100644 --- a/src/main/java/io/aiven/klaw/controller/UiConfigController.java +++ b/src/main/java/io/aiven/klaw/controller/UiConfigController.java @@ -1,6 +1,7 @@ package io.aiven.klaw.controller; import io.aiven.klaw.dao.ActivityLog; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.service.UiConfigControllerService; import java.util.List; import java.util.Map; @@ -37,7 +38,7 @@ public ResponseEntity> getRequestTypeStatuses() { } @PostMapping(value = "/sendMessageToAdmin") - public ResponseEntity> sendMessageToAdmin( + public ResponseEntity sendMessageToAdmin( @RequestParam("contactFormSubject") String contactFormSubject, @RequestParam("contactFormMessage") String contactFormMessage) { return new ResponseEntity<>( diff --git a/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java b/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java index 48614ed64f..88f5c3167c 100644 --- a/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java +++ b/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java @@ -1,12 +1,15 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.RegisterSaasUserInfoModel; import io.aiven.klaw.model.RegisterUserInfoModel; import io.aiven.klaw.model.TeamModel; import io.aiven.klaw.model.UserInfoModel; import io.aiven.klaw.service.SaasService; import io.aiven.klaw.service.UsersTeamsControllerService; -import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; @@ -50,66 +53,73 @@ public ResponseEntity> getAllTeamsSUOnly() { } @PostMapping(value = "/deleteTeamRequest") - public ResponseEntity deleteTeam(@RequestParam("teamId") Integer teamId) { - - return new ResponseEntity<>(usersTeamsControllerService.deleteTeam(teamId), HttpStatus.OK); + public ResponseEntity deleteTeam(@RequestParam("teamId") Integer teamId) { + try { + return new ResponseEntity<>(usersTeamsControllerService.deleteTeam(teamId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/deleteUserRequest") - public ResponseEntity deleteUser(@RequestParam("userId") String userId) { - - return new ResponseEntity<>( - usersTeamsControllerService.deleteUser(userId, true), HttpStatus.OK); + public ResponseEntity deleteUser(@RequestParam("userId") String userId) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.deleteUser(userId, true), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/updateUser") - public ResponseEntity updateUser(@Valid @RequestBody UserInfoModel updateUserObj) { - return new ResponseEntity<>( - usersTeamsControllerService.updateUser(updateUserObj), HttpStatus.OK); + public ResponseEntity updateUser(@Valid @RequestBody UserInfoModel updateUserObj) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.updateUser(updateUserObj), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/updateProfile") - public ResponseEntity> updateProfile( + public ResponseEntity updateProfile( @Valid @RequestBody UserInfoModel updateUserObj) { - return new ResponseEntity<>( - usersTeamsControllerService.updateProfile(updateUserObj), HttpStatus.OK); + try { + return new ResponseEntity<>( + usersTeamsControllerService.updateProfile(updateUserObj), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/addNewUser") - public ResponseEntity> addNewUser(@Valid @RequestBody UserInfoModel newUser) { - + public ResponseEntity addNewUser(@Valid @RequestBody UserInfoModel newUser) { try { - Map response = usersTeamsControllerService.addNewUser(newUser, true); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - Map resMap = new HashMap<>(); - resMap.put("result", "Failure. Unable to create the user."); - return new ResponseEntity<>(resMap, HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>( + usersTeamsControllerService.addNewUser(newUser, true), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); } } @PostMapping(value = "/registerUser") - public ResponseEntity> registerUser( - @Valid @RequestBody RegisterUserInfoModel newUser) throws Exception { + public ResponseEntity registerUser(@Valid @RequestBody RegisterUserInfoModel newUser) + throws Exception { try { return new ResponseEntity<>( usersTeamsControllerService.registerUser(newUser, true), HttpStatus.OK); - } catch (Exception e) { - Map resMap = new HashMap<>(); - resMap.put("result", "Failure. " + e.getMessage()); - return new ResponseEntity<>(resMap, HttpStatus.INTERNAL_SERVER_ERROR); + } catch (KlawException e) { + return handleException(e); } } @PostMapping(value = "/registerUserSaas") - public ResponseEntity> registerUserSaas( + public ResponseEntity registerUserSaas( @Valid @RequestBody RegisterSaasUserInfoModel newUser) throws Exception { try { return new ResponseEntity<>(saasService.registerUserSaas(newUser), HttpStatus.OK); - } catch (Exception e) { - Map resMap = new HashMap<>(); - resMap.put("result", "Failure. Something went wrong. Please try later."); - return new ResponseEntity<>(resMap, HttpStatus.INTERNAL_SERVER_ERROR); + } catch (KlawException e) { + return handleException(e); } } @@ -142,26 +152,45 @@ public ResponseEntity getRegistrationInfoFromId( } @PostMapping(value = "/execNewUserRequestApprove") - public ResponseEntity approveNewUserRequests(@RequestParam("username") String username) { - return new ResponseEntity<>( - usersTeamsControllerService.approveNewUserRequests(username, true, 0, ""), HttpStatus.OK); + public ResponseEntity approveNewUserRequests( + @RequestParam("username") String username) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.approveNewUserRequests(username, true, 0, ""), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/execNewUserRequestDecline") - public ResponseEntity declineNewUserRequests(@RequestParam("username") String username) { - return new ResponseEntity<>( - usersTeamsControllerService.declineNewUserRequests(username), HttpStatus.OK); + public ResponseEntity declineNewUserRequests( + @RequestParam("username") String username) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.declineNewUserRequests(username), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/addNewTeam") - public ResponseEntity addNewTeam(@Valid @RequestBody TeamModel newTeam) { - return new ResponseEntity<>( - usersTeamsControllerService.addNewTeam(newTeam, true), HttpStatus.OK); + public ResponseEntity addNewTeam(@Valid @RequestBody TeamModel newTeam) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.addNewTeam(newTeam, true), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/updateTeam") - public ResponseEntity updateTeam(@Valid @RequestBody TeamModel updateTeam) { - return new ResponseEntity<>(usersTeamsControllerService.updateTeam(updateTeam), HttpStatus.OK); + public ResponseEntity updateTeam(@Valid @RequestBody TeamModel updateTeam) { + try { + return new ResponseEntity<>( + usersTeamsControllerService.updateTeam(updateTeam), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -176,8 +205,12 @@ public ResponseEntity getTeamDetails( } @PostMapping(value = "/chPwd") - public ResponseEntity changePwd(@RequestParam("changePwd") String changePwd) { - return new ResponseEntity<>(usersTeamsControllerService.changePwd(changePwd), HttpStatus.OK); + public ResponseEntity changePwd(@RequestParam("changePwd") String changePwd) { + try { + return new ResponseEntity<>(usersTeamsControllerService.changePwd(changePwd), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 6622d35cfb..445bc1e0b4 100644 --- a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -1084,10 +1084,13 @@ public Map deleteTenant() { List allUsers = manageDatabase.getHandleDbRequests().selectAllUsersInfo(tenantId); for (UserInfo userInfo : allUsers) { - usersTeamsControllerService.deleteUser(userInfo.getUsername(), false); // internal delete + try { + usersTeamsControllerService.deleteUser(userInfo.getUsername(), false); // internal delete + } catch (KlawException e) { + throw new RuntimeException(e); + } } manageDatabase.getHandleDbRequests().deleteAllUsers(tenantId); - manageDatabase.getHandleDbRequests().deleteAllTeams(tenantId); manageDatabase.getHandleDbRequests().deleteAllEnvs(tenantId); manageDatabase.getHandleDbRequests().deleteAllClusters(tenantId); @@ -1097,7 +1100,7 @@ public Map deleteTenant() { String result = manageDatabase.getHandleDbRequests().disableTenant(tenantId); - if ("success".equals(result)) { + if (ApiResultStatus.SUCCESS.value.equals(result)) { commonUtilsService.updateMetadata(tenantId, EntityType.TENANT, MetadataOperationType.DELETE); resultMap.put("result", "success"); resultMap.put("tenantId", tenantName); diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java index 7ac8757800..896ec98193 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java @@ -65,7 +65,6 @@ public Map getConnectorDetails(String connectorName, String envI } response.put("result", res.toString()); - return response; } @@ -73,7 +72,6 @@ public ApiResponse updateSyncConnectors(List updatedSyncTo throws KlawException { log.info("updateSyncConnectors {}", updatedSyncTopics); String userDetails = getUserName(); - Map response = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_CONNECTORS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); diff --git a/src/main/java/io/aiven/klaw/service/SaasService.java b/src/main/java/io/aiven/klaw/service/SaasService.java index 7101b3cece..3a1630efcf 100644 --- a/src/main/java/io/aiven/klaw/service/SaasService.java +++ b/src/main/java/io/aiven/klaw/service/SaasService.java @@ -5,6 +5,9 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.RegisterUserInfo; import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.error.KlawException; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwTenantModel; import io.aiven.klaw.model.RegisterSaasUserInfoModel; import io.aiven.klaw.model.RegisterUserInfoModel; @@ -83,10 +86,11 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws && teamAddMap.get("team2result").contains("success")) { // approve user - String resultApproveUser = + ApiResponse resultApproveUser = usersTeamsControllerService.approveNewUserRequests( newUser.getUsername(), false, tenantId, KwConstants.INFRATEAM); - if (resultApproveUser.contains("success")) updateStaticData(newUser, tenantId); + if (resultApproveUser.getResult().contains(ApiResultStatus.SUCCESS.value)) + updateStaticData(newUser, tenantId); else { resultMap.put("error", "Something went wrong. Please try again."); return resultMap; @@ -112,43 +116,42 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws } // TO DO transactions - public Map registerUserSaas(RegisterSaasUserInfoModel newUser) throws Exception { + public ApiResponse registerUserSaas(RegisterSaasUserInfoModel newUser) throws Exception { log.info("registerUserSaas {} / {}", newUser.getFullname(), newUser.getMailid()); Map tenantMap = manageDatabase.getTenantMap(); - Map resultMap = new HashMap<>(); - resultMap.put("result", "failure"); try { - if (handleValidations(newUser, tenantMap, resultMap)) return resultMap; + if (handleValidations(newUser, tenantMap, resultMap)) + return ApiResponse.builder().result(resultMap.get("result")).build(); RegisterUserInfoModel newUserTarget = new RegisterUserInfoModel(); copyProperties(newUser, newUserTarget); - String userName = newUser.getMailid(); - newUserTarget.setUsername(userName); String pwd = usersTeamsControllerService.generateRandomWord(10); newUserTarget.setPwd(pwd); if (newUser.getTenantName() == null || newUser.getTenantName().equals("")) { // new user - if (createNewUserForActivation(resultMap, newUserTarget)) return resultMap; + if (createNewUserForActivation(resultMap, newUserTarget)) + return ApiResponse.builder().result(resultMap.get("error")).build(); } else if (!tenantMap.containsValue(newUser.getTenantName())) { resultMap.put("error", "Tenant does not exist."); - return resultMap; + return ApiResponse.builder() + .result("Tenant does not exist.") + .message("Tenant does not exist.") + .build(); } else { // create user for existing tenant if (createUserForExistingTenant(newUser, tenantMap, resultMap, newUserTarget)) - return resultMap; + return ApiResponse.builder().result(resultMap.get("error")).build(); } - resultMap.put("result", "success"); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } catch (Exception e) { log.error("Exception:", e); - resultMap.put("error", "Something went wrong. Please try again."); - return resultMap; + throw new KlawException(e.getMessage()); } } @@ -160,9 +163,9 @@ private boolean createNewUserForActivation( newUserTarget.setTeam(KwConstants.INFRATEAM); newUserTarget.setRegistrationId(randomId); newUserTarget.setRegisteredTime(new Timestamp(System.currentTimeMillis())); - Map userRegMap = usersTeamsControllerService.registerUser(newUserTarget, false); + ApiResponse userRegMap = usersTeamsControllerService.registerUser(newUserTarget, false); - if (!"success".equals(userRegMap.get("result"))) { + if (!ApiResultStatus.SUCCESS.value.equals(userRegMap.getResult())) { resultMap.put("error", "Something went wrong. Please try again."); return true; } @@ -195,10 +198,9 @@ private boolean createUserForExistingTenant( String newTenantName = newUser.getTenantName(); Integer tenantId; // register user - String finalNewTenantName = newTenantName; tenantId = tenantMap.entrySet().stream() - .filter(obj -> Objects.equals(obj.getValue(), finalNewTenantName)) + .filter(obj -> Objects.equals(obj.getValue(), newTenantName)) .findFirst() .get() .getKey(); @@ -206,16 +208,14 @@ private boolean createUserForExistingTenant( newUserTarget.setTenantId(tenantId); newUserTarget.setTeam(KwConstants.STAGINGTEAM); newUserTarget.setRole(KwConstants.USER_ROLE); - Map userRegMap = usersTeamsControllerService.registerUser(newUserTarget, false); + ApiResponse userRegMap = usersTeamsControllerService.registerUser(newUserTarget, false); - if (!"success".equals(userRegMap.get("result"))) { + if (!ApiResultStatus.SUCCESS.value.equals(userRegMap.getResult())) { resultMap.put("error", "Something went wrong. Please try again."); return true; } else { RegisterUserInfo registerUserInfo = new RegisterUserInfo(); - copyProperties(newUserTarget, registerUserInfo); - mailService.sendMailRegisteredUserSaas( registerUserInfo, manageDatabase.getHandleDbRequests(), @@ -224,21 +224,7 @@ private boolean createUserForExistingTenant( newUserTarget.getTeam(), "activationUrl", commonUtilsService.getLoginUrl()); - - // String resultApproveUser = usersTeamsControllerService - // .approveNewUserRequests(newUserTarget.getUsername(), false, tenantId, - // STAGINGTEAM); - // if(resultApproveUser.contains("success")){ - // RegisterUserInfo registerUserInfo = new RegisterUserInfo(); - // copyProperties(newUserTarget, registerUserInfo); - // - // mailService.sendMailRegisteredUserSaas(registerUserInfo, - // manageDatabase.getHandleDbRequests(), newTenantName, - // tenantId, newUserTarget.getTeam(), "activationUrl", - // commonUtilsService.getLoginUrl()); - // } } - return false; } diff --git a/src/main/java/io/aiven/klaw/service/ServerConfigService.java b/src/main/java/io/aiven/klaw/service/ServerConfigService.java index cd2b08e226..2c934f003a 100644 --- a/src/main/java/io/aiven/klaw/service/ServerConfigService.java +++ b/src/main/java/io/aiven/klaw/service/ServerConfigService.java @@ -154,7 +154,6 @@ public List> getAllEditableProps() { public ApiResponse updateKwCustomProperty(KwPropertiesModel kwPropertiesModel) throws KlawException { log.info("updateKwCustomProperty {}", kwPropertiesModel); - // Map response = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); String kwKey = kwPropertiesModel.getKwKey(); String kwVal = kwPropertiesModel.getKwValue().trim(); diff --git a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index 974fbfd248..e63d27dd98 100644 --- a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -10,6 +10,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.PermissionType; @@ -487,7 +488,7 @@ private List tenantFilterTeams(List teamList) { return teamList; } - public Map> updateSyncBackTopics(SyncBackTopics syncBackTopics) { + public ApiResponse updateSyncBackTopics(SyncBackTopics syncBackTopics) { log.info("updateSyncBackTopics {}", syncBackTopics); Map> resultMap = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -499,15 +500,11 @@ public Map> updateSyncBackTopics(SyncBackTopics syncBackTop logArray.add("Type of Sync " + syncBackTopics.getTypeOfSync()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { - List notAuth = new ArrayList<>(); - notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); - resultMap.put("result", notAuth); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } List resultStatus = new ArrayList<>(); - resultStatus.add("success"); - + resultStatus.add(ApiResultStatus.SUCCESS.value); resultMap.put("result", resultStatus); if ("SELECTED_TOPICS".equals(syncBackTopics.getTypeOfSync())) { @@ -532,9 +529,7 @@ public Map> updateSyncBackTopics(SyncBackTopics syncBackTop } } - resultMap.put("syncbacklog", logArray); - - return resultMap; + return ApiResponse.builder().result(resultMap.get("result").get(0)).data(logArray).build(); } private void approveSyncBackTopics( @@ -822,9 +817,9 @@ private List groupTopicsByEnv(List topicsFromSOT) { return tmpTopicList; } - public Map> updateSyncTopicsBulk(SyncTopicsBulk syncTopicsBulk) { + public ApiResponse updateSyncTopicsBulk(SyncTopicsBulk syncTopicsBulk) throws KlawException { log.info("updateSyncTopicsBulk {}", syncTopicsBulk); - Map> resultMap = new HashMap<>(); + // Map> resultMap = new HashMap<>(); List logArray = new ArrayList<>(); @@ -833,16 +828,13 @@ public Map> updateSyncTopicsBulk(SyncTopicsBulk syncTopicsB logArray.add("Type of Sync " + syncTopicsBulk.getTypeOfSync()); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { - List notAuth = new ArrayList<>(); - notAuth.add(ApiResultStatus.NOT_AUTHORIZED.value); - resultMap.put("result", notAuth); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } - List resultStatus = new ArrayList<>(); - resultStatus.add("success"); - - resultMap.put("result", resultStatus); + // List resultStatus = new ArrayList<>(); + // resultStatus.add("success"); + // + // resultMap.put("result", resultStatus); if ("SELECTED_TOPICS".equals(syncTopicsBulk.getTypeOfSync())) { Object[] topicMap = syncTopicsBulk.getTopicDetails(); @@ -866,11 +858,11 @@ public Map> updateSyncTopicsBulk(SyncTopicsBulk syncTopicsB } } catch (Exception e) { log.error("Could not retrieve topics ", e); + throw new KlawException(e.getMessage()); } } - resultMap.put("syncbulklog", logArray); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).data(logArray).build(); } private void invokeUpdateSyncAllTopics( @@ -891,7 +883,7 @@ private void invokeUpdateSyncAllTopics( "Topic status :" + hashMap.get("topicName") + " " - + updateSyncTopics(updatedSyncTopicsList).get("result")); + + updateSyncTopics(updatedSyncTopicsList).getResult()); } catch (Exception e) { logArray.add("Topic update failed :" + hashMap.get("topicName") + " " + e.toString()); log.error("Exception:", e); @@ -956,24 +948,20 @@ private void invokeUpdateSync( updatedSyncTopicsList.add(syncTopicUpdates); try { logArray.add( - "Topic status :" - + topicName - + " " - + updateSyncTopics(updatedSyncTopicsList).get("result")); + "Topic status :" + topicName + " " + updateSyncTopics(updatedSyncTopicsList).getResult()); } catch (Exception e) { log.error("Exception:", e); logArray.add("Topic update failed :" + topicName + " " + e); } } - public Map updateSyncTopics(List updatedSyncTopics) { + public ApiResponse updateSyncTopics(List updatedSyncTopics) + throws KlawException { log.info("updateSyncTopics {}", updatedSyncTopics); String userDetails = getUserName(); - Map response = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { - response.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } // tenant filtering @@ -1008,8 +996,7 @@ public Map updateSyncTopics(List updatedSyncTo for (SyncTopicUpdates topicUpdate : updatedSyncTopics) { // tenant filtering if (!getEnvsFromUserId(userDetails).contains(topicUpdate.getEnvSelected())) { - response.put("result", "Not Authorized."); - return response; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } existingTopics = getTopicFromName(topicUpdate.getTopicName(), tenantId); @@ -1107,39 +1094,45 @@ public Map updateSyncTopics(List updatedSyncTo } if (updatedSyncTopics.size() == 0 && updatedSyncTopicsDelete.size() > 0) { - response.put("result", "success"); - return response; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } if (topicsDontExistInMainCluster) { - response.put( - "result", - "Failure. Please sync up the team of the following topic(s) first in" - + " main Sync cluster (klaw.syncdata.cluster)" - + " :" - + syncCluster - + ". \n Topics : " - + erroredTopicsExist); - return response; + return ApiResponse.builder() + .result( + "Failure. Please sync up the team of the following topic(s) first in" + + " main Sync cluster (klaw.syncdata.cluster)" + + " :" + + syncCluster + + ". \n Topics : " + + erroredTopicsExist) + .build(); } if (topicsWithDiffTeams) { - response.put( - "result", - "Failure. The following topics are being synchronized with" - + " a different team, when compared to main Sync cluster (klaw.syncdata.cluster)" - + " :" - + syncCluster - + ". \n Topics : " - + erroredTopics); - return response; + return ApiResponse.builder() + .result( + "Failure. The following topics are being synchronized with" + + " a different team, when compared to main Sync cluster (klaw.syncdata.cluster)" + + " :" + + syncCluster + + ". \n Topics : " + + erroredTopics) + .build(); } if (listTopics.size() > 0) { - response.put("result", manageDatabase.getHandleDbRequests().addToSynctopics(listTopics)); - } else response.put("result", "No record updated."); - - return response; + try { + return ApiResponse.builder() + .result(manageDatabase.getHandleDbRequests().addToSynctopics(listTopics)) + .build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } + } else { + return ApiResponse.builder().result("No record updated.").build(); + } } private List handleTopicDeletes( diff --git a/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java b/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java index 865f0330c7..9710114dbf 100644 --- a/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java @@ -3,6 +3,8 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.ActivityLog; import io.aiven.klaw.dao.Env; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.PermissionType; import java.util.*; import java.util.stream.Collectors; @@ -120,20 +122,16 @@ else if ("ConnectorRequest".equals(activityName)) return envFound.map(Env::getName).orElse(null); } - public Map sendMessageToAdmin( - String contactFormSubject, String contactFormMessage) { + public ApiResponse sendMessageToAdmin(String contactFormSubject, String contactFormMessage) { String userName = getUserName(); - Map hashMap = new HashMap<>(); - hashMap.put("result", "success"); - contactFormMessage = "From " + userName + ": \n" + contactFormMessage; mailService.sendMailToAdmin( contactFormSubject, contactFormMessage, commonUtilsService.getTenantId(getUserName()), commonUtilsService.getLoginUrl()); - return hashMap; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } public List getRequestTypeStatuses() { diff --git a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index d6fcc173ec..b3d3b19dcb 100644 --- a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -9,6 +9,7 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.EntityType; import io.aiven.klaw.model.MetadataOperationType; @@ -83,7 +84,7 @@ public UserInfoModel getUserInfoDetails(String userId) { } else return null; } - public Map updateProfile(UserInfoModel updateUserObj) { + public ApiResponse updateProfile(UserInfoModel updateUserObj) throws KlawException { log.info("updateProfile {}", updateUserObj); Map updateProfileResult = new HashMap<>(); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -91,16 +92,18 @@ public Map updateProfile(UserInfoModel updateUserObj) { UserInfo userInfo = manageDatabase.getHandleDbRequests().getUsersInfo(getUserName()); userInfo.setFullname(updateUserObj.getFullname()); userInfo.setMailid(updateUserObj.getMailid()); - - updateProfileResult.put("result", dbHandle.updateUser(userInfo)); - return updateProfileResult; + try { + return ApiResponse.builder().result(dbHandle.updateUser(userInfo)).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } - public String updateUser(UserInfoModel newUser) { + public ApiResponse updateUser(UserInfoModel newUser) throws KlawException { log.info("updateUser {}", newUser.getUsername()); if (commonUtilsService.isNotAuthorizedUser(getUserName(), PermissionType.ADD_EDIT_DELETE_USERS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); UserInfo existingUserInfo = manageDatabase.getHandleDbRequests().getUsersInfo(newUser.getUsername()); @@ -111,13 +114,14 @@ public String updateUser(UserInfoModel newUser) { && permissions.contains(PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES.name())) { if (!Objects.equals( getUserName(), newUser.getUsername())) { // should be able to update same user - return "{\"result\":\"Not Authorized to update another SUPERADMIN user.\"}"; + return ApiResponse.builder() + .result("Not Authorized to update another SUPERADMIN user.") + .build(); } } String pwdUpdated = newUser.getUserPassword(); String existingPwd; - if ("*******".equals(pwdUpdated) && "db".equals(authenticationType)) { existingPwd = existingUserInfo.getPwd(); if (!"".equals(existingPwd)) newUser.setUserPassword(decodePwd(existingPwd)); @@ -125,7 +129,6 @@ public String updateUser(UserInfoModel newUser) { try { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - if ("db".equals(authenticationType)) { if (inMemoryUserDetailsManager.userExists(newUser.getUsername())) { inMemoryUserDetailsManager.updateUser( @@ -151,12 +154,10 @@ public String updateUser(UserInfoModel newUser) { userInfo.setTeamId(manageDatabase.getTeamIdFromTeamName(tenantId, newUser.getTeam())); userInfo.setTenantId(tenantId); - String result = dbHandle.updateUser(userInfo); - - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(dbHandle.updateUser(userInfo)).build(); } catch (Exception e) { log.error("Error from updateUser ", e); - return "{\"result\":\"Failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } @@ -211,7 +212,7 @@ public Map resetPassword(String username) { inMemoryUserDetailsManager.updatePassword( updatePwdUserDetails, encoder.encode(newGeneratedPwd)); String pwdUpdated = dbHandle.updatePassword(username, encodePwd(newGeneratedPwd)); - if ("success".equals(pwdUpdated)) { + if (ApiResultStatus.SUCCESS.value.equals(pwdUpdated)) { userMap.put("passwordSent", "true"); mailService.sendMailResetPwd( username, @@ -302,10 +303,8 @@ public List getAllTeamsSUOnly() { .getTeamname(); List teams = new ArrayList<>(); - // tenant filtering List teamsList = getAllTeamsSU(); - teams.add("All teams"); // team id 1 teams.add(myTeamName); @@ -316,24 +315,24 @@ public List getAllTeamsSUOnly() { return teams; } - public String deleteTeam(Integer teamId) { + public ApiResponse deleteTeam(Integer teamId) throws KlawException { log.info("deleteTeam {}", teamId); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) - return "{\"result\":\"Not Authorized\"}"; - - String envAddResult = "{\"result\":\"Team cannot be deleted.\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (manageDatabase.getHandleDbRequests().findAllComponentsCountForTeam(teamId, tenantId) > 0) { - return "{\"result\":\"Not allowed to delete this team, as there are associated topics/acls/requests..\"}"; + return ApiResponse.builder() + .result("Not allowed to delete this team, as there are associated topics/acls/requests..") + .build(); } // own team cannot be deleted - if (Objects.equals(getMyTeamId(userDetails), teamId)) return envAddResult; + if (Objects.equals(getMyTeamId(userDetails), teamId)) + return ApiResponse.builder().result("Team cannot be deleted.").build(); try { String result = @@ -341,24 +340,24 @@ public String deleteTeam(Integer teamId) { .getHandleDbRequests() .deleteTeamRequest(teamId, commonUtilsService.getTenantId(getUserName())); - if ("success".equals(result)) { + if (ApiResultStatus.SUCCESS.value.equals(result)) { commonUtilsService.updateMetadata(tenantId, EntityType.TEAM, MetadataOperationType.DELETE); } - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } - public String deleteUser(String userId, boolean isExternal) { + public ApiResponse deleteUser(String userId, boolean isExternal) throws KlawException { log.info("deleteUser {}", userId); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); UserInfo existingUserInfo = manageDatabase.getHandleDbRequests().getUsersInfo(userId); List permissions = @@ -367,21 +366,22 @@ public String deleteUser(String userId, boolean isExternal) { .get(existingUserInfo.getRole()); if (permissions != null && permissions.contains(PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES.name())) - return "{\"result\":\"Not Authorized. Cannot delete a user with SUPERADMIN access.\"}"; + return ApiResponse.builder() + .result("Not Authorized. Cannot delete a user with SUPERADMIN access.") + .build(); String envAddResult = "{\"result\":\"User cannot be deleted\"}"; - - if (Objects.equals(userDetails, userId) && isExternal) return envAddResult; - - inMemoryUserDetailsManager.deleteUser(userId); + if (Objects.equals(userDetails, userId) && isExternal) + return ApiResponse.builder().result(envAddResult).build(); try { - return "{\"result\":\"" - + manageDatabase.getHandleDbRequests().deleteUserRequest(userId) - + "\"}"; + inMemoryUserDetailsManager.deleteUser(userId); + return ApiResponse.builder() + .result(manageDatabase.getHandleDbRequests().deleteUserRequest(userId)) + .build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } @@ -401,9 +401,7 @@ private BasicTextEncryptor getJasyptEncryptor() { return textEncryptor; } - public Map addNewUser(UserInfoModel newUser, boolean isExternal) - throws KlawException { - Map resMap = new HashMap<>(); + public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws KlawException { log.info("addNewUser {} {} {}", newUser.getUsername(), newUser.getTeam(), newUser.getRole()); if ("saas".equals(kwInstallationType)) { @@ -411,16 +409,14 @@ public Map addNewUser(UserInfoModel newUser, boolean isExternal) Pattern p = Pattern.compile(regex); Matcher m = p.matcher(newUser.getUsername()); if (!m.matches()) { - resMap.put("result", "Invalid mail id"); - return resMap; + return ApiResponse.builder().result("Invalid mail id").build(); } } else { String regex = "^[a-zA-Z0-9]{3,}$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(newUser.getUsername()); if (!m.matches()) { - resMap.put("result", "Invalid username"); - return resMap; + return ApiResponse.builder().result("Invalid username").build(); } } @@ -439,8 +435,7 @@ public Map addNewUser(UserInfoModel newUser, boolean isExternal) if (isExternal && commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { - resMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) newUser.setRole("NA"); @@ -480,13 +475,11 @@ public Map addNewUser(UserInfoModel newUser, boolean isExternal) dbHandle, commonUtilsService.getLoginUrl()); } - resMap.put("result", result); - return resMap; + return ApiResponse.builder().result(result).build(); } catch (Exception e) { inMemoryUserDetailsManager.deleteUser(newUser.getUsername()); if (e.getMessage().contains("should not exist")) { - resMap.put("result", "Failure. User already exists."); - return resMap; + return ApiResponse.builder().result("Failure. User already exists.").build(); } else { log.error("Error ", e); throw new KlawException("Unable to create the user."); @@ -494,13 +487,13 @@ public Map addNewUser(UserInfoModel newUser, boolean isExternal) } } - public String addNewTeam(TeamModel newTeam, boolean isExternal) { + public ApiResponse addNewTeam(TeamModel newTeam, boolean isExternal) throws KlawException { log.info("addNewTeam {}", newTeam); if (isExternal && commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); int tenantId; if (isExternal) { @@ -510,30 +503,30 @@ public String addNewTeam(TeamModel newTeam, boolean isExternal) { Team team = new Team(); copyProperties(newTeam, team); - String envListStrCommaSeperated; + if (newTeam.getEnvList() != null && newTeam.getEnvList().size() > 0) { envListStrCommaSeperated = String.join(",", newTeam.getEnvList().toArray(new String[0])); team.setRequestTopicsEnvs(envListStrCommaSeperated); } try { String res = manageDatabase.getHandleDbRequests().addNewTeam(team); - if ("success".equals(res)) { + if (ApiResultStatus.SUCCESS.value.equals(res)) { commonUtilsService.updateMetadata(tenantId, EntityType.TEAM, MetadataOperationType.CREATE); } - return "{\"result\":\"" + res + "\"}"; + return ApiResponse.builder().result(res).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } - public String updateTeam(TeamModel updatedTeam) { + public ApiResponse updateTeam(TeamModel updatedTeam) throws KlawException { log.info("updateTeam {}", updatedTeam); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); int tenantId = commonUtilsService.getTenantId(getUserName()); Team team = new Team(); @@ -549,22 +542,22 @@ public String updateTeam(TeamModel updatedTeam) { try { String res = manageDatabase.getHandleDbRequests().updateTeam(team); commonUtilsService.updateMetadata(tenantId, EntityType.TEAM, MetadataOperationType.UPDATE); - return "{\"result\":\"" + res + "\"}"; + return ApiResponse.builder().result(res).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } - public String changePwd(String changePwd) { + public ApiResponse changePwd(String changePwd) throws KlawException { if ("ldap".equals(authenticationType) || "ad".equals(authenticationType)) { - return "{\"result\":\" Password cannot be updated in ldap/ad authentication mode. \"}"; + return ApiResponse.builder() + .result("Password cannot be updated in ldap/ad authentication mode.") + .build(); } String userDetails = getUserName(); - GsonJsonParser jsonParser = new GsonJsonParser(); Map pwdMap = jsonParser.parseMap(changePwd); - String pwdChange = (String) pwdMap.get("pwd"); try { @@ -573,12 +566,15 @@ public String changePwd(String changePwd) { UserDetails updatePwdUserDetails = inMemoryUserDetailsManager.loadUserByUsername(userDetails); inMemoryUserDetailsManager.updatePassword(updatePwdUserDetails, encoder.encode(pwdChange)); - return "{\"result\":\"" - + manageDatabase.getHandleDbRequests().updatePassword(userDetails, encodePwd(pwdChange)) - + "\"}"; + return ApiResponse.builder() + .result( + manageDatabase + .getHandleDbRequests() + .updatePassword(userDetails, encodePwd(pwdChange))) + .build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } @@ -659,7 +655,7 @@ private String getUserName() { } Map addTwoDefaultTeams( - String teamContactPerson, String newTenantName, Integer tenantId) { + String teamContactPerson, String newTenantName, Integer tenantId) throws KlawException { Map teamAddMap = new HashMap<>(); TeamModel teamModel = new TeamModel(); @@ -668,8 +664,8 @@ Map addTwoDefaultTeams( teamModel.setTeamname(KwConstants.INFRATEAM); teamModel.setContactperson(teamContactPerson); - String addTeamRes = addNewTeam(teamModel, false); - teamAddMap.put("team1result", addTeamRes); + ApiResponse addTeamRes = addNewTeam(teamModel, false); + teamAddMap.put("team1result", addTeamRes.getResult()); TeamModel teamModel1 = new TeamModel(); teamModel1.setTenantId(tenantId); @@ -677,25 +673,24 @@ Map addTwoDefaultTeams( teamModel1.setTeamname(KwConstants.STAGINGTEAM); teamModel1.setContactperson(teamContactPerson); - String addTeamRes2 = addNewTeam(teamModel1, false); - teamAddMap.put("team2result", addTeamRes2); + ApiResponse addTeamRes2 = addNewTeam(teamModel1, false); + teamAddMap.put("team2result", addTeamRes2.getResult()); return teamAddMap; } - public Map registerUser(RegisterUserInfoModel newUser, boolean isExternal) + public ApiResponse registerUser(RegisterUserInfoModel newUser, boolean isExternal) throws Exception { log.info("registerUser {}", newUser.getUsername()); - Map result = new HashMap<>(); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); // check if user exists List userList = manageDatabase.getHandleDbRequests().selectAllUsersAllTenants(); if (userList.stream() .anyMatch(user -> Objects.equals(user.getUsername(), newUser.getMailid()))) { - throw new KlawException("User already exists."); + return ApiResponse.builder().result("User already exists.").build(); } else if (userList.stream() .anyMatch(user -> Objects.equals(user.getUsername(), newUser.getUsername()))) { - throw new KlawException("User already exists."); + return ApiResponse.builder().result("User already exists.").build(); } // check if registration exists @@ -703,10 +698,10 @@ public Map registerUser(RegisterUserInfoModel newUser, boolean i manageDatabase.getHandleDbRequests().selectAllRegisterUsersInfo(); if (registerUserInfoList.stream() .anyMatch(user -> user.getUsername().equals(newUser.getMailid()))) { - throw new KlawException("User already exists."); + return ApiResponse.builder().result("User already exists.").build(); } else if (registerUserInfoList.stream() .anyMatch(user -> user.getUsername().equals(newUser.getUsername()))) { - throw new KlawException("User already exists."); + return ApiResponse.builder().result("User already exists.").build(); } try { @@ -753,27 +748,25 @@ public Map registerUser(RegisterUserInfoModel newUser, boolean i } } catch (Exception e) { log.error("Exception:", e); - throw new KlawException("Invalid tenant provided."); + return ApiResponse.builder().result("Invalid tenant provided.").build(); } } } String resultRegister = dbHandle.registerUser(registerUserInfo); - if (resultRegister.contains("Failure")) - throw new KlawException("Registration already exists."); - - result.put("result", resultRegister); + return ApiResponse.builder().result("Registration already exists.").build(); if (isExternal) { mailService.sendMailRegisteredUser( registerUserInfo, dbHandle, commonUtilsService.getLoginUrl()); } + + return ApiResponse.builder().result(resultRegister).build(); } catch (Exception e) { log.error("Exception:", e); throw new KlawException("Failure. Something went wrong. Please try later."); } - return result; } public List getNewUserRequests() { @@ -801,15 +794,15 @@ public List getNewUserRequests() { return registerUserInfoModels; } - public String approveNewUserRequests( - String username, boolean isExternal, int tenantId, String teamName) { + public ApiResponse approveNewUserRequests( + String username, boolean isExternal, int tenantId, String teamName) throws KlawException { log.info("approveNewUserRequests {}", username); String userDetails = getUserName(); if (isExternal && commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); try { @@ -819,12 +812,6 @@ public String approveNewUserRequests( registerUserInfo.setTenantId(tenantId); registerUserInfo.setTeamId(manageDatabase.getTeamIdFromTeamName(tenantId, teamName)); } - // if(kwInstallationType.equals("saas")){ //from saas new user requests for not - // tenant owners - join thru tenant id - // tenantId = registerUserInfo.getTenantId(); - // registerUserInfo.setTeamId(manageDatabase.getTeamIdFromTeamName(tenantId, - // STAGINGTEAM)); - // } tenantId = registerUserInfo.getTenantId(); @@ -842,32 +829,34 @@ public String approveNewUserRequests( else userInfo.setUserPassword(""); userInfo.setMailid(registerUserInfo.getMailid()); - Map result = addNewUser(userInfo, isExternal); - if (result.get("result").contains("success")) + ApiResponse resultResp = addNewUser(userInfo, isExternal); + if (resultResp.getResult().contains("success")) dbHandle.updateNewUserRequest(username, userDetails, true); - else return "{\"result\":\"failure\"}"; - return "{\"result\":\"success\"}"; + else { + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure\"}"; + throw new KlawException(e.getMessage()); } } - public String declineNewUserRequests(String username) { + public ApiResponse declineNewUserRequests(String username) throws KlawException { log.info("declineNewUserRequests {}", username); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); try { dbHandle.updateNewUserRequest(username, userDetails, false); - return "{\"result\":\"success\"}"; + return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure\"}"; + throw new KlawException(e.getMessage()); } } diff --git a/src/main/resources/static/js/syncBackTopics.js b/src/main/resources/static/js/syncBackTopics.js index 0031d609ca..4c453e5014 100644 --- a/src/main/resources/static/js/syncBackTopics.js +++ b/src/main/resources/static/js/syncBackTopics.js @@ -357,7 +357,7 @@ app.controller("syncBackTopicsCtrl", function($scope, $http, $location, $window) $scope.alert = "Sync back topic request : "+ output.result[0]; if(output.result[0] == "success"){ $scope.resetCheckBoxes(); - $scope.syncbacklog = output.syncbacklog; + $scope.syncbacklog = output.data; $scope.alert = $scope.alert + ". Errors are ignored if topics already exist on the target environment. Please verify logs."; } if(output.result[0] == 'success'){ diff --git a/src/main/resources/static/js/syncConnectors.js b/src/main/resources/static/js/syncConnectors.js index ff77c1af7c..ab90a37387 100644 --- a/src/main/resources/static/js/syncConnectors.js +++ b/src/main/resources/static/js/syncConnectors.js @@ -523,7 +523,7 @@ app.controller("syncConnectorsCtrl", function($scope, $http, $location, $window) if(output.result == 'success'){ $scope.resetCheckBoxes(); - $scope.syncbulklog = output.syncbulklog; + $scope.syncbulklog = output.data; $scope.alertbulk = $scope.alertbulk + ". Please verify logs below."; swal({ diff --git a/src/main/resources/static/js/synchronizeTopics.js b/src/main/resources/static/js/synchronizeTopics.js index 866e340402..5107321caa 100644 --- a/src/main/resources/static/js/synchronizeTopics.js +++ b/src/main/resources/static/js/synchronizeTopics.js @@ -495,7 +495,7 @@ app.controller("synchronizeTopicsCtrl", function($scope, $http, $location, $wind if(output.result == 'success'){ $scope.resetCheckBoxes(); - $scope.syncbulklog = output.syncbulklog; + $scope.syncbulklog = output.data; $scope.alertbulk = $scope.alertbulk + ". Please verify logs below."; swal({ diff --git a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java index 422198fa29..a21b7131fe 100644 --- a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java +++ b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.TeamModel; import io.aiven.klaw.model.UserInfoModel; @@ -149,8 +150,9 @@ public void createSameTeamAgainFailure() throws Exception { .andReturn() .getResponse() .getContentAsString(); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(response).contains("Failure. Team already exists"); + assertThat(objectResponse.getResult()).contains("Failure. Team already exists"); } // Create team failure, invalid team mail id diff --git a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java index dd1f1d8507..5a0e0f3913 100644 --- a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java @@ -12,6 +12,7 @@ import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SyncAclUpdates; import io.aiven.klaw.model.TopicOverview; import io.aiven.klaw.service.AclControllerService; @@ -66,7 +67,7 @@ public void setup() { public void createAcl() throws Exception { AclRequestsModel addAclRequest = utilMethods.getAclRequestModel(topicName + topicId); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(addAclRequest); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(aclControllerService.createAcl(any())).thenReturn(apiResponse); String response = diff --git a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java index 6eaaaac752..11be53819d 100644 --- a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java @@ -96,9 +96,8 @@ public void createTopics() throws Exception { public void updateSyncTopics() throws Exception { List syncTopicUpdates = utilMethods.getSyncTopicUpdates(); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(syncTopicUpdates); - Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); - when(topicSyncControllerService.updateSyncTopics(any())).thenReturn(resultMap); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(topicSyncControllerService.updateSyncTopics(any())).thenReturn(apiResponse); String response = mvcSync @@ -112,10 +111,9 @@ public void updateSyncTopics() throws Exception { .getResponse() .getContentAsString(); - Map actualResult = - new ObjectMapper().readValue(response, new TypeReference<>() {}); + ApiResponse actualResult = new ObjectMapper().readValue(response, new TypeReference<>() {}); - assertThat(actualResult).containsEntry("result", "success"); + assertThat(actualResult.getResult()).isEqualTo("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java b/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java index ce2fa9616a..38f236df96 100644 --- a/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java @@ -13,6 +13,8 @@ import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.Team; import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.TeamModel; @@ -260,7 +262,8 @@ public void deleteEnv() throws Exception { @Test @Order(10) public void deleteTeam() throws Exception { - when(usersTeamsControllerService.deleteTeam(any())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); + when(usersTeamsControllerService.deleteTeam(any())).thenReturn(apiResponse); String response = mvcUserTeams @@ -273,14 +276,16 @@ public void deleteTeam() throws Exception { .andReturn() .getResponse() .getContentAsString(); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(response).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test @Order(11) public void deleteUser() throws Exception { - when(usersTeamsControllerService.deleteUser(anyString(), anyBoolean())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(usersTeamsControllerService.deleteUser(anyString(), anyBoolean())).thenReturn(apiResponse); String response = mvcUserTeams @@ -294,17 +299,17 @@ public void deleteUser() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo("success"); } @Test @Order(12) public void addNewUser() throws Exception { - Map result = new HashMap<>(); - result.put("result", "success"); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); UserInfoModel userInfo = utilMethods.getUserInfoMock(); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(userInfo); - when(usersTeamsControllerService.addNewUser(any(), anyBoolean())).thenReturn(result); + when(usersTeamsControllerService.addNewUser(any(), anyBoolean())).thenReturn(apiResponse); String response = mvcUserTeams @@ -326,8 +331,8 @@ public void addNewUser() throws Exception { public void addNewTeam() throws Exception { Team team = utilMethods.getTeams().get(0); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(team); - String result = "{ \"status\": \"" + "success" + "\" }"; - when(usersTeamsControllerService.addNewTeam(any(), anyBoolean())).thenReturn(result); + ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + when(usersTeamsControllerService.addNewTeam(any(), anyBoolean())).thenReturn(apiResponse); String response = mvcUserTeams @@ -347,7 +352,8 @@ public void addNewTeam() throws Exception { @Test @Order(14) public void changePwd() throws Exception { - when(usersTeamsControllerService.changePwd(any())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); + when(usersTeamsControllerService.changePwd(any())).thenReturn(apiResponse); String response = mvcUserTeams @@ -361,7 +367,7 @@ public void changePwd() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).isEqualTo("success"); + assertThat(response).contains("success"); } @Test diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index 29931841ef..c65200e905 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -18,6 +18,7 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwTenantConfigModel; import io.aiven.klaw.model.SyncTopicUpdates; import io.aiven.klaw.model.TopicInfo; @@ -211,7 +212,7 @@ public void createTopicsFailure1() throws KlawException { @Test @Order(7) - public void updateSyncTopicsSuccess() { + public void updateSyncTopicsSuccess() throws KlawException { stubUserInfo(); when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); @@ -221,15 +222,15 @@ public void updateSyncTopicsSuccess() { .thenReturn(Collections.singletonList("1")); when(handleDbRequests.addToSynctopics(any())).thenReturn("success"); - Map result = + ApiResponse result = topicSyncControllerService.updateSyncTopics(utilMethods.getSyncTopicUpdates()); - assertThat(result).containsEntry("result", "success"); + assertThat(result.getResult()).isEqualTo("success"); } @Test @Order(8) - public void updateSyncTopicsNoUpdate() { + public void updateSyncTopicsNoUpdate() throws KlawException { List topicUpdates = new ArrayList<>(); stubUserInfo(); @@ -240,22 +241,22 @@ public void updateSyncTopicsNoUpdate() { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - Map result = topicSyncControllerService.updateSyncTopics(topicUpdates); + ApiResponse result = topicSyncControllerService.updateSyncTopics(topicUpdates); - assertThat(result).containsEntry("result", "No record updated."); + assertThat(result.getResult()).isEqualTo("No record updated."); } @Test @Order(9) - public void updateSyncTopicsNotAuthorized() { + public void updateSyncTopicsNotAuthorized() throws KlawException { stubUserInfo(); when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); - Map result = + ApiResponse result = topicSyncControllerService.updateSyncTopics(utilMethods.getSyncTopicUpdates()); - assertThat(result).containsEntry("result", "Not Authorized."); + assertThat(result.getResult()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); } @Test From ac511722d17b37cfd766d342d24d1d94510ef875 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Wed, 5 Oct 2022 13:53:00 +0200 Subject: [PATCH 10/15] Updating response on front end in case of validation errors --- src/main/resources/static/js/analytics.js | 12 +++---- src/main/resources/static/js/browseAcls.js | 20 ++++++------ src/main/resources/static/js/browseTopics.js | 32 +++++++++---------- .../resources/static/js/connectorOverview.js | 22 +++++++------ src/main/resources/static/js/envs.js | 30 +++++++++-------- src/main/resources/static/js/execAcls.js | 4 +-- .../resources/static/js/execConnectors.js | 4 +-- src/main/resources/static/js/execSchemas.js | 4 +-- src/main/resources/static/js/manageUsers.js | 19 +++++------ src/main/resources/static/js/modifyEnvs.js | 26 ++++++++------- src/main/resources/static/js/modifyTeam.js | 16 ++++++---- src/main/resources/static/js/modifyUser.js | 18 ++++++----- src/main/resources/static/js/myRequests.js | 32 ++++++++++--------- src/main/resources/static/js/registerUsers.js | 30 +++++++++-------- src/main/resources/static/js/requestAcls.js | 16 ++++++---- .../static/js/requestAvroSchemaUpload.js | 24 +++++++------- .../resources/static/js/requestConnector.js | 26 ++++++++------- src/main/resources/static/js/requestTopics.js | 26 ++++++++------- src/main/resources/static/js/rolesperms.js | 24 +++++++------- src/main/resources/static/js/serverConfig.js | 28 ++++++++-------- src/main/resources/static/js/syncBackAcls.js | 6 ++-- .../resources/static/js/syncBackTopics.js | 10 +++--- .../resources/static/js/synchronizeAcls.js | 2 +- .../resources/static/js/synchronizeTopics.js | 4 +-- 24 files changed, 232 insertions(+), 203 deletions(-) diff --git a/src/main/resources/static/js/analytics.js b/src/main/resources/static/js/analytics.js index b4979ace3b..c12db64f93 100644 --- a/src/main/resources/static/js/analytics.js +++ b/src/main/resources/static/js/analytics.js @@ -139,7 +139,7 @@ app.controller("showAnalyticsCtrl", function($scope, $http, $location, $window) $scope.checkPendingApprovals = function() { - if($scope.dashboardDetails.pendingApprovalsRedirectionPage == '') + if($scope.dashboardDetails.pendingApprovalsRedirectionPage === '') return; var sPageURL = window.location.search.substring(1); @@ -148,14 +148,14 @@ app.controller("showAnalyticsCtrl", function($scope, $http, $location, $window) for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); - if (sParameterName[0] == "loggedin") + if (sParameterName[0] === "loggedin") { foundLoggedInVar = "true"; - if(sParameterName[1] != "true") + if(sParameterName[1] !== "true") return; } } - if(foundLoggedInVar == "true") + if(foundLoggedInVar === "true") $scope.redirectToPendingReqs($scope.dashboardDetails.pendingApprovalsRedirectionPage); } @@ -180,9 +180,9 @@ app.controller("showAnalyticsCtrl", function($scope, $http, $location, $window) return; if(!$scope.contactFormMessage) return; - if($scope.contactFormSubject.trim().length==0) + if($scope.contactFormSubject.trim().length===0) return; - if($scope.contactFormMessage.trim().length==0) + if($scope.contactFormMessage.trim().length===0) return; $http({ diff --git a/src/main/resources/static/js/browseAcls.js b/src/main/resources/static/js/browseAcls.js index fe575dbb4e..73863f78c5 100644 --- a/src/main/resources/static/js/browseAcls.js +++ b/src/main/resources/static/js/browseAcls.js @@ -46,16 +46,18 @@ app.controller("browseAclsCtrl", function($scope, $http, $location, $window) { $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.getEnvs = function() { diff --git a/src/main/resources/static/js/browseTopics.js b/src/main/resources/static/js/browseTopics.js index 684c6a7caa..3a8003abef 100644 --- a/src/main/resources/static/js/browseTopics.js +++ b/src/main/resources/static/js/browseTopics.js @@ -67,7 +67,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { $scope.notificationsSchemas = output.notificationsSchemas; $scope.notificationsUsers = output.notificationsUsers; - if(output.viewTopics!='Authorized') + if(output.viewTopics!=='Authorized') { $window.location.href = $window.location.origin + $scope.dashboardDetails.contextPath + "/index"; } @@ -112,7 +112,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { $scope.checkPendingApprovals = function() { - if($scope.dashboardDetails.pendingApprovalsRedirectionPage == '') + if($scope.dashboardDetails.pendingApprovalsRedirectionPage === '') return; var sPageURL = window.location.search.substring(1); @@ -121,14 +121,14 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); - if (sParameterName[0] == "loggedin") + if (sParameterName[0] === "loggedin") { foundLoggedInVar = "true"; - if(sParameterName[1] != "true") + if(sParameterName[1] !== "true") return; } } - if(foundLoggedInVar == "true") + if(foundLoggedInVar === "true") $scope.redirectToPendingReqs($scope.dashboardDetails.pendingApprovalsRedirectionPage); } @@ -161,7 +161,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { var teamSel = $scope.getTopics.team; var topicType = null; - if(fromSelect == "false") + if(fromSelect === "false") { var envSelected; @@ -170,7 +170,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); - if (sParameterName[0] == "envSelected") + if (sParameterName[0] === "envSelected") { envSelected = sParameterName[1]; serviceInput['env'] = envSelected; @@ -178,7 +178,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { $scope.getTopics.envName = envSelected; }else return; } - }else if(fromSelect == "true"){ + }else if(fromSelect === "true"){ if(!$scope.getTopics.envName) envSelected = "ALL"; else @@ -194,17 +194,17 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); - if (sParameterName[0] == "team") + if (sParameterName[0] === "team") { teamSel = sParameterName[1]; window.history.pushState({}, document.title, "browseTopics"); $scope.getTopics.team = teamSel; } - else if (sParameterName[0] == "producer") + else if (sParameterName[0] === "producer") { topicType = 'Producer'; } - else if (sParameterName[0] == "consumer") + else if (sParameterName[0] === "consumer") { topicType = 'Consumer'; } @@ -224,7 +224,7 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { } var getTopicsUrl = ""; - if(topicsDisplayType == 'grid') + if(topicsDisplayType === 'grid') getTopicsUrl = "getTopics"; else getTopicsUrl = "getTopicsRowView"; @@ -241,8 +241,8 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { } }).success(function(output) { $scope.resultBrowse = output; - if(output!=null && output.length !=0){ - if(topicsDisplayType == "grid"){ + if(output!=null && output.length !==0){ + if(topicsDisplayType === "grid"){ $scope.currentPageSelected = output[0][0].currentPage; $scope.resultPages = output[0][0].allPageNos; } @@ -272,9 +272,9 @@ app.controller("browseTopicsCtrl", function($scope, $http, $location, $window) { return; if(!$scope.contactFormMessage) return; - if($scope.contactFormSubject.trim().length==0) + if($scope.contactFormSubject.trim().length===0) return; - if($scope.contactFormMessage.trim().length==0) + if($scope.contactFormMessage.trim().length===0) return; $http({ diff --git a/src/main/resources/static/js/connectorOverview.js b/src/main/resources/static/js/connectorOverview.js index 81b2a5e2cd..9c70372ab1 100644 --- a/src/main/resources/static/js/connectorOverview.js +++ b/src/main/resources/static/js/connectorOverview.js @@ -46,16 +46,18 @@ app.controller("connectorOverviewCtrl", function($scope, $http, $location, $wind $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.getEnvs = function() { @@ -198,7 +200,7 @@ app.controller("connectorOverviewCtrl", function($scope, $http, $location, $wind 'env' : env}, }).success(function(output) { - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Connector Delete Request : "+output.result, diff --git a/src/main/resources/static/js/envs.js b/src/main/resources/static/js/envs.js index 841a7a177b..f5920bddf7 100644 --- a/src/main/resources/static/js/envs.js +++ b/src/main/resources/static/js/envs.js @@ -53,18 +53,20 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ $scope.alert = error.errors[0].defaultMessage; }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = "Unable to process the request."; + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; $scope.alertnote = $scope.alert; $scope.showAlertToast(); - } + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -138,7 +140,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { showConfirmButton: false }); - if(output.result == 'success'){ + if(output.result === 'success'){ $scope.getEnvsPaginated(1); $scope.getSchemaRegEnvs(); $scope.getKafkaConnectEnvs(); @@ -319,7 +321,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { headers : { 'Content-Type' : 'application/json' } }).success(function(output) { $scope.alert = "Delete Tenant Request : "+output.result; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "Delete Tenant Request : "+output.result, @@ -378,7 +380,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { data: {'orgName' : orgName} }).success(function(output) { $scope.alert = "Update Tenant Request : "+output.result; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "Update Tenant Request : "+output.result, @@ -418,7 +420,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { data: {'selectedTenantExtensionPeriod' : $scope.selectedTenantExtensionPeriod} }).success(function(output) { $scope.alert = "Update Tenant extension Request : "+output.result; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "Update Tenant extension Request : "+output.result + ". You will hear from us very soon. Thank you !!", @@ -557,7 +559,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { data: {'clusterId' : idval} }).success(function(output) { $scope.alert = "Delete Cluster Request : "+output.result; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "Delete Cluster Request : "+output.result, @@ -601,7 +603,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { data: {'envId' : idval} }).success(function(output) { $scope.alert = "Delete Environment Request : "+output.result; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "Delete Environment Request : "+output.result, @@ -717,7 +719,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { $scope.addNewCluster.envname = ""; $scope.addNewCluster.host = ""; $scope.addNewCluster.pubKeyFile = ""; - if(output.result=='success'){ + if(output.result==='success'){ swal({ title: "", text: "New cluster added : "+output.result, diff --git a/src/main/resources/static/js/execAcls.js b/src/main/resources/static/js/execAcls.js index 83a7a9827a..18690cc40c 100644 --- a/src/main/resources/static/js/execAcls.js +++ b/src/main/resources/static/js/execAcls.js @@ -218,7 +218,7 @@ app.controller("execAclsCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Acl Approve Request : "+output.result; $scope.getMyAclRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Subscription Approve Request : "+output.result, @@ -303,7 +303,7 @@ app.controller("execAclsCtrl", function($scope, $http, $location, $window) { $scope.showDeclinePanel = "false"; $scope.reqForDecline = ""; $scope.getMyAclRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Subscription Decline Request : "+output.result, diff --git a/src/main/resources/static/js/execConnectors.js b/src/main/resources/static/js/execConnectors.js index 69866c084d..5a81a4cabc 100644 --- a/src/main/resources/static/js/execConnectors.js +++ b/src/main/resources/static/js/execConnectors.js @@ -128,7 +128,7 @@ app.controller("execConnectorsCtrl", function($scope, $http, $location, $window) $scope.alert = "Connector Approve Request : "+output.result; $scope.getMyConnectorRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Connector Approve Request : "+output.result, @@ -212,7 +212,7 @@ app.controller("execConnectorsCtrl", function($scope, $http, $location, $window) $scope.showDeclinePanel = "false"; $scope.topicForDecline = ""; $scope.getMyConnectorRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Connector Decline Request : "+output.result, diff --git a/src/main/resources/static/js/execSchemas.js b/src/main/resources/static/js/execSchemas.js index a531977278..56b983924c 100644 --- a/src/main/resources/static/js/execSchemas.js +++ b/src/main/resources/static/js/execSchemas.js @@ -121,7 +121,7 @@ app.controller("execSchemasCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Schema Approve Request : " + output.result; $scope.getMySchemaRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Schema Approve Request : "+output.result, @@ -205,7 +205,7 @@ app.controller("execSchemasCtrl", function($scope, $http, $location, $window) { $scope.showDeclinePanel = "false"; $scope.topicForDecline = ""; $scope.getMySchemaRequests(1, false); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Schema Decline Request : "+output.result, diff --git a/src/main/resources/static/js/manageUsers.js b/src/main/resources/static/js/manageUsers.js index d0874c10e5..de270c6ac1 100644 --- a/src/main/resources/static/js/manageUsers.js +++ b/src/main/resources/static/js/manageUsers.js @@ -30,10 +30,11 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { $scope.alert = error.errors[0].defaultMessage; }else if(error.message != null){ $scope.alert = error.message; - }else if(error.result != null){ + }else if(error.result != null){ $scope.alert = error.result; - } - else $scope.alert = "Unable to process the request."; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; $scope.alertnote = $scope.alert; $scope.showAlertToast(); @@ -140,7 +141,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { data: {'changePwd' : serviceInput} }).success(function(output) { $scope.alert = "Password changed : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Password changed : "+output.result, @@ -184,7 +185,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Delete Team Request : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Delete Team Request : "+output.result, @@ -228,7 +229,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { data: {'userId' : idval} }).success(function(output) { $scope.alert = "Delete User Request : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Delete User Request : "+output.result, @@ -278,7 +279,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { data: serviceInput }).success(function(output) { $scope.alert = "Update User Request : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Update User Request : "+output.result, @@ -489,7 +490,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { $scope.addNewUser.pwd = ""; $scope.addNewUser.reppwd = ""; $scope.addNewUser.emailid = ""; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "New User Request : "+output.result, @@ -555,7 +556,7 @@ app.controller("manageUsersCtrl", function($scope, $http, $location, $window) { data: serviceInput }).success(function(output) { $scope.alert = "New User Request : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ $scope.addNewUser.username = ""; $scope.addNewUser.fullname = ""; $scope.addNewUser.emailid = ""; diff --git a/src/main/resources/static/js/modifyEnvs.js b/src/main/resources/static/js/modifyEnvs.js index a14874d08a..4db1ef1f8b 100644 --- a/src/main/resources/static/js/modifyEnvs.js +++ b/src/main/resources/static/js/modifyEnvs.js @@ -25,18 +25,20 @@ app.controller("modifyEnvsCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); diff --git a/src/main/resources/static/js/modifyTeam.js b/src/main/resources/static/js/modifyTeam.js index f789543045..fddd847eac 100644 --- a/src/main/resources/static/js/modifyTeam.js +++ b/src/main/resources/static/js/modifyTeam.js @@ -25,18 +25,20 @@ app.controller("modifyTeamCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ $scope.alert = error.errors[0].defaultMessage; }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; $scope.alertnote = $scope.alert; $scope.showAlertToast(); - } + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); diff --git a/src/main/resources/static/js/modifyUser.js b/src/main/resources/static/js/modifyUser.js index ac673c6219..45eefde2ac 100644 --- a/src/main/resources/static/js/modifyUser.js +++ b/src/main/resources/static/js/modifyUser.js @@ -25,18 +25,20 @@ app.controller("modifyUserCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ $scope.alert = error.errors[0].defaultMessage; }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; $scope.alertnote = $scope.alert; $scope.showAlertToast(); - } + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -189,7 +191,7 @@ app.controller("modifyUserCtrl", function($scope, $http, $location, $window) { data: serviceInput }).success(function(output) { $scope.alert = "User update request : "+output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "User update request : "+output.result, diff --git a/src/main/resources/static/js/myRequests.js b/src/main/resources/static/js/myRequests.js index 20089857de..6e01c8ab7e 100644 --- a/src/main/resources/static/js/myRequests.js +++ b/src/main/resources/static/js/myRequests.js @@ -25,18 +25,20 @@ app.controller("myRequestsCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.refreshPage = function(){ $window.location.reload(); @@ -410,7 +412,7 @@ app.controller("myRequestsCtrl", function($scope, $http, $location, $window) { data: {'connectorId' : topicId } }).success(function(output) { $scope.alert = "Request deleted : " + output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Request deleted : "+output.result, @@ -454,7 +456,7 @@ app.controller("myRequestsCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Request deleted : "+output.result; $scope.getMyAclRequests(1, true); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Request deleted : "+output.result, @@ -496,7 +498,7 @@ app.controller("myRequestsCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Request deleted : "+output.result; $scope.getMySchemaRequests(1, true); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Request deleted : "+output.result, diff --git a/src/main/resources/static/js/registerUsers.js b/src/main/resources/static/js/registerUsers.js index 43e676341a..6fac53b27e 100644 --- a/src/main/resources/static/js/registerUsers.js +++ b/src/main/resources/static/js/registerUsers.js @@ -25,18 +25,20 @@ app.controller("registerUsersCtrl", function($scope, $http, $location, $window) }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = "Sorry, unable to process the request."; + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -237,7 +239,7 @@ app.controller("registerUsersCtrl", function($scope, $http, $location, $window) $scope.alert = "User Approve Request : "+output.result; $scope.getUserRequests(); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "User Approve Request : "+output.result, @@ -266,7 +268,7 @@ app.controller("registerUsersCtrl", function($scope, $http, $location, $window) $scope.alert = "User decline Request : "+output.result; $scope.getUserRequests(); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "User decline Request : "+output.result, @@ -380,7 +382,7 @@ app.controller("registerUsersCtrl", function($scope, $http, $location, $window) headers : { 'Content-Type' : 'application/json' }, data: serviceInput }).success(function(output) { - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Registration Request : "+output.result, @@ -476,7 +478,7 @@ app.controller("registerUsersCtrl", function($scope, $http, $location, $window) headers : { 'Content-Type' : 'application/json' }, data: serviceInput }).success(function(output) { - if(output.result == 'success'){ + if(output.result === 'success'){ $scope.alert = "Registration Request : "+output.result; swal({ title: "", diff --git a/src/main/resources/static/js/requestAcls.js b/src/main/resources/static/js/requestAcls.js index a251d4cbc8..a31d79eb24 100644 --- a/src/main/resources/static/js/requestAcls.js +++ b/src/main/resources/static/js/requestAcls.js @@ -35,18 +35,20 @@ app.controller("requestAclsCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ - if(error.errors != null && error.errors.length > 0){ + $scope.handleValidationErrors = function(error){ + if(error.errors != null && error.errors.length > 0){ $scope.alert = error.errors[0].defaultMessage; }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; $scope.alertnote = $scope.alert; $scope.showAlertToast(); - } + } $scope.TopReqTypeList = [ { label: 'Producer', value: 'Producer' }, { label: 'Consumer', value: 'Consumer' } ]; diff --git a/src/main/resources/static/js/requestAvroSchemaUpload.js b/src/main/resources/static/js/requestAvroSchemaUpload.js index f626e0cef5..373cc60a04 100644 --- a/src/main/resources/static/js/requestAvroSchemaUpload.js +++ b/src/main/resources/static/js/requestAvroSchemaUpload.js @@ -47,18 +47,20 @@ app.controller("requestSchemaCtrl", function($scope, $http, $location, $window) }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); diff --git a/src/main/resources/static/js/requestConnector.js b/src/main/resources/static/js/requestConnector.js index 350f4401de..878e2889b5 100644 --- a/src/main/resources/static/js/requestConnector.js +++ b/src/main/resources/static/js/requestConnector.js @@ -25,18 +25,20 @@ app.controller("requestConnectorCtrl", function($scope, $http, $location, $windo }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -189,7 +191,7 @@ app.controller("requestConnectorCtrl", function($scope, $http, $location, $windo params: {'addConnectorRequest' : serviceInput }, data: serviceInput }).success(function(output) { - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "Awesome !", text: "Connector Request : "+output.result, diff --git a/src/main/resources/static/js/requestTopics.js b/src/main/resources/static/js/requestTopics.js index 9039429226..e992315b41 100644 --- a/src/main/resources/static/js/requestTopics.js +++ b/src/main/resources/static/js/requestTopics.js @@ -25,18 +25,20 @@ app.controller("requestTopicsCtrl", function($scope, $http, $location, $window) }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -268,7 +270,7 @@ app.controller("requestTopicsCtrl", function($scope, $http, $location, $window) params: {'addTopicRequest' : serviceInput }, data: serviceInput }).success(function(output) { - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "Awesome !", text: "Topic Request : "+output.result, diff --git a/src/main/resources/static/js/rolesperms.js b/src/main/resources/static/js/rolesperms.js index 25dad543c7..9e180a189f 100644 --- a/src/main/resources/static/js/rolesperms.js +++ b/src/main/resources/static/js/rolesperms.js @@ -25,18 +25,20 @@ app.controller("rolesPermsCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); diff --git a/src/main/resources/static/js/serverConfig.js b/src/main/resources/static/js/serverConfig.js index f10b2cc337..c288cf9a5b 100644 --- a/src/main/resources/static/js/serverConfig.js +++ b/src/main/resources/static/js/serverConfig.js @@ -25,18 +25,20 @@ app.controller("serverConfigCtrl", function($scope, $http, $location, $window) { }); } - $scope.handleValidationErrors = function(error){ + $scope.handleValidationErrors = function(error){ if(error.errors != null && error.errors.length > 0){ - $scope.alert = error.errors[0].defaultMessage; - }else if(error.message != null){ - $scope.alert = error.message; - }else if(error.result != null){ - $scope.alert = error.result; - }else $scope.alert = error; - - $scope.alertnote = $scope.alert; - $scope.showAlertToast(); - } + $scope.alert = error.errors[0].defaultMessage; + }else if(error.message != null){ + $scope.alert = error.message; + }else if(error.result != null){ + $scope.alert = error.result; + } + else + $scope.alert = "Unable to process the request. Please verify the request or contact our Administrator !!"; + + $scope.alertnote = $scope.alert; + $scope.showAlertToast(); + } $scope.showAlertToast = function() { var x = document.getElementById("alertbar"); @@ -84,7 +86,7 @@ app.controller("serverConfigCtrl", function($scope, $http, $location, $window) { headers : { 'Content-Type' : 'application/json' } }).success(function(output) { $scope.alert = "Stopping Klaw ..."; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Stopping Klaw ...", @@ -184,7 +186,7 @@ app.controller("serverConfigCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Property ("+ output.data +") update status : " + output.result; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Property Update status. ("+ output.data +") " + output.result, diff --git a/src/main/resources/static/js/syncBackAcls.js b/src/main/resources/static/js/syncBackAcls.js index 49ea11adff..afb9e488d8 100644 --- a/src/main/resources/static/js/syncBackAcls.js +++ b/src/main/resources/static/js/syncBackAcls.js @@ -290,15 +290,15 @@ app.controller("syncBackAclsCtrl", function($scope, $http, $location, $window) { data: serviceInput }).success(function(output) { $scope.ShowSpinnerStatus = false; - $scope.alert = "Sync back acls request : "+ output.result[0]; - if(output.result[0] == "success"){ + $scope.alert = "Sync back acls request : "+ output.result; + if(output.result === "success"){ $scope.resetCheckBoxes(); $scope.syncbacklog = output.data; $scope.alert = $scope.alert + ". Please verify logs."; swal({ title: "", - text: "Sync back subscriptions request : "+ output.result[0], + text: "Sync back subscriptions request : "+ output.result, timer: 2000, showConfirmButton: false }); diff --git a/src/main/resources/static/js/syncBackTopics.js b/src/main/resources/static/js/syncBackTopics.js index 4c453e5014..b8ea8e1ea6 100644 --- a/src/main/resources/static/js/syncBackTopics.js +++ b/src/main/resources/static/js/syncBackTopics.js @@ -343,7 +343,7 @@ app.controller("syncBackTopicsCtrl", function($scope, $http, $location, $window) closeOnConfirm: true, closeOnCancel: true }).then(function(isConfirm){ - if (isConfirm.dismiss != "cancel") { + if (isConfirm.dismiss !== "cancel") { $scope.ShowSpinnerStatus = true; @@ -354,16 +354,16 @@ app.controller("syncBackTopicsCtrl", function($scope, $http, $location, $window) data: serviceInput }).success(function(output) { $scope.ShowSpinnerStatus = false; - $scope.alert = "Sync back topic request : "+ output.result[0]; - if(output.result[0] == "success"){ + $scope.alert = "Sync back topic request : "+ output.result; + if(output.result === "success"){ $scope.resetCheckBoxes(); $scope.syncbacklog = output.data; $scope.alert = $scope.alert + ". Errors are ignored if topics already exist on the target environment. Please verify logs."; } - if(output.result[0] == 'success'){ + if(output.result === 'success'){ swal({ title: "", - text: "Sync back topic request : "+ output.result[0], + text: "Sync back topic request : "+ output.result, timer: 2000, showConfirmButton: false }); diff --git a/src/main/resources/static/js/synchronizeAcls.js b/src/main/resources/static/js/synchronizeAcls.js index 88eb5b6ee5..eb2912ae58 100644 --- a/src/main/resources/static/js/synchronizeAcls.js +++ b/src/main/resources/static/js/synchronizeAcls.js @@ -194,7 +194,7 @@ app.controller("synchronizeAclsCtrl", function($scope, $http, $location, $window $scope.updatedSyncArray = []; // $scope.getAcls(1); - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Acl Sync Request : "+output.result, diff --git a/src/main/resources/static/js/synchronizeTopics.js b/src/main/resources/static/js/synchronizeTopics.js index 5107321caa..92f734bb1f 100644 --- a/src/main/resources/static/js/synchronizeTopics.js +++ b/src/main/resources/static/js/synchronizeTopics.js @@ -261,7 +261,7 @@ app.controller("synchronizeTopicsCtrl", function($scope, $http, $location, $wind $scope.alert = "Topic Sync Request : "+output.result; $scope.updatedSyncArray = []; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", text: "Topic Sync Request : "+output.result, @@ -493,7 +493,7 @@ app.controller("synchronizeTopicsCtrl", function($scope, $http, $location, $wind $scope.alertbulk = "Topic Sync Bulk Request : "+output.result; $scope.updatedSyncArray = []; - if(output.result == 'success'){ + if(output.result === 'success'){ $scope.resetCheckBoxes(); $scope.syncbulklog = output.data; $scope.alertbulk = $scope.alertbulk + ". Please verify logs below."; From b74f6710265ee98c4f4e5a1268556dc993d3d1c9 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Wed, 5 Oct 2022 16:50:15 +0200 Subject: [PATCH 11/15] Updating enum values, apis for EnvController --- .../io/aiven/klaw/config/ManageDatabase.java | 2 +- .../EnvsClustersTenantsController.java | 59 +++-- .../controller/KafkaConnectController.java | 70 +++--- .../klaw/helpers/db/rdbms/DeleteDataJdbc.java | 47 ++-- .../klaw/helpers/db/rdbms/InsertDataJdbc.java | 49 ++-- .../klaw/helpers/db/rdbms/SelectDataJdbc.java | 23 +- .../klaw/helpers/db/rdbms/UpdateDataJdbc.java | 56 ++--- .../io/aiven/klaw/model/AclPatternType.java | 12 + .../aiven/klaw/model/AclPermissionType.java | 12 + ...ionType.java => RequestOperationType.java} | 5 +- .../klaw/model/cluster/ClusterAclRequest.java | 4 +- .../klaw/service/AclControllerService.java | 34 +-- .../service/AclSyncControllerService.java | 25 ++- .../service/AnalyticsControllerService.java | 11 +- .../aiven/klaw/service/ClusterApiService.java | 21 +- .../EnvsClustersTenantsControllerService.java | 210 +++++++----------- .../KafkaConnectControllerService.java | 142 ++++++------ .../java/io/aiven/klaw/service/MailUtils.java | 3 +- .../io/aiven/klaw/service/SaasService.java | 22 +- .../klaw/service/ServerConfigService.java | 2 +- .../klaw/service/TopicControllerService.java | 7 +- .../service/TopicSyncControllerService.java | 13 +- .../service/UsersTeamsControllerService.java | 2 +- src/main/resources/static/js/envs.js | 2 +- src/main/resources/static/js/rolesperms.js | 4 +- .../klaw/EnvsClustersTenantsControllerIT.java | 19 +- .../io/aiven/klaw/TopicAclControllerIT.java | 39 ++-- .../io/aiven/klaw/UsersTeamsControllerIT.java | 14 +- src/test/java/io/aiven/klaw/UtilMethods.java | 54 ++--- .../klaw/controller/AclControllerTest.java | 18 +- .../SchemaRegstryControllerTest.java | 13 +- .../klaw/controller/TopicControllerTest.java | 20 +- .../controller/UiConfigControllerTest.java | 31 +-- .../helpers/db/rdbms/DeleteDataJdbcTest.java | 15 +- .../helpers/db/rdbms/InsertDataJdbcTest.java | 19 +- .../helpers/db/rdbms/UpdateDataJdbcTest.java | 23 +- .../service/AclControllerServiceTest.java | 33 +-- .../klaw/service/ClusterApiServiceTest.java | 41 ++-- .../SchemaRegistryControllerServiceTest.java | 18 +- .../service/TopicControllerServiceTest.java | 35 +-- 40 files changed, 647 insertions(+), 582 deletions(-) create mode 100644 src/main/java/io/aiven/klaw/model/AclPatternType.java create mode 100644 src/main/java/io/aiven/klaw/model/AclPermissionType.java rename src/main/java/io/aiven/klaw/model/{AclOperationType.java => RequestOperationType.java} (58%) diff --git a/src/main/java/io/aiven/klaw/config/ManageDatabase.java b/src/main/java/io/aiven/klaw/config/ManageDatabase.java index 435f934079..30d399b954 100644 --- a/src/main/java/io/aiven/klaw/config/ManageDatabase.java +++ b/src/main/java/io/aiven/klaw/config/ManageDatabase.java @@ -748,6 +748,6 @@ public String deleteTenant(int tenantId) { kwSchemaRegClustersPertenant.remove(tenantId); kwKafkaConnectClustersPertenant.remove(tenantId); kwAllClustersPertenant.remove(tenantId); - return "success"; + return ApiResultStatus.SUCCESS.value; } } diff --git a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java index 2a6bf6d77e..ab6f2045db 100644 --- a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java +++ b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java @@ -144,13 +144,6 @@ public ResponseEntity>> getSyncEnv() { return new ResponseEntity<>(envsClustersTenantsControllerService.getSyncEnvs(), HttpStatus.OK); } - // @RequestMapping(value = "/getEnvsStatus", method = RequestMethod.GET, produces = - // {MediaType.APPLICATION_JSON_VALUE}) - // public ResponseEntity>> getEnvsStatus() { - // return new ResponseEntity<>(envsClustersTenantsControllerService.getEnvsStatus(), - // HttpStatus.OK); - // } - @RequestMapping( value = "/getEnvParams", method = RequestMethod.GET, @@ -189,16 +182,24 @@ public ResponseEntity> getSchemaRegEnvsStatus() { } @PostMapping(value = "/addNewEnv") - public ResponseEntity addNewEnv(@Valid @RequestBody EnvModel newEnv) { - return new ResponseEntity<>( - envsClustersTenantsControllerService.addNewEnv(newEnv), HttpStatus.OK); + public ResponseEntity addNewEnv(@Valid @RequestBody EnvModel newEnv) { + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.addNewEnv(newEnv), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/deleteEnvironmentRequest") - public ResponseEntity> deleteEnvironment( + public ResponseEntity deleteEnvironment( @RequestParam("envId") String envId, @RequestParam("envType") String envType) { - return new ResponseEntity<>( - envsClustersTenantsControllerService.deleteEnvironment(envId, envType), HttpStatus.OK); + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.deleteEnvironment(envId, envType), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -220,28 +221,40 @@ public ResponseEntity> getExtensionPeriods() { } @PostMapping(value = "/addTenantId") - public ResponseEntity> addTenantId( - @Valid @RequestBody KwTenantModel kwTenantModel) { - return new ResponseEntity<>( - envsClustersTenantsControllerService.addTenantId(kwTenantModel, true), HttpStatus.OK); + public ResponseEntity addTenantId(@Valid @RequestBody KwTenantModel kwTenantModel) { + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.addTenantId(kwTenantModel, true), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/deleteTenant") - public ResponseEntity> deleteTenant() { - return new ResponseEntity<>(envsClustersTenantsControllerService.deleteTenant(), HttpStatus.OK); + public ResponseEntity deleteTenant() { + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.deleteTenant(), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } // Pattern a-zA-z and/or spaces. @PostMapping(value = "/udpateTenant") - public ResponseEntity> udpateTenant( + public ResponseEntity udpateTenant( @RequestParam("orgName") @Pattern(message = "Invalid Organization.", regexp = "^[a-zA-z ]*$") String orgName) { - return new ResponseEntity<>( - envsClustersTenantsControllerService.updateTenant(orgName), HttpStatus.OK); + try { + return new ResponseEntity<>( + envsClustersTenantsControllerService.updateTenant(orgName), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/udpateTenantExtension") - public ResponseEntity> udpateTenantExtension( + public ResponseEntity udpateTenantExtension( @RequestParam("selectedTenantExtensionPeriod") String selectedTenantExtensionPeriod) { return new ResponseEntity<>( envsClustersTenantsControllerService.udpateTenantExtension(selectedTenantExtensionPeriod), diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java index 9a783b16fa..47c96376b2 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java @@ -1,5 +1,7 @@ package io.aiven.klaw.controller; +import static io.aiven.klaw.service.UtilControllerService.handleException; + import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ConnectorOverview; @@ -46,7 +48,6 @@ public ResponseEntity> getCreatedConnectorReque @RequestParam("pageNo") String pageNo, @RequestParam(value = "currentPage", defaultValue = "") String currentPage, @RequestParam(value = "requestsType", defaultValue = "created") String requestsType) { - return new ResponseEntity<>( kafkaConnectControllerService.getCreatedConnectorRequests( pageNo, currentPage, requestsType), @@ -57,10 +58,14 @@ public ResponseEntity> getCreatedConnectorReque value = "/deleteConnectorRequests", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteConnectorRequests( + public ResponseEntity deleteConnectorRequests( @RequestParam("connectorId") String connectorId) { - return new ResponseEntity<>( - kafkaConnectControllerService.deleteConnectorRequests(connectorId), HttpStatus.OK); + try { + return new ResponseEntity<>( + kafkaConnectControllerService.deleteConnectorRequests(connectorId), HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping( @@ -72,34 +77,37 @@ public ResponseEntity approveTopicRequests( return new ResponseEntity<>( kafkaConnectControllerService.approveConnectorRequests(connectorId), HttpStatus.OK); } catch (KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder().message("Unable to create kafka connector.").build(), - HttpStatus.INTERNAL_SERVER_ERROR); + return handleException(e); } } @PostMapping( value = "/execConnectorRequestsDecline", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity declineConnectorRequests( + public ResponseEntity declineConnectorRequests( @RequestParam("connectorId") String connectorId, - @RequestParam("reasonForDecline") String reasonForDecline) - throws KlawException { - - return new ResponseEntity<>( - kafkaConnectControllerService.declineConnectorRequests(connectorId, reasonForDecline), - HttpStatus.OK); + @RequestParam("reasonForDecline") String reasonForDecline) { + try { + return new ResponseEntity<>( + kafkaConnectControllerService.declineConnectorRequests(connectorId, reasonForDecline), + HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping( value = "/createConnectorDeleteRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> createConnectorDeleteRequest( + public ResponseEntity createConnectorDeleteRequest( @RequestParam("connectorName") String topicName, @RequestParam("env") String envId) { - return new ResponseEntity<>( - kafkaConnectControllerService.createConnectorDeleteRequest(topicName, envId), - HttpStatus.OK); + try { + return new ResponseEntity<>( + kafkaConnectControllerService.createConnectorDeleteRequest(topicName, envId), + HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @RequestMapping( @@ -126,7 +134,6 @@ public ResponseEntity>> getTopics( @RequestParam(value = "connectornamesearch", required = false) String topicNameSearch, @RequestParam(value = "teamName", required = false) String teamName) throws Exception { - return new ResponseEntity<>( kafkaConnectControllerService.getConnectors( envId, pageNo, currentPage, topicNameSearch, teamName), @@ -146,19 +153,22 @@ public ResponseEntity getConnectorOverview( @PostMapping( value = "/createClaimConnectorRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity> createClaimConnectorRequest( + public ResponseEntity createClaimConnectorRequest( @RequestParam("connectorName") String connectorName, @RequestParam("env") String envId) { - return new ResponseEntity<>( - kafkaConnectControllerService.createClaimConnectorRequest(connectorName, envId), - HttpStatus.OK); + try { + return new ResponseEntity<>( + kafkaConnectControllerService.createClaimConnectorRequest(connectorName, envId), + HttpStatus.OK); + } catch (KlawException e) { + return handleException(e); + } } @PostMapping(value = "/saveConnectorDocumentation") - public ResponseEntity> saveConnectorDocumentation( + public ResponseEntity saveConnectorDocumentation( @RequestBody KafkaConnectorModel topicInfo) { - Map saveTopicDocumentationResult = - kafkaConnectControllerService.saveConnectorDocumentation(topicInfo); - return new ResponseEntity<>(saveTopicDocumentationResult, HttpStatus.OK); + return new ResponseEntity<>( + kafkaConnectControllerService.saveConnectorDocumentation(topicInfo), HttpStatus.OK); } @RequestMapping( @@ -167,9 +177,7 @@ public ResponseEntity> saveConnectorDocumentation( produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity> getConnectorDetailsPerEnv( @RequestParam("envSelected") String envId, - @RequestParam("connectorName") String connectorName) - throws Exception { - + @RequestParam("connectorName") String connectorName) { return new ResponseEntity<>( kafkaConnectControllerService.getConnectorDetailsPerEnv(envId, connectorName), HttpStatus.OK); diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java index e9d0c8258b..1c6da5d8a0 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java @@ -1,6 +1,7 @@ package io.aiven.klaw.helpers.db.rdbms; import io.aiven.klaw.dao.*; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.repository.*; import java.util.List; import java.util.Optional; @@ -91,7 +92,7 @@ public String deleteConnectorRequest(int connectorId, int tenantId) { topicReq.get().setConnectorStatus("deleted"); kafkaConnectorRequestsRepo.save(topicReq.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteTopicRequest(int topicId, int tenantId) { @@ -106,7 +107,7 @@ public String deleteTopicRequest(int topicId, int tenantId) { topicReq.get().setTopicstatus("deleted"); topicRequestsRepo.save(topicReq.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteTopic(int topicId, int tenantId) { @@ -117,7 +118,7 @@ public String deleteTopic(int topicId, int tenantId) { Optional topicReq = topicRepo.findById(topicID); topicReq.ifPresent(topic -> topicRepo.delete(topic)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteConnector(int topicId, int tenantId) { @@ -128,7 +129,7 @@ public String deleteConnector(int topicId, int tenantId) { Optional topicReq = kafkaConnectorRepo.findById(kwKafkaConnectorID); topicReq.ifPresent(topic -> kafkaConnectorRepo.delete(topic)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteSchemaRequest(int avroSchemaId, int tenantId) { @@ -139,7 +140,7 @@ public String deleteSchemaRequest(int avroSchemaId, int tenantId) { schemaReq.get().setTopicstatus("deleted"); schemaRequestRepo.save(schemaReq.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAclRequest(int aclId, int tenantId) { @@ -153,7 +154,7 @@ public String deleteAclRequest(int aclId, int tenantId) { aclRequestsRepo.save(optAclRequests.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteEnvironment(String envId, int tenantId) { @@ -166,8 +167,8 @@ public String deleteEnvironment(String envId, int tenantId) { if (env.isPresent()) { // env.get().setEnvExists("false"); envRepo.delete(env.get()); - return "success"; - } else return "failure"; + return ApiResultStatus.SUCCESS.value; + } else return ApiResultStatus.FAILURE.value; } public String deleteCluster(int clusterId, int tenantId) { @@ -184,8 +185,8 @@ public String deleteCluster(int clusterId, int tenantId) { if (kwClusterRepo.findById(kwClusterID).isPresent()) { kwClusterRepo.delete(clusters); envRepo.deleteAll(allAssociatedEnvs); - return "success"; - } else return "failure"; + return ApiResultStatus.SUCCESS.value; + } else return ApiResultStatus.FAILURE.value; } public String deleteUserRequest(String userId) { @@ -193,7 +194,7 @@ public String deleteUserRequest(String userId) { UserInfo user = new UserInfo(); user.setUsername(userId); userInfoRepo.delete(user); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteTeamRequest(Integer teamId, int tenantId) { @@ -203,7 +204,7 @@ public String deleteTeamRequest(Integer teamId, int tenantId) { team.setTenantId(tenantId); teamRepo.delete(team); - return "success"; + return ApiResultStatus.SUCCESS.value; } // the actual req of Acl stored in otherParams of AclReq @@ -217,7 +218,7 @@ public String deletePrevAclRecs(AclRequests aclsToBeDeleted) { Optional acl = aclRepo.findById(aclID); acl.ifPresent(value -> aclRepo.delete(value)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAclSubscriptionRequest(int req_no, int tenantId) { @@ -229,7 +230,7 @@ public String deleteAclSubscriptionRequest(int req_no, int tenantId) { Optional aclRec = aclRepo.findById(aclID); aclRec.ifPresent(acl -> aclRepo.delete(acl)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public void deleteTopics(Topic topic) { @@ -253,45 +254,45 @@ public String deleteRole(String roleId, int tenantId) { kwRolesPermsRepo.findAllByRoleIdAndTenantId(roleId, tenantId); kwRolesPermsRepo.deleteAll(rolePerms); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllUsers(int tenantId) { userInfoRepo.deleteAll(userInfoRepo.findAllByTenantId(tenantId)); registerInfoRepo.deleteAll(registerInfoRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllTeams(int tenantId) { teamRepo.deleteAll(teamRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllEnvs(int tenantId) { envRepo.deleteAll(envRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllClusters(int tenantId) { kwClusterRepo.deleteAll(kwClusterRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllRolesPerms(int tenantId) { kwRolesPermsRepo.deleteAll(kwRolesPermsRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteAllKwProps(int tenantId) { kwPropertiesRepo.deleteAll(kwPropertiesRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteTenant(int tenantId) { KwTenants kwTenants = new KwTenants(); kwTenants.setTenantId(tenantId); tenantRepo.delete(kwTenants); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String deleteTxnData(int tenantId) { @@ -307,6 +308,6 @@ public String deleteTxnData(int tenantId) { kafkaConnectorRepo.deleteAll(kafkaConnectorRepo.findAllByTenantId(tenantId)); kafkaConnectorRequestsRepo.deleteAll(kafkaConnectorRequestsRepo.findAllByTenantId(tenantId)); - return "success"; + return ApiResultStatus.SUCCESS.value; } } diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java index 0707824cec..bcaf081cea 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java @@ -1,6 +1,7 @@ package io.aiven.klaw.helpers.db.rdbms; import io.aiven.klaw.dao.*; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.repository.*; import java.sql.Timestamp; import java.util.HashMap; @@ -103,10 +104,10 @@ public synchronized Map insertIntoRequestTopic(TopicRequest topi activityLog.setEnv(topicRequest.getEnvironment()); activityLog.setTenantId(topicRequest.getTenantId()); - if ("success".equals(insertIntoActivityLog(activityLog))) { - hashMap.put("result", "success"); + if (ApiResultStatus.SUCCESS.value.equals(insertIntoActivityLog(activityLog))) { + hashMap.put("result", ApiResultStatus.SUCCESS.value); } else { - hashMap.put("result", "failure"); + hashMap.put("result", ApiResultStatus.FAILURE.value); } return hashMap; @@ -140,10 +141,10 @@ public synchronized Map insertIntoRequestConnector( activityLog.setEnv(connectorRequest.getEnvironment()); activityLog.setTenantId(connectorRequest.getTenantId()); - if ("success".equals(insertIntoActivityLog(activityLog))) { - hashMap.put("result", "success"); + if (ApiResultStatus.SUCCESS.value.equals(insertIntoActivityLog(activityLog))) { + hashMap.put("result", ApiResultStatus.SUCCESS.value); } else { - hashMap.put("result", "failure"); + hashMap.put("result", ApiResultStatus.FAILURE.value); } return hashMap; @@ -166,7 +167,7 @@ public synchronized String insertIntoTopicSOT(List topics, boolean isSync topicRepo.save(topic); }); - return "success"; + return ApiResultStatus.SUCCESS.value; } public synchronized String insertIntoConnectorSOT( @@ -188,14 +189,14 @@ public synchronized String insertIntoConnectorSOT( kafkaConnectorRepo.save(connector); }); - return "success"; + return ApiResultStatus.SUCCESS.value; } private String insertIntoActivityLog(ActivityLog activityLog) { log.debug("insertIntoActivityLog {}", activityLog.getActivityName()); activityLogRepo.save(activityLog); - return "success"; + return ApiResultStatus.SUCCESS.value; } synchronized Map insertIntoRequestAcl(AclRequests aclReq) { @@ -237,7 +238,7 @@ synchronized Map insertIntoRequestAcl(AclRequests aclReq) { // Insert into acl activity log insertIntoActivityLog(activityLog); - hashMap.put("result", "success"); + hashMap.put("result", ApiResultStatus.SUCCESS.value); return hashMap; } @@ -249,7 +250,7 @@ public synchronized String insertIntoAclsSOT(List acls, boolean isSyncAcls) if (acl.getReq_no() == null) acl.setReq_no(getNextAclId(acl.getTenantId())); aclRepo.save(acl); }); - return "success"; + return ApiResultStatus.SUCCESS.value; } public synchronized String insertIntoRequestSchema(SchemaRequest schemaRequest) { @@ -280,7 +281,7 @@ public synchronized String insertIntoRequestSchema(SchemaRequest schemaRequest) // Insert into acl activity log insertIntoActivityLog(activityLog); - return "success"; + return ApiResultStatus.SUCCESS.value; } public synchronized String insertIntoMessageSchemaSOT(List schemas) { @@ -291,7 +292,7 @@ public synchronized String insertIntoMessageSchemaSOT(List schema mSchema.setReq_no(getNextSchemaRequestId("SCHEMA_ID", mSchema.getTenantId())); messageSchemaRepo.save(mSchema); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertIntoUsers(UserInfo userInfo) { @@ -300,7 +301,7 @@ public String insertIntoUsers(UserInfo userInfo) { if (userExists.isPresent()) return "Failure. User already exists"; userInfoRepo.save(userInfo); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertIntoTeams(Team team) { @@ -320,14 +321,14 @@ public String insertIntoTeams(Team team) { team.setApp(""); teamRepo.save(team); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertIntoEnvs(Env env) { log.debug("insertIntoEnvs {}", env.getName()); envRepo.save(env); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertIntoClusters(KwClusters kwClusters) { @@ -342,7 +343,7 @@ public String insertIntoClusters(KwClusters kwClusters) { kwClusters.setClusterId(lastClusterId); } kwClusterRepo.save(kwClusters); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertIntoRegisterUsers(RegisterUserInfo userInfo) { @@ -362,7 +363,7 @@ public String insertIntoRegisterUsers(RegisterUserInfo userInfo) { } registerInfoRepo.save(userInfo); - return "success"; + return ApiResultStatus.SUCCESS.value; } public Integer getNextTeamId(int tenantId) { @@ -427,12 +428,12 @@ public String addNewTenant(KwTenants kwTenants) { else maxTenantId = maxTenantId + 1; kwTenants.setTenantId(maxTenantId); tenantRepo.save(kwTenants); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String registerUserForAD(RegisterUserInfo newUser) { registerInfoRepo.save(newUser); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertMetrics(KwMetrics kwMetrics) { @@ -443,12 +444,12 @@ public String insertMetrics(KwMetrics kwMetrics) { kwMetrics.setMetricsId(metricsId); metricsRepo.save(kwMetrics); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertDefaultKwProperties(List kwPropertiesList) { kwPropertiesRepo.saveAll(kwPropertiesList); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String insertDefaultRolesPermissions(List kwRolesPermissionsList) { @@ -458,7 +459,7 @@ public String insertDefaultRolesPermissions(List kwRolesPerm kwRolesPermsRepo.save(kwRolesPermissions); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public Integer getNextRolePermissionId(int tenantId) { @@ -471,6 +472,6 @@ public Integer getNextRolePermissionId(int tenantId) { public String insertProductDetails(ProductDetails productDetails) { productDetailsRepo.save(productDetails); - return "success"; + return ApiResultStatus.SUCCESS.value; } } diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java index 84d7e026e7..97d0570fd4 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java @@ -2,7 +2,9 @@ import com.google.common.collect.Lists; import io.aiven.klaw.dao.*; +import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.AclType; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.TopicRequestTypes; import io.aiven.klaw.repository.*; import java.math.BigInteger; @@ -109,7 +111,7 @@ public List selectAclRequests( teamName = row.getTeamId(); } - if ("Delete".equals(aclType)) { + if (RequestOperationType.DELETE.value.equals(aclType)) { teamName = row.getRequestingteam(); } } else { @@ -199,7 +201,8 @@ public List selectSyncTopics(String env, Integer teamId, int tenantId) { public Map getDashboardStats(Integer teamId, int tenantId) { Map dashboardMap = new HashMap<>(); int countProducers = 0, countConsumers = 0; - List acls = aclRepo.findAllByTopictypeAndTeamIdAndTenantId("Producer", teamId, tenantId); + List acls = + aclRepo.findAllByTopictypeAndTeamIdAndTenantId(AclType.PRODUCER.value, teamId, tenantId); List topicList = new ArrayList<>(); if (acls != null) { acls.forEach(a -> topicList.add(a.getTopicname())); @@ -207,7 +210,7 @@ public Map getDashboardStats(Integer teamId, int tenantId) { } dashboardMap.put("producerCount", "" + countProducers); - acls = aclRepo.findAllByTopictypeAndTeamIdAndTenantId("Consumer", teamId, tenantId); + acls = aclRepo.findAllByTopictypeAndTeamIdAndTenantId(AclType.CONSUMER.value, teamId, tenantId); List topicListCons = new ArrayList<>(); if (acls != null) { acls.forEach(a -> topicListCons.add(a.getTopicname())); @@ -226,8 +229,9 @@ public List selectAllTopicsByTopictypeAndTeamname( log.debug("selectAllByTopictypeAndTeamname {} {}", isProducerConsumer, teamId); List topics = new ArrayList<>(); String topicType, aclPatternType; - if (isProducerConsumer != null && isProducerConsumer.equals("Producer")) topicType = "Producer"; - else topicType = "Consumer"; + if (isProducerConsumer != null && isProducerConsumer.equals(AclType.PRODUCER.value)) + topicType = AclType.PRODUCER.value; + else topicType = AclType.CONSUMER.value; List acls = aclRepo.findAllByTopictypeAndTeamIdAndTenantId(topicType, teamId, tenantId); Topic t; @@ -240,8 +244,8 @@ public List selectAllTopicsByTopictypeAndTeamname( tmpTopicName = acl.getTopicname(); aclPatternType = acl.getAclPatternType(); - if (aclPatternType != null && aclPatternType.equals("PREFIXED")) - tmpTopicName = tmpTopicName + "--PREFIXED--"; + if (aclPatternType != null && aclPatternType.equals(AclPatternType.PREFIXED.value)) + tmpTopicName = tmpTopicName + "--" + AclPatternType.PREFIXED.value + "--"; t.setEnvironment(acl.getEnvironment()); t.setTopicname(tmpTopicName); @@ -281,7 +285,8 @@ public List selectSyncAcls(String env, int tenantId) { } public List getPrefixedAclsSOT(String env, int tenantId) { - return aclRepo.findAllByEnvironmentAndAclPatternTypeAndTenantId(env, "PREFIXED", tenantId); + return aclRepo.findAllByEnvironmentAndAclPatternTypeAndTenantId( + env, AclPatternType.PREFIXED.value, tenantId); } public List selectTopicRequestsByStatus( @@ -754,7 +759,7 @@ public List> selectAclsCountByTeams( List> totalAclCount = new ArrayList<>(); try { List acls; - if ("Producer".equals(aclType)) { + if (AclType.PRODUCER.value.equals(aclType)) { if (teamId != null) { acls = aclRepo.findAllProducerAclsForTeamId(teamId, tenantId); } else { diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java index ba77fe0bf3..f27d168090 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java @@ -3,6 +3,8 @@ import static org.springframework.beans.BeanUtils.copyProperties; import io.aiven.klaw.dao.*; +import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.RequestStatus; import io.aiven.klaw.model.TopicRequestTypes; import io.aiven.klaw.repository.*; @@ -82,7 +84,7 @@ public String declineTopicRequest(TopicRequest topicRequest, String approver) { topicRequest.setApprovingtime(new Timestamp(System.currentTimeMillis())); topicRequestsRepo.save(topicRequest); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String declineConnectorRequest(KafkaConnectorRequest connectorRequest, String approver) { @@ -92,7 +94,7 @@ public String declineConnectorRequest(KafkaConnectorRequest connectorRequest, St connectorRequest.setApprovingtime(new Timestamp(System.currentTimeMillis())); kafkaConnectorRequestsRepo.save(connectorRequest); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateTopicRequestStatus(TopicRequest topicRequest, String approver) { @@ -102,7 +104,7 @@ public String updateTopicRequestStatus(TopicRequest topicRequest, String approve topicRequest.setApprovingtime(new Timestamp(System.currentTimeMillis())); topicRequestsRepo.save(topicRequest); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateConnectorRequestStatus( @@ -113,7 +115,7 @@ public String updateConnectorRequestStatus( connectorRequest.setApprovingtime(new Timestamp(System.currentTimeMillis())); kafkaConnectorRequestsRepo.save(connectorRequest); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateTopicRequest(TopicRequest topicRequest, String approver) { @@ -145,7 +147,7 @@ public String updateTopicRequest(TopicRequest topicRequest, String approver) { deleteDataJdbcHelper.deleteTopics(topicObj); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateConnectorRequest(KafkaConnectorRequest connectorRequest, String approver) { @@ -177,7 +179,7 @@ public String updateConnectorRequest(KafkaConnectorRequest connectorRequest, Str deleteDataJdbcHelper.deleteConnectors(topicObj); } - return "success"; + return ApiResultStatus.SUCCESS.value; } private void updateTopicSOT(List topics, String topicId) { @@ -223,7 +225,8 @@ private String processMultipleAcls(AclRequests aclReq, String jsonParams) { aclObj.setAclssl(aclReq.getAcl_ssl()); acls.add(aclObj); - if (aclReq.getAclType() != null && aclReq.getAclType().equals("Create")) { + if (aclReq.getAclType() != null + && RequestOperationType.CREATE.value.equals(aclReq.getAclType())) { acls.forEach(acl -> acl.setReq_no(null)); insertDataJdbcHelper.insertIntoAclsSOT(acls, false); } else { @@ -244,7 +247,8 @@ private String processMultipleAcls(AclRequests aclReq, String jsonParams) { aclObj.setAclssl(aclString); acls.add(aclObj); - if (aclReq.getAclType() != null && aclReq.getAclType().equals("Create")) { + if (aclReq.getAclType() != null + && RequestOperationType.CREATE.value.equals(aclReq.getAclType())) { acls.forEach(acl -> acl.setReq_no(null)); insertDataJdbcHelper.insertIntoAclsSOT(acls, false); } else { @@ -254,7 +258,7 @@ private String processMultipleAcls(AclRequests aclReq, String jsonParams) { } } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String declineAclRequest(AclRequests aclRequests, String approver) { @@ -264,7 +268,7 @@ public String declineAclRequest(AclRequests aclRequests, String approver) { aclRequests.setApprovingtime(new Timestamp(System.currentTimeMillis())); aclRequestsRepo.save(aclRequests); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updatePassword(String username, String password) { @@ -274,9 +278,9 @@ public String updatePassword(String username, String password) { UserInfo userInfo = userRec.get(); userInfo.setPwd(password); userInfoRepo.save(userInfo); - return "success"; + return ApiResultStatus.SUCCESS.value; } - return "failure"; + return ApiResultStatus.FAILURE.value; } public String updateSchemaRequest(SchemaRequest schemaRequest, String approver) { @@ -294,7 +298,7 @@ public String updateSchemaRequest(SchemaRequest schemaRequest, String approver) schemas.add(schemaObj); insertDataJdbcHelper.insertIntoMessageSchemaSOT(schemas); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateSchemaRequestDecline(SchemaRequest schemaRequest, String approver) { @@ -305,7 +309,7 @@ public String updateSchemaRequestDecline(SchemaRequest schemaRequest, String app schemaRequestRepo.save(schemaRequest); - return "success"; + return ApiResultStatus.SUCCESS.value; } public void updateNewUserRequest(String username, String approver, boolean isApprove) { @@ -332,7 +336,7 @@ public String updateUser(UserInfo userInfo) { if (!userExists.isPresent()) return "Failure. User doesn't exist"; userInfoRepo.save(userInfo); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateTeam(Team team) { @@ -342,7 +346,7 @@ public String updateTeam(Team team) { if (teamExists.isEmpty()) return "Failure. Team doesn't exist"; teamRepo.save(team); - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateKwProperty(KwProperties kwProperties, int tenantId) { @@ -351,10 +355,10 @@ public String updateKwProperty(KwProperties kwProperties, int tenantId) { if (!kwProp.isEmpty()) { kwProp.get(0).setKwValue(kwProperties.getKwValue()); kwPropertiesRepo.save(kwProp.get(0)); - return "success"; + return ApiResultStatus.SUCCESS.value; } - return "failure"; + return ApiResultStatus.FAILURE.value; } public Integer getNextRolePermissionId(int tenantId) { @@ -383,7 +387,7 @@ public String updatePermissions(List permissions, String add } } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateTopicDocumentation(Topic topic) { @@ -395,10 +399,10 @@ public String updateTopicDocumentation(Topic topic) { if (optTopic.isPresent()) { optTopic.get().setDocumentation(topic.getDocumentation()); topicRepo.save(optTopic.get()); - return "success"; + return ApiResultStatus.SUCCESS.value; } - return "failure"; + return ApiResultStatus.FAILURE.value; } public String updateConnectorDocumentation(KwKafkaConnector topic) { @@ -410,10 +414,10 @@ public String updateConnectorDocumentation(KwKafkaConnector topic) { if (optTopic.isPresent()) { optTopic.get().setDocumentation(topic.getDocumentation()); kafkaConnectorRepo.save(optTopic.get()); - return "success"; + return ApiResultStatus.SUCCESS.value; } - return "failure"; + return ApiResultStatus.FAILURE.value; } public String setTenantActivestatus(int tenantId, boolean status) { @@ -424,7 +428,7 @@ public String setTenantActivestatus(int tenantId, boolean status) { tenantRepo.save(kwTenant.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String updateTenant(int tenantId, String organizationName) { @@ -433,7 +437,7 @@ public String updateTenant(int tenantId, String organizationName) { kwTenant.get().setOrgName(organizationName); tenantRepo.save(kwTenant.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } public String disableTenant(int tenantId) { @@ -442,6 +446,6 @@ public String disableTenant(int tenantId) { kwTenant.get().setIsActive("false"); tenantRepo.save(kwTenant.get()); } - return "success"; + return ApiResultStatus.SUCCESS.value; } } diff --git a/src/main/java/io/aiven/klaw/model/AclPatternType.java b/src/main/java/io/aiven/klaw/model/AclPatternType.java new file mode 100644 index 0000000000..9e4ed7dd76 --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/AclPatternType.java @@ -0,0 +1,12 @@ +package io.aiven.klaw.model; + +public enum AclPatternType { + PREFIXED("PREFIXED"), + LITERAL("LITERAL"); + + public final String value; + + AclPatternType(String value) { + this.value = value; + } +} diff --git a/src/main/java/io/aiven/klaw/model/AclPermissionType.java b/src/main/java/io/aiven/klaw/model/AclPermissionType.java new file mode 100644 index 0000000000..ab5987bf97 --- /dev/null +++ b/src/main/java/io/aiven/klaw/model/AclPermissionType.java @@ -0,0 +1,12 @@ +package io.aiven.klaw.model; + +public enum AclPermissionType { + WRITE("WRITE"), + READ("READ"); + + public final String value; + + AclPermissionType(String value) { + this.value = value; + } +} diff --git a/src/main/java/io/aiven/klaw/model/AclOperationType.java b/src/main/java/io/aiven/klaw/model/RequestOperationType.java similarity index 58% rename from src/main/java/io/aiven/klaw/model/AclOperationType.java rename to src/main/java/io/aiven/klaw/model/RequestOperationType.java index f33a4c31b1..77263b5b2c 100644 --- a/src/main/java/io/aiven/klaw/model/AclOperationType.java +++ b/src/main/java/io/aiven/klaw/model/RequestOperationType.java @@ -1,12 +1,13 @@ package io.aiven.klaw.model; -public enum AclOperationType { +public enum RequestOperationType { CREATE("Create"), + UPDATE("Update"), DELETE("Delete"); public final String value; - AclOperationType(String value) { + RequestOperationType(String value) { this.value = value; } } diff --git a/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java b/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java index e082439bc5..cd396a2370 100644 --- a/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java +++ b/src/main/java/io/aiven/klaw/model/cluster/ClusterAclRequest.java @@ -1,7 +1,7 @@ package io.aiven.klaw.model.cluster; import com.fasterxml.jackson.annotation.JsonProperty; -import io.aiven.klaw.model.AclOperationType; +import io.aiven.klaw.model.RequestOperationType; import java.io.Serializable; import lombok.Builder; @@ -42,5 +42,5 @@ public class ClusterAclRequest implements Serializable { @JsonProperty private String aivenAclKey; - @JsonProperty private AclOperationType aclOperationType; + @JsonProperty private RequestOperationType requestOperationType; } diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index a03630ccf2..5f49f0cb50 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -20,11 +20,14 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.PermissionType; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.RequestStatus; import io.aiven.klaw.model.TopicHistory; import io.aiven.klaw.model.TopicInfo; @@ -71,7 +74,7 @@ public class AclControllerService { public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { log.info("createAcl {}", aclReq); String userDetails = getUserName(); - aclReq.setAclType("Create"); + aclReq.setAclType(RequestOperationType.CREATE.value); aclReq.setUsername(userDetails); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -88,7 +91,7 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { boolean topicFound = false; String result; - if ("LITERAL".equals(aclReq.getAclPatternType())) { + if (AclPatternType.LITERAL.value.equals(aclReq.getAclPatternType())) { for (Topic topic : topics) { if (Objects.equals(topic.getEnvironment(), aclReq.getEnvironment())) { topicFound = true; @@ -99,8 +102,8 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { if (!topicFound) return ApiResponse.builder().result(result).build(); } - if ("Consumer".equals(aclReq.getTopictype())) { - if ("PREFIXED".equals(aclReq.getAclPatternType())) { + if (AclType.CONSUMER.value.equals(aclReq.getTopictype())) { + if (AclPatternType.PREFIXED.value.equals(aclReq.getAclPatternType())) { result = "Failure : Please change the pattern to LITERAL for topic type."; return ApiResponse.builder().result(result).build(); } @@ -147,7 +150,7 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { String execRes = manageDatabase.getHandleDbRequests().requestForAcl(aclRequestsDao).get("result"); - if ("success".equals(execRes)) { + if (ApiResultStatus.SUCCESS.value.equals(execRes)) { mailService.sendMail( aclReq.getTopicname(), aclReq.getTopictype(), @@ -241,7 +244,7 @@ private String updateApprovingInfo( if (topicTeamsList.size() > 0) { Integer teamId = getFilteredTopicsForTenant(topicTeamsList).get(0).getTeamId(); - if ("Delete".equals(aclType)) teamId = team; + if (RequestOperationType.DELETE.value.equals(aclType)) teamId = team; List userList = manageDatabase.getHandleDbRequests().selectAllUsersInfoForTeam(teamId, tenantId); @@ -408,7 +411,7 @@ public ApiResponse createDeleteAclSubscriptionRequest(String req_no) throws Klaw Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())); if (!getEnvsFromUserId(userDetails).contains(acl.getEnvironment())) - return ApiResponse.builder().result("failure").build(); + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); AclRequests aclReq = new AclRequests(); @@ -417,12 +420,12 @@ public ApiResponse createDeleteAclSubscriptionRequest(String req_no) throws Klaw aclReq.setAcl_ssl(acl.getAclssl()); aclReq.setUsername(userDetails); - aclReq.setAclType("Delete"); + aclReq.setAclType(RequestOperationType.DELETE.value); aclReq.setOtherParams(req_no); aclReq.setJsonParams(acl.getJsonParams()); String execRes = manageDatabase.getHandleDbRequests().requestForAcl(aclReq).get("result"); - if ("success".equals(execRes)) { + if (ApiResultStatus.SUCCESS.value.equals(execRes)) { mailService.sendMail( aclReq.getTopicname(), aclReq.getTopictype(), @@ -481,12 +484,13 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { // set back all ips, principles aclReq.setAcl_ip(allIps); aclReq.setAcl_ssl(allSsl); - - String updateAclReqStatus = null; + String updateAclReqStatus; try { ApiResponse responseBody = Objects.requireNonNull(response).getBody(); - if (Objects.requireNonNull(responseBody).getResult().contains("success")) { + if (Objects.requireNonNull(responseBody) + .getResult() + .contains(ApiResultStatus.SUCCESS.value)) { String jsonParams = "", aivenAclIdKey = "aivenaclid"; if (responseBody.getData() instanceof Map) { Map dataMap = (Map) responseBody.getData(); @@ -601,7 +605,6 @@ private Map getTopicPromotionEnv( // tenant filtering String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_ENVS"); - envList.sort(Comparator.comparingInt(orderOfEnvs::indexOf)); String lastEnv = envList.get(envList.size() - 1); @@ -610,7 +613,7 @@ private Map getTopicPromotionEnv( if (orderdEnvs.indexOf(lastEnv) == orderdEnvs.size() - 1) { hashMap.put("status", "NO_PROMOTION"); // PRD } else { - hashMap.put("status", "success"); + hashMap.put("status", ApiResultStatus.SUCCESS.value); hashMap.put("sourceEnv", lastEnv); String targetEnv = orderdEnvs.get(orderdEnvs.indexOf(lastEnv) + 1); hashMap.put("targetEnv", getEnvDetails(targetEnv, tenantId).getName()); @@ -621,7 +624,7 @@ private Map getTopicPromotionEnv( } } catch (Exception e) { log.error("getTopicPromotionEnv {}", e.getMessage()); - hashMap.put("status", "failure"); + hashMap.put("status", ApiResultStatus.FAILURE.value); hashMap.put("error", "Topic does not exist in any environment."); } @@ -654,7 +657,6 @@ public TopicOverview getAcls(String topicNameSearch) { else return null; Integer loggedInUserTeam = getMyTeamId(userDetails); - List topics = handleDb.getTopics(topicNameSearch, tenantId); // tenant filtering diff --git a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java index d2fa553dfa..b0d12c84a7 100644 --- a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java @@ -10,12 +10,15 @@ import io.aiven.klaw.dao.Team; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.AclInfo; -import io.aiven.klaw.model.AclOperationType; +import io.aiven.klaw.model.AclPatternType; +import io.aiven.klaw.model.AclPermissionType; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; import io.aiven.klaw.model.PermissionType; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.SyncAclUpdates; import io.aiven.klaw.model.SyncBackAcls; import java.util.ArrayList; @@ -92,7 +95,7 @@ public ApiResponse updateSyncAcls(List syncAclUpdates) throws Kl manageDatabase.getTeamIdFromTeamName(tenantId, syncAclUpdateItem.getTeamSelected())); t.setEnvironment(syncAclUpdateItem.getEnvSelected()); t.setTopictype(syncAclUpdateItem.getAclType()); - t.setAclPatternType("LITERAL"); + t.setAclPatternType(AclPatternType.LITERAL.value); t.setTenantId(tenantId); listTopics.add(t); @@ -133,7 +136,7 @@ public ApiResponse updateSyncBackAcls(SyncBackAcls syncBackAcls) throws KlawExce } List resultStatus = new ArrayList<>(); - resultStatus.add("success"); + resultStatus.add(ApiResultStatus.SUCCESS.value); resultMap.put("result", resultStatus); try { @@ -176,16 +179,15 @@ private void approveSyncBackAcls( aclReq.setAcl_ssl(aclFound.getAclssl()); aclReq.setEnvironment(syncBackAcls.getTargetEnv()); aclReq.setRequestingteam(aclFound.getTeamId()); - aclReq.setAclType(AclOperationType.CREATE.value); + aclReq.setAclType(RequestOperationType.CREATE.value); aclReq.setUsername(getUserName()); aclReq.setTenantId(tenantId); ResponseEntity response = clusterApiService.approveAclRequests(aclReq, tenantId); ApiResponse responseBody = response.getBody(); - // String resultAclReq = responseBody.getResult(); String resultAclNullCheck = Objects.requireNonNull(responseBody).getResult(); - if (!Objects.requireNonNull(resultAclNullCheck).contains("success")) { + if (!Objects.requireNonNull(resultAclNullCheck).contains(ApiResultStatus.SUCCESS.value)) { log.error("Error in creating acl {} {}", aclFound, responseBody); logUpdateSyncBackTopics.add( "Error in Acl creation. Acl:" + aclFound.getTopicname() + " " + resultAclNullCheck); @@ -236,8 +238,8 @@ private List> updateConsumerGroups( for (Map hMapGroupItem : groupedList) { for (Map hMapItem : clusterAclList) { - if ("READ".equals(hMapGroupItem.get("operation")) - && "READ".equals(hMapItem.get("operation")) + if (AclPermissionType.READ.value.equals(hMapGroupItem.get("operation")) + && AclPermissionType.READ.value.equals(hMapItem.get("operation")) && "GROUP".equals(hMapItem.get("resourceType"))) { if (Objects.equals(hMapItem.get("host"), hMapGroupItem.get("host")) && Objects.equals(hMapItem.get("principle"), hMapGroupItem.get("principle"))) { @@ -409,9 +411,10 @@ private List applyFiltersAcls( String tmpPermType = aclListItem.get("operation"); - if ("WRITE".equals(tmpPermType)) mp.setTopictype("Producer"); - else if ("READ".equals(tmpPermType)) { - mp.setTopictype("Consumer"); + if (AclPermissionType.WRITE.value.equals(tmpPermType)) + mp.setTopictype(AclType.PRODUCER.value); + else if (AclPermissionType.READ.value.equals(tmpPermType)) { + mp.setTopictype(AclType.CONSUMER.value); if (aclListItem.get("consumerGroup") != null) mp.setConsumergroup(aclListItem.get("consumerGroup")); else continue; diff --git a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java index 3098eb81b6..211f33fcd3 100644 --- a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java @@ -4,6 +4,7 @@ import io.aiven.klaw.dao.Acl; import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.Topic; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.PermissionType; import io.aiven.klaw.model.charts.ChartsJsOverview; @@ -127,7 +128,7 @@ public Map getTopicsCountPerEnv(String sourceEnvSelected) { .collect(Collectors.toList()); if (topicsCountList.size() == 1) { - resultMap.put("status", "success"); + resultMap.put("status", ApiResultStatus.SUCCESS.value); resultMap.put("topicsCount", topicsCountList.get(0).get("topicscount")); } } @@ -139,7 +140,9 @@ public Map getTopicsCountPerEnv(String sourceEnvSelected) { public ChartsJsOverview getProducerAclsTeamsOverview(Integer teamId, Integer tenantId) { List> producerAclsPerTeamList = - manageDatabase.getHandleDbRequests().selectAclsCountByTeams("Producer", teamId, tenantId); + manageDatabase + .getHandleDbRequests() + .selectAclsCountByTeams(AclType.PRODUCER.value, teamId, tenantId); String title = "Producer Acls"; if (teamId != null) @@ -152,7 +155,9 @@ public ChartsJsOverview getProducerAclsTeamsOverview(Integer teamId, Integer ten public ChartsJsOverview getConsumerAclsTeamsOverview(Integer teamId, Integer tenantId) { List> consumerAclsPerTeamList = - manageDatabase.getHandleDbRequests().selectAclsCountByTeams("Consumer", teamId, tenantId); + manageDatabase + .getHandleDbRequests() + .selectAclsCountByTeams(AclType.CONSUMER.value, teamId, tenantId); String title = "Consumer Acls"; if (teamId != null) diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index 2a644edf07..1f02389c95 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -9,7 +9,7 @@ import io.aiven.klaw.dao.KwClusters; import io.aiven.klaw.dao.SchemaRequest; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.model.AclOperationType; +import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.AclsNativeType; import io.aiven.klaw.model.ApiResponse; @@ -17,6 +17,7 @@ import io.aiven.klaw.model.ClusterStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KafkaFlavors; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.cluster.ClusterAclRequest; import io.aiven.klaw.model.cluster.ClusterConnectorRequest; import io.aiven.klaw.model.cluster.ClusterSchemaRequest; @@ -402,9 +403,9 @@ public String approveConnectorRequests( String uri; String URI_GET_TOPICS = "/topics/"; - if ("Create".equals(connectorType)) { + if (RequestOperationType.CREATE.value.equals(connectorType)) { uri = clusterConnUrl + URI_GET_TOPICS + "postConnector"; - } else if ("Update".equals(connectorType)) { + } else if (RequestOperationType.UPDATE.value.equals(connectorType)) { uri = clusterConnUrl + URI_GET_TOPICS + "updateConnector"; } else uri = clusterConnUrl + URI_GET_TOPICS + "deleteConnector"; @@ -457,14 +458,14 @@ public ResponseEntity approveTopicRequests( .build(); String uri; - if ("Create".equals(topicRequestType)) { + if (RequestOperationType.CREATE.value.equals(topicRequestType)) { uri = clusterConnUrl + URI_CREATE_TOPICS; clusterTopicRequest = clusterTopicRequest.toBuilder() .partitions(topicPartitions) .replicationFactor(Short.parseShort(replicationFactor)) .build(); - } else if ("Update".equals(topicRequestType)) { + } else if (RequestOperationType.UPDATE.value.equals(topicRequestType)) { uri = clusterConnUrl + URI_UPDATE_TOPICS; clusterTopicRequest = clusterTopicRequest.toBuilder() @@ -519,7 +520,7 @@ public ResponseEntity approveAclRequests(AclRequests aclReq, int te clusterAclRequest = clusterAclRequest.toBuilder().permission("write").build(); else clusterAclRequest = clusterAclRequest.toBuilder().permission("read").build(); - if (Objects.equals(AclOperationType.DELETE.value, aclReq.getAclType()) + if (Objects.equals(RequestOperationType.DELETE.value, aclReq.getAclType()) && null != aclReq.getJsonParams()) { Map jsonObj = OBJECT_MAPPER.readValue(aclReq.getJsonParams(), Map.class); String aivenAclKey = "aivenaclid"; @@ -547,18 +548,18 @@ public ResponseEntity approveAclRequests(AclRequests aclReq, int te .aclSsl(aclReq.getAcl_ssl()) .transactionalId(aclReq.getTransactionalId()) .aclIpPrincipleType(aclReq.getAclIpPrincipleType().name()) - .isPrefixAcl("PREFIXED".equals(aclPatternType)) + .isPrefixAcl(AclPatternType.PREFIXED.value.equals(aclPatternType)) .build(); } - if ("Create".equals(aclReq.getAclType())) { + if (RequestOperationType.CREATE.value.equals(aclReq.getAclType())) { uri = clusterConnUrl + uriCreateAcls; clusterAclRequest = - clusterAclRequest.toBuilder().aclOperationType(AclOperationType.CREATE).build(); + clusterAclRequest.toBuilder().requestOperationType(RequestOperationType.CREATE).build(); } else { uri = clusterConnUrl + uriDeleteAcls; clusterAclRequest = - clusterAclRequest.toBuilder().aclOperationType(AclOperationType.DELETE).build(); + clusterAclRequest.toBuilder().requestOperationType(RequestOperationType.DELETE).build(); } HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); diff --git a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 445bc1e0b4..48fc6f4634 100644 --- a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -312,20 +312,6 @@ public List getEnvsForRequestTopicsCluster() { } public List getEnvsForRequestTopicsClusterFiltered() { - // List envModelList = getEnvsForRequestTopicsCluster(); - // String userDetails = getUserDetails(); - // HandleDbRequests reqsHandle = manageDatabase.getHandleDbRequests(); - // - // if(userDetails!=null) { - // String teamName = reqsHandle.getUsersInfo(userDetails).getTeam(); - // List teamEnvList = getTeamDetails(teamName).getEnvList(); - // if(teamEnvList != null && teamEnvList.size() > 0) { - // envModelList = envModelList.stream() - // .filter(a -> teamEnvList.contains(a.getId())) - // .collect(Collectors.toList()); - // } - // } - // return envModelList; return getKafkaEnvs(); } @@ -360,17 +346,7 @@ public List getKafkaEnvs() { public List getConnectorEnvs() { int tenantId = getUserDetails(getUserName()).getTenantId(); String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_ENVS"); - List listEnvs = manageDatabase.getKafkaConnectEnvList(tenantId); - - // if(commonUtilsService.isNotAuthorizedUser(getPrincipal(), - // PermissionType.VIEW_EDIT_ALL_ENVS_CLUSTERS_TENANTS)){ - // List allowedEnvIdList = getEnvsFromUserId(); - // listEnvs = listEnvs.stream() - // .filter(env -> allowedEnvIdList.contains(env.getId())) - // .collect(Collectors.toList()); - // } - List envModelList = getEnvModels(listEnvs, KafkaClustersType.KAFKA_CONNECT.value, tenantId); @@ -384,8 +360,6 @@ public List getConnectorEnvs() { public Map> getEnvsStatus() { Integer tenantId = getUserDetails(getUserName()).getTenantId(); - // Integer tenantId = - // getTeamDetails(getUserDetails(getUserDetails()).getTeam()).getTenantId(); Map> allTenantsEnvModels = manageDatabase.getEnvModelsClustersStatusAllTenants(); Map> allTenantsEnvModelsUpdated = new HashMap<>(); @@ -405,9 +379,7 @@ public Map> getEnvsStatus() { } public List getEnvsPaginated(String envId, String pageNo, String searchEnvParam) { - List envListMap = getKafkaEnvs(); - if (envId != null && !envId.equals("")) { envListMap = envListMap.stream() @@ -459,7 +431,6 @@ public List getEnvsPaginated(String envId, String pageNo, String searc private List getEnvModelsPaginated(String pageNo, List envListMap) { List envListMapUpdated = new ArrayList<>(); - int totalRecs = envListMap.size(); int recsPerPage = 10; @@ -612,15 +583,16 @@ public List getSchemaRegEnvsStatus() { return getEnvModels(newListEnvs, KafkaClustersType.SCHEMA_REGISTRY.value, tenantId); } - public String addNewEnv(EnvModel newEnv) { + public ApiResponse addNewEnv(EnvModel newEnv) throws KlawException { log.info("addNewEnv {}", newEnv); int tenantId = getUserDetails(getUserName()).getTenantId(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); newEnv.setTenantId(tenantId); - if (newEnv.getClusterId() == null) return "{\"result\":\"Please select a cluster.\"}"; + if (newEnv.getClusterId() == null) + return ApiResponse.builder().result("Please select a cluster.").build(); if (newEnv.getName().length() > 3 && Objects.equals(newEnv.getType(), KafkaClustersType.KAFKA.value)) @@ -657,9 +629,10 @@ public String addNewEnv(EnvModel newEnv) { && Objects.equals(en.getTenantId(), newEnv.getTenantId()) && Objects.equals(en.getEnvExists(), "true")); // 504 change if (envNameAlreadyPresent) { - return "{\"result\":\"Failure " - + "Please choose a different name. This environment name already exists." - + "\"}"; + return ApiResponse.builder() + .result( + "Failure. Please choose a different name. This environment name already exists.") + .build(); } else if (envActualList.stream() .anyMatch( en -> @@ -690,10 +663,10 @@ public String addNewEnv(EnvModel newEnv) { String result = manageDatabase.getHandleDbRequests().addNewEnv(env); commonUtilsService.updateMetadata( tenantId, EntityType.ENVIRONMENT, MetadataOperationType.CREATE); - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception:", e); - return "{\"result\":\"failure " + e.getMessage() + "\"}"; + throw new KlawException(e.getMessage()); } } @@ -825,15 +798,12 @@ public ApiResponse deleteCluster(String clusterId) throws KlawException { } } - public Map deleteEnvironment(String envId, String envType) { - Map resultMap = new HashMap<>(); - + public ApiResponse deleteEnvironment(String envId, String envType) throws KlawException { log.info("deleteEnvironment {}", envId); int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } switch (envType) { @@ -842,8 +812,7 @@ public Map deleteEnvironment(String envId, String envType) { > 0) { String notAllowed = "Not allowed to delete this environment, as there are associated topics/acls/requests."; - resultMap.put("result", notAllowed); - return resultMap; + return ApiResponse.builder().result(notAllowed).build(); } break; case "kafkaconnect": @@ -853,8 +822,7 @@ public Map deleteEnvironment(String envId, String envType) { > 0) { String notAllowed = "Not allowed to delete this environment, as there are associated connectors/requests."; - resultMap.put("result", notAllowed); - return resultMap; + return ApiResponse.builder().result(notAllowed).build(); } break; case "schemaregistry": @@ -862,8 +830,7 @@ public Map deleteEnvironment(String envId, String envType) { > 0) { String notAllowed = "Not allowed to delete this environment, as there are associated schemaregistry/requests."; - resultMap.put("result", notAllowed); - return resultMap; + return ApiResponse.builder().result(notAllowed).build(); } break; } @@ -874,12 +841,10 @@ public Map deleteEnvironment(String envId, String envType) { commonUtilsService.updateMetadata( tenantId, EntityType.ENVIRONMENT, MetadataOperationType.DELETE); - resultMap.put("result", result); - return resultMap; + return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error("Exception:", e); - resultMap.put("result", "failure " + e.getMessage()); - return resultMap; + throw new KlawException(e.getMessage()); } } @@ -965,20 +930,16 @@ public List getStandardEnvNames() { return envList; } - public Map addTenantId(KwTenantModel kwTenantModel, boolean isExternal) { - - Map addTenantStatus = new HashMap<>(); - + public ApiResponse addTenantId(KwTenantModel kwTenantModel, boolean isExternal) + throws KlawException { if (manageDatabase.getHandleDbRequests().getTenants().size() >= maxNumberOfTenantsCanBeCreated) { - addTenantStatus.put("result", "Maximum tenants reached."); - return addTenantStatus; + return ApiResponse.builder().result("Maximum tenants reached.").build(); } if (isExternal && commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ADD_TENANT)) { - addTenantStatus.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return addTenantStatus; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } KwTenants kwTenants = new KwTenants(); @@ -1000,36 +961,37 @@ public Map addTenantId(KwTenantModel kwTenantModel, boolean isEx new Timestamp( System.currentTimeMillis() + TimeUnit.DAYS.toMillis(DAYS_EXPIRY_DEFAULT_TENANT))); - addTenantStatus.put("result", manageDatabase.getHandleDbRequests().addNewTenant(kwTenants)); - int tenantId = - manageDatabase.getHandleDbRequests().getTenants().stream() - .filter( - kwTenant -> Objects.equals(kwTenant.getTenantName(), kwTenantModel.getTenantName())) - .findFirst() - .get() - .getTenantId(); - - addTenantStatus.put("tenantId", "" + tenantId); - - commonUtilsService.updateMetadata(tenantId, EntityType.TENANT, MetadataOperationType.CREATE); - - if (isExternal) { - manageDatabase - .getHandleDbRequests() - .insertDefaultKwProperties(defaultDataService.createDefaultProperties(tenantId, "")); - manageDatabase - .getHandleDbRequests() - .insertDefaultRolesPermissions( - defaultDataService.createDefaultRolesPermissions( - tenantId, false, kwInstallationType)); - - commonUtilsService.updateMetadata( - tenantId, EntityType.ROLES_PERMISSIONS, MetadataOperationType.CREATE); - commonUtilsService.updateMetadata( - tenantId, EntityType.PROPERTIES, MetadataOperationType.CREATE); + try { + String addNewTenantStatus = manageDatabase.getHandleDbRequests().addNewTenant(kwTenants); + int tenantId = + manageDatabase.getHandleDbRequests().getTenants().stream() + .filter( + kwTenant -> + Objects.equals(kwTenant.getTenantName(), kwTenantModel.getTenantName())) + .findFirst() + .get() + .getTenantId(); + + commonUtilsService.updateMetadata(tenantId, EntityType.TENANT, MetadataOperationType.CREATE); + if (isExternal) { + manageDatabase + .getHandleDbRequests() + .insertDefaultKwProperties(defaultDataService.createDefaultProperties(tenantId, "")); + manageDatabase + .getHandleDbRequests() + .insertDefaultRolesPermissions( + defaultDataService.createDefaultRolesPermissions( + tenantId, false, kwInstallationType)); + + commonUtilsService.updateMetadata( + tenantId, EntityType.ROLES_PERMISSIONS, MetadataOperationType.CREATE); + commonUtilsService.updateMetadata( + tenantId, EntityType.PROPERTIES, MetadataOperationType.CREATE); + } + return ApiResponse.builder().result(addNewTenantStatus).data("" + tenantId).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); } - - return addTenantStatus; } public KwTenantModel getMyTenantInfo() { @@ -1067,18 +1029,14 @@ private Object getPrincipal() { return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } - public Map deleteTenant() { - Map resultMap = new HashMap<>(); - + public ApiResponse deleteTenant() throws KlawException { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } int tenantId = commonUtilsService.getTenantId(getUserName()); if (tenantId == DEFAULT_TENANT_ID) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } String tenantName = manageDatabase.getTenantMap().get(tenantId); @@ -1098,36 +1056,38 @@ public Map deleteTenant() { manageDatabase.getHandleDbRequests().deleteAllKwProps(tenantId); manageDatabase.getHandleDbRequests().deleteTxnData(tenantId); - String result = manageDatabase.getHandleDbRequests().disableTenant(tenantId); + try { + String result = manageDatabase.getHandleDbRequests().disableTenant(tenantId); - if (ApiResultStatus.SUCCESS.value.equals(result)) { - commonUtilsService.updateMetadata(tenantId, EntityType.TENANT, MetadataOperationType.DELETE); - resultMap.put("result", "success"); - resultMap.put("tenantId", tenantName); - SecurityContextHolder.getContext().setAuthentication(null); - } else { - resultMap.put("result", "failure"); + if (ApiResultStatus.SUCCESS.value.equals(result)) { + commonUtilsService.updateMetadata( + tenantId, EntityType.TENANT, MetadataOperationType.DELETE); + SecurityContextHolder.getContext().setAuthentication(null); + } + return ApiResponse.builder().result(result).data(tenantName).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); } - return resultMap; } - public Map updateTenant(String orgName) { - Map resultMap = new HashMap<>(); + public ApiResponse updateTenant(String orgName) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } int tenantId = commonUtilsService.getTenantId(getUserName()); - String result = manageDatabase.getHandleDbRequests().updateTenant(tenantId, orgName); + try { + String result = manageDatabase.getHandleDbRequests().updateTenant(tenantId, orgName); - if ("success".equals(result)) { - resultMap.put("result", "success"); - commonUtilsService.updateMetadata(tenantId, EntityType.TENANT, MetadataOperationType.UPDATE); - } else { - resultMap.put("result", "failure"); + if (ApiResultStatus.SUCCESS.value.equals(result)) { + commonUtilsService.updateMetadata( + tenantId, EntityType.TENANT, MetadataOperationType.UPDATE); + } + + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); } - return resultMap; } public List getExtensionPeriods() { @@ -1136,14 +1096,11 @@ public List getExtensionPeriods() { // year", "2 years", "3 years", "5 years"); } - public Map udpateTenantExtension(String selectedTenantExtensionPeriod) { + public ApiResponse udpateTenantExtension(String selectedTenantExtensionPeriod) { // send mail - - Map resultMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { - resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return resultMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -1156,17 +1113,12 @@ public Map udpateTenantExtension(String selectedTenantExtensionP selectedTenantExtensionPeriod, commonUtilsService.getLoginUrl()); - if ("success".equals(result)) { - resultMap.put("result", "success"); - } else { - resultMap.put("result", "failure"); - } - return resultMap; + return ApiResponse.builder().result(result).build(); } public Map getAclCommands() { Map res = new HashMap<>(); - res.put("result", "success"); + res.put("result", ApiResultStatus.SUCCESS.value); res.put("aclCommandSsl", aclCommandSsl); res.put("aclCommandPlaintext", aclCommandPlaintext); return res; @@ -1227,7 +1179,7 @@ public Map getUpdateEnvStatus(String envId) { manageDatabase.getHandleDbRequests().addNewEnv(env); manageDatabase.loadEnvMapForOneTenant(tenantId); - envUpdatedStatus.put("result", "success"); + envUpdatedStatus.put("result", ApiResultStatus.SUCCESS.value); envUpdatedStatus.put("envstatus", status); return envUpdatedStatus; diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index 6a338763e0..a1d8726b60 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -28,6 +28,7 @@ import io.aiven.klaw.model.KafkaConnectorModel; import io.aiven.klaw.model.KafkaConnectorRequestModel; import io.aiven.klaw.model.PermissionType; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.RequestStatus; import io.aiven.klaw.model.TopicHistory; import io.aiven.klaw.model.TopicRequestTypes; @@ -415,21 +416,24 @@ private List groupConnectorsByEnv(List topic return tmpTopicList; } - public String deleteConnectorRequests(String topicId) { + public ApiResponse deleteConnectorRequests(String topicId) throws KlawException { log.info("deleteConnectorRequests {}", topicId); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_CREATE_CONNECTORS)) { - String res = "Not Authorized."; - return "{\"result\":\"" + res + "\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } - String deleteTopicReqStatus = - manageDatabase - .getHandleDbRequests() - .deleteConnectorRequest( - Integer.parseInt(topicId), commonUtilsService.getTenantId(getUserName())); + try { + String deleteTopicReqStatus = + manageDatabase + .getHandleDbRequests() + .deleteConnectorRequest( + Integer.parseInt(topicId), commonUtilsService.getTenantId(getUserName())); - return "{\"result\":\"" + deleteTopicReqStatus + "\"}"; + return ApiResponse.builder().result(deleteTopicReqStatus).build(); + } catch (Exception e) { + throw new KlawException(e.getMessage()); + } } public List getCreatedConnectorRequests( @@ -490,7 +494,6 @@ private String createConnectorConfig(KafkaConnectorRequest connectorRequest) { public ApiResponse approveConnectorRequests(String connectorId) throws KlawException { log.info("approveConnectorRequests {}", connectorId); - Map resultMap = new HashMap<>(); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -540,7 +543,7 @@ public ApiResponse approveConnectorRequests(String connectorId) throws KlawExcep } updateTopicReqStatus = dbHandle.addToSyncConnectors(allTopics); - if ("success".equals(updateTopicReqStatus)) + if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) updateTopicReqStatus = dbHandle.updateConnectorRequestStatus(connectorRequest, userDetails); } else { Env envSelected = @@ -554,7 +557,8 @@ public ApiResponse approveConnectorRequests(String connectorId) throws KlawExcep String protocol = kwClusters.getProtocol(); String kafkaConnectHost = kwClusters.getBootstrapServers(); - if ("Update".equals(connectorRequest.getConnectortype())) // only config + if (RequestOperationType.UPDATE.value.equals( + connectorRequest.getConnectortype())) // only config { updateTopicReqStatus = clusterApiService.approveConnectorRequests( @@ -574,7 +578,7 @@ public ApiResponse approveConnectorRequests(String connectorId) throws KlawExcep kafkaConnectHost, tenantId); } - if (Objects.equals(updateTopicReqStatus, "success")) { + if (Objects.equals(updateTopicReqStatus, ApiResultStatus.SUCCESS.value)) { setConnectorHistory(connectorRequest, userDetails, tenantId); updateTopicReqStatus = dbHandle.updateConnectorRequest(connectorRequest, userDetails); mailService.sendMail( @@ -630,11 +634,12 @@ private void setConnectorHistory( } } - public String declineConnectorRequests(String connectorId, String reasonForDecline) { + public ApiResponse declineConnectorRequests(String connectorId, String reasonForDecline) + throws KlawException { log.info("declineConnectorRequests {} {}", connectorId, reasonForDecline); String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -643,37 +648,41 @@ public String declineConnectorRequests(String connectorId, String reasonForDecli dbHandle.selectConnectorRequestsForConnector(Integer.parseInt(connectorId), tenantId); if (!RequestStatus.created.name().equals(connectorRequest.getConnectorStatus())) { - return "{\"result\":\"This request does not exist anymore.\"}"; + return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); if (!allowedEnvIdList.contains(connectorRequest.getEnvironment())) - return "{\"result\":\"Not Authorized\"}"; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); - String result = dbHandle.declineConnectorRequest(connectorRequest, userDetails); - mailService.sendMail( - connectorRequest.getConnectorName(), - null, - reasonForDecline, - connectorRequest.getRequestor(), - dbHandle, - CONNECTOR_REQUEST_DENIED, - commonUtilsService.getLoginUrl()); + try { + String result = dbHandle.declineConnectorRequest(connectorRequest, userDetails); + mailService.sendMail( + connectorRequest.getConnectorName(), + null, + reasonForDecline, + connectorRequest.getRequestor(), + dbHandle, + CONNECTOR_REQUEST_DENIED, + commonUtilsService.getLoginUrl()); - return "{\"result\":\"" + result + "\"}"; + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } // create a request to delete connector. - public Map createConnectorDeleteRequest(String connectorName, String envId) { + public ApiResponse createConnectorDeleteRequest(String connectorName, String envId) + throws KlawException { log.info("createConnectorDeleteRequest {} {}", connectorName, envId); String userDetails = getUserName(); - Map hashMap = new HashMap<>(); if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.REQUEST_DELETE_CONNECTORS)) { - hashMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); - return hashMap; + return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -686,10 +695,10 @@ public Map createConnectorDeleteRequest(String connectorName, St if (topics != null && topics.size() > 0 && !Objects.equals(topics.get(0).getTeamId(), userTeamId)) { - hashMap.put( - "result", - "Failure. Sorry, you cannot delete this connector, as you are not part of this team."); - return hashMap; + return ApiResponse.builder() + .result( + "Failure. Sorry, you cannot delete this connector, as you are not part of this team.") + .build(); } topicRequestReq.setRequestor(userDetails); @@ -714,8 +723,9 @@ public Map createConnectorDeleteRequest(String connectorName, St tenantId) .size() > 0) { - hashMap.put("result", "Failure. A delete connector request already exists."); - return hashMap; + return ApiResponse.builder() + .result("Failure. A delete connector request already exists.") + .build(); } if (topicOb.isPresent()) { @@ -730,15 +740,18 @@ public Map createConnectorDeleteRequest(String connectorName, St CONNECTOR_DELETE_REQUESTED, commonUtilsService.getLoginUrl()); - hashMap.put( - "result", - manageDatabase.getHandleDbRequests().requestForConnector(topicRequestReq).get("result")); + try { + String result = + manageDatabase.getHandleDbRequests().requestForConnector(topicRequestReq).get("result"); + return ApiResponse.builder().result(result).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } else { log.error("Connector not found : {}", connectorName); - hashMap.put("result", "failure"); + return ApiResponse.builder().result("Failure : Connector not found" + connectorName).build(); } - - return hashMap; } private boolean checkInPromotionOrder(String topicname, String envId, String orderOfEnvs) { @@ -776,12 +789,11 @@ public List getConnectorRequests( return getConnectorRequestModels(topicReqs, true); } - public Map createClaimConnectorRequest(String connectorName, String envId) { + public ApiResponse createClaimConnectorRequest(String connectorName, String envId) + throws KlawException { log.info("createClaimConnectorRequest {}", connectorName); String userDetails = getUserName(); - Map resultMap = new HashMap<>(); - HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); KafkaConnectorRequest connectorRequest = new KafkaConnectorRequest(); int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -791,8 +803,9 @@ public Map createClaimConnectorRequest(String connectorName, Str .selectConnectorRequests(connectorName, envId, RequestStatus.created.name(), tenantId) .size() > 0) { - resultMap.put("result", "Failure. A request already exists for this connector."); - return resultMap; + return ApiResponse.builder() + .result("Failure. A request already exists for this connector.") + .build(); } List topics = getConnectorsFromName(connectorName, tenantId); @@ -835,11 +848,14 @@ public Map createClaimConnectorRequest(String connectorName, Str CONNECTOR_CLAIM_REQUESTED, commonUtilsService.getLoginUrl())); - resultMap.put( - "result", - manageDatabase.getHandleDbRequests().requestForConnector(connectorRequest).get("result")); - - return resultMap; + try { + String res = + manageDatabase.getHandleDbRequests().requestForConnector(connectorRequest).get("result"); + return ApiResponse.builder().result(res).build(); + } catch (Exception e) { + log.error(e.getMessage()); + throw new KlawException(e.getMessage()); + } } public ConnectorOverview getConnectorOverview(String connectorNamesearch) { @@ -1063,7 +1079,7 @@ private Map getConnectorPromotionEnv( if (orderdEnvs.indexOf(lastEnv) == orderdEnvs.size() - 1) { hashMap.put("status", "NO_PROMOTION"); // PRD } else { - hashMap.put("status", "success"); + hashMap.put("status", ApiResultStatus.SUCCESS.value); hashMap.put("sourceEnv", lastEnv); hashMap.put("sourceConnectorConfig", sourceConnectorConfig.get()); String targetEnv = orderdEnvs.get(orderdEnvs.indexOf(lastEnv) + 1); @@ -1075,21 +1091,18 @@ private Map getConnectorPromotionEnv( } } catch (Exception e) { log.error("getConnectorPromotionEnv ", e); - hashMap.put("status", "failure"); + hashMap.put("status", ApiResultStatus.FAILURE.value); hashMap.put("error", "Connector does not exist in any environment."); } return hashMap; } - public Map saveConnectorDocumentation(KafkaConnectorModel topicInfo) { - Map saveResult = new HashMap<>(); - + public ApiResponse saveConnectorDocumentation(KafkaConnectorModel topicInfo) { KwKafkaConnector topic = new KwKafkaConnector(); topic.setConnectorId(topicInfo.getConnectorId()); topic.setDocumentation(topicInfo.getDocumentation()); - HandleDbRequests handleDb = manageDatabase.getHandleDbRequests(); List topicsSearchList = manageDatabase .getHandleDbRequests() @@ -1097,17 +1110,14 @@ public Map saveConnectorDocumentation(KafkaConnectorModel topicI topicInfo.getConnectorName(), commonUtilsService.getTenantId(getUserName())); // tenant filtering - int tenantId = commonUtilsService.getTenantId(getUserName()); Integer topicOwnerTeam = getFilteredConnectorsForTenant(topicsSearchList).get(0).getTeamId(); - Integer loggedInUserTeam = getMyTeamId(getUserName()); if (Objects.equals(topicOwnerTeam, loggedInUserTeam)) { - saveResult.put( - "result", manageDatabase.getHandleDbRequests().updateConnectorDocumentation(topic)); - } else saveResult.put("result", "failure"); - - return saveResult; + return ApiResponse.builder() + .result(manageDatabase.getHandleDbRequests().updateConnectorDocumentation(topic)) + .build(); + } else return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); } private List getConnectorRequestModels( diff --git a/src/main/java/io/aiven/klaw/service/MailUtils.java b/src/main/java/io/aiven/klaw/service/MailUtils.java index 8f9c4d74e5..dc92420bfc 100644 --- a/src/main/java/io/aiven/klaw/service/MailUtils.java +++ b/src/main/java/io/aiven/klaw/service/MailUtils.java @@ -3,6 +3,7 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.RegisterUserInfo; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwTenantConfigModel; import io.aiven.klaw.model.MailType; import java.util.*; @@ -395,6 +396,6 @@ public String sendMailToSaasAdmin(int tenantId, String userName, String period, "Tenant extension : Tenant " + tenantId + " username " + userName + " period " + period; emailService.sendSimpleMessage( userName, kwSaasAdminMailId, "Tenant Extension", mailtext, tenantId, loginUrl); - return "success"; + return ApiResultStatus.SUCCESS.value; } } diff --git a/src/main/java/io/aiven/klaw/service/SaasService.java b/src/main/java/io/aiven/klaw/service/SaasService.java index 3a1630efcf..28d44b4e7e 100644 --- a/src/main/java/io/aiven/klaw/service/SaasService.java +++ b/src/main/java/io/aiven/klaw/service/SaasService.java @@ -48,7 +48,7 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws Map tenantMap = manageDatabase.getTenantMap(); Map resultMap = new HashMap<>(); - resultMap.put("result", "failure"); + resultMap.put("result", ApiResultStatus.FAILURE.value); // check if user exists List userList = manageDatabase.getHandleDbRequests().selectAllUsersAllTenants(); @@ -71,19 +71,19 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws kwTenantModel.setContactPerson(newUser.getFullname()); kwTenantModel.setInTrialPhase(true); kwTenantModel.setActiveTenant(true); - Map addTenantResult = + ApiResponse addTenantResult = envsClustersTenantsControllerService.addTenantId(kwTenantModel, false); // create INFRATEAM and STAGINGTEAM - if ("success".equals(addTenantResult.get("result"))) { - tenantId = Integer.parseInt(addTenantResult.get("tenantId")); + if (ApiResultStatus.SUCCESS.value.equals(addTenantResult.getResult())) { + tenantId = Integer.parseInt((String) addTenantResult.getData()); Map teamAddMap = usersTeamsControllerService.addTwoDefaultTeams( newUser.getFullname(), newTenantName, tenantId); - if (teamAddMap.get("team1result").contains("success") - && teamAddMap.get("team2result").contains("success")) { + if (teamAddMap.get("team1result").contains(ApiResultStatus.SUCCESS.value) + && teamAddMap.get("team2result").contains(ApiResultStatus.SUCCESS.value)) { // approve user ApiResponse resultApproveUser = @@ -101,12 +101,12 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws return resultMap; } } else { - resultMap.put("error", "Failure :" + addTenantResult.get("result")); + resultMap.put("error", "Failure :" + addTenantResult.getResult()); return resultMap; } } - resultMap.put("result", "success"); + resultMap.put("result", ApiResultStatus.SUCCESS.value); return resultMap; } catch (Exception e) { log.error("Exception:", e); @@ -283,7 +283,7 @@ public Map getActivationInfo(String activationId) { usersTeamsControllerService.getRegistrationInfoFromId(activationId, ""); if (registerUserInfoModel == null) { - resultMap.put("result", "failure"); + resultMap.put("result", ApiResultStatus.FAILURE.value); return resultMap; } else if ("APPROVED".equals(registerUserInfoModel.getStatus())) { resultMap.put("result", "already_activated"); @@ -292,8 +292,8 @@ public Map getActivationInfo(String activationId) { Map result; try { result = approveUserSaas(registerUserInfoModel); - if ("success".equals(result.get("result"))) { - resultMap.put("result", "success"); + if (ApiResultStatus.SUCCESS.value.equals(result.get("result"))) { + resultMap.put("result", ApiResultStatus.SUCCESS.value); } else resultMap.put("result", "othererror"); } catch (Exception e) { log.error("Exception:", e); diff --git a/src/main/java/io/aiven/klaw/service/ServerConfigService.java b/src/main/java/io/aiven/klaw/service/ServerConfigService.java index 2c934f003a..96b8ea2a4c 100644 --- a/src/main/java/io/aiven/klaw/service/ServerConfigService.java +++ b/src/main/java/io/aiven/klaw/service/ServerConfigService.java @@ -104,7 +104,7 @@ public List> getAllEditableProps() { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { - resultMap.put("result", "Not Authorized."); + resultMap.put("result", ApiResultStatus.NOT_AUTHORIZED.value); listMap.add(resultMap); return listMap; } diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index 90916d2fbb..1230712f0f 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -16,6 +16,8 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.AclPatternType; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; @@ -508,7 +510,7 @@ public Map getTopicTeamOnly(String topicName, String patternType log.debug("getTopicTeamOnly {} {}", topicName, patternType); Map teamMap = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if ("PREFIXED".equals(patternType)) { + if (AclPatternType.PREFIXED.value.equals(patternType)) { List topics = manageDatabase.getHandleDbRequests().getAllTopics(tenantId); // tenant filtering @@ -1006,8 +1008,7 @@ private List getTopicsPaginated( // To get Producer or Consumer topics, first get all topics based on acls and then filter List producerConsumerTopics = new ArrayList<>(); - if (topicType != null - && ("Producer".equals(topicType) || "Consumer".equals(topicType)) + if ((AclType.PRODUCER.value.equals(topicType) || AclType.CONSUMER.value.equals(topicType)) && teamName != null) { producerConsumerTopics = handleDbRequests.selectAllTopicsByTopictypeAndTeamname( diff --git a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index e63d27dd98..d0282c19fd 100644 --- a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -10,10 +10,12 @@ import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.PermissionType; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.RequestStatus; import io.aiven.klaw.model.SyncBackTopics; import io.aiven.klaw.model.SyncTopicUpdates; @@ -542,13 +544,13 @@ private void approveSyncBackTopics( ResponseEntity response = clusterApiService.approveTopicRequests( topicFound.getTopicname(), - "Create", + RequestOperationType.CREATE.value, topicFound.getNoOfPartitions(), topicFound.getNoOfReplcias(), syncBackTopics.getTargetEnv(), tenantId); - if (!Objects.equals(response.getBody(), "success")) { + if (!Objects.equals(response.getBody(), ApiResultStatus.SUCCESS.value)) { log.error("Error in creating topic {} {}", topicFound, response.getBody()); if (response.getBody().contains("TopicExistsException")) logUpdateSyncBackTopics.add( @@ -583,7 +585,7 @@ private void createAndApproveTopicRequest( TopicRequest topicRequest; topicRequest = new TopicRequest(); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); topicRequest.setTopicname(topicFound.getTopicname()); topicRequest.setEnvironment(syncBackTopics.getTargetEnv()); topicRequest.setTopicpartitions(topicFound.getNoOfPartitions()); @@ -635,8 +637,7 @@ private List getTopicsPaginated( // To get Producer or Consumer topics, first get all topics based on acls and then filter List producerConsumerTopics = new ArrayList<>(); - if (topicType != null - && ("Producer".equals(topicType) || "Consumer".equals(topicType)) + if ((AclType.PRODUCER.value.equals(topicType) || AclType.CONSUMER.value.equals(topicType)) && teamName != null) { producerConsumerTopics = handleDbRequests.selectAllTopicsByTopictypeAndTeamname( @@ -832,7 +833,7 @@ public ApiResponse updateSyncTopicsBulk(SyncTopicsBulk syncTopicsBulk) throws Kl } // List resultStatus = new ArrayList<>(); - // resultStatus.add("success"); + // resultStatus.add(ApiResultStatus.SUCCESS.value); // // resultMap.put("result", resultStatus); diff --git a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index b3d3b19dcb..c29db67629 100644 --- a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -830,7 +830,7 @@ public ApiResponse approveNewUserRequests( userInfo.setMailid(registerUserInfo.getMailid()); ApiResponse resultResp = addNewUser(userInfo, isExternal); - if (resultResp.getResult().contains("success")) + if (resultResp.getResult().contains(ApiResultStatus.SUCCESS.value)) dbHandle.updateNewUserRequest(username, userDetails, true); else { return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); diff --git a/src/main/resources/static/js/envs.js b/src/main/resources/static/js/envs.js index f5920bddf7..82cf046591 100644 --- a/src/main/resources/static/js/envs.js +++ b/src/main/resources/static/js/envs.js @@ -314,7 +314,7 @@ app.controller("envsCtrl", function($scope, $http, $location, $window) { closeOnConfirm: true, closeOnCancel: true }).then(function(isConfirm){ - if (isConfirm.dismiss != "cancel") { + if (isConfirm.dismiss !== "cancel") { $http({ method: "POST", url: "deleteTenant", diff --git a/src/main/resources/static/js/rolesperms.js b/src/main/resources/static/js/rolesperms.js index 9e180a189f..ed277f66d5 100644 --- a/src/main/resources/static/js/rolesperms.js +++ b/src/main/resources/static/js/rolesperms.js @@ -90,10 +90,10 @@ app.controller("rolesPermsCtrl", function($scope, $http, $location, $window) { }).success(function(output) { $scope.alert = "Tenant add status : "+ output.result; $scope.addTenantId.tenantName = ""; - if(output.result == 'success'){ + if(output.result === 'success'){ swal({ title: "", - text: "Tenant add status : "+output.result, + text: "Tenant add status : " + output.result, timer: 2000, showConfirmButton: false }); diff --git a/src/test/java/io/aiven/klaw/EnvsClustersTenantsControllerIT.java b/src/test/java/io/aiven/klaw/EnvsClustersTenantsControllerIT.java index 6692b77b30..f4f9cf1776 100644 --- a/src/test/java/io/aiven/klaw/EnvsClustersTenantsControllerIT.java +++ b/src/test/java/io/aiven/klaw/EnvsClustersTenantsControllerIT.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KwClustersModel; @@ -86,7 +87,7 @@ public void addTenantSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -122,7 +123,7 @@ public void addClusterSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -177,7 +178,7 @@ public void modifyClusterSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // getclusterdetails success @@ -220,7 +221,7 @@ public void addAndDeleteClusterSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -252,7 +253,7 @@ public void addAndDeleteClusterSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -290,7 +291,7 @@ public void addNewEnvSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -348,7 +349,7 @@ public void modifyEnvSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -408,7 +409,7 @@ public void deleteEnvSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -438,7 +439,7 @@ public void deleteEnvSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // get env params success diff --git a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java index f91288f769..411f48bcaa 100644 --- a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java +++ b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java @@ -19,10 +19,12 @@ import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclRequestsModel; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.KafkaClustersType; import io.aiven.klaw.model.KwClustersModel; import io.aiven.klaw.model.KwPropertiesModel; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.TopicInfo; import io.aiven.klaw.model.TopicOverview; import io.aiven.klaw.model.TopicRequestModel; @@ -105,7 +107,7 @@ public void createRequiredUsers() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); userInfoModel = mockMethods.getUserInfoModel(user2, role, "INFRATEAM"); jsonReq = OBJECT_MAPPER.writer().writeValueAsString(userInfoModel); @@ -141,7 +143,7 @@ public void addNewCluster() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -177,7 +179,7 @@ public void createEnv() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -223,7 +225,7 @@ public void updateTenantConfig() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // Create topic requests @@ -245,7 +247,7 @@ public void createTopicRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // Query topic requests in created state @@ -296,8 +298,9 @@ public void approveTopic() throws Exception { when(clusterApiService.getClusterApiStatus(anyString(), anyBoolean(), anyInt())) .thenReturn("ONLINE"); - when(clusterApiService.approveTopicRequests(topicName, "Create", 2, "1", "1", 101)) - .thenReturn(new ResponseEntity<>("success", HttpStatus.OK)); + when(clusterApiService.approveTopicRequests( + topicName, RequestOperationType.CREATE.value, 2, "1", "1", 101)) + .thenReturn(new ResponseEntity<>(ApiResultStatus.SUCCESS.value, HttpStatus.OK)); String response = mvc.perform( @@ -311,7 +314,7 @@ public void approveTopic() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // decline topic - topic in cluster @@ -334,7 +337,7 @@ public void declineTopicRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); login(user2, PASSWORD, "APPROVER"); @@ -351,7 +354,7 @@ public void declineTopicRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // get team of topic @@ -393,7 +396,7 @@ public void deleteTopicRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -407,7 +410,7 @@ public void deleteTopicRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // get topics from cluster @@ -520,7 +523,7 @@ public void aclRequest() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // Get created acl requests again @@ -564,7 +567,7 @@ public void getAclResAgainAndApprove() throws Exception { Object obj = response.get(0); LinkedHashMap hMap = (LinkedHashMap) obj; - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(clusterApiService.approveAclRequests(any(), anyInt())) .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); Integer reqNo = hMap.get("req_no"); @@ -581,7 +584,7 @@ public void getAclResAgainAndApprove() throws Exception { .getResponse() .getContentAsString(); - assertThat(res).contains("success"); + assertThat(res).contains(ApiResultStatus.SUCCESS.value); } // Request for a acl @@ -603,7 +606,7 @@ public void requestAnAcl() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } // Decline acl request @@ -640,7 +643,7 @@ public void declineAclReq() throws Exception { .getResponse() .getContentAsString(); - assertThat(resNew).contains("success"); + assertThat(resNew).contains(ApiResultStatus.SUCCESS.value); } // delete acl requests @@ -675,7 +678,7 @@ public void deleteAclReq() throws Exception { .getResponse() .getContentAsString(); - assertThat(responseNew).contains("success"); + assertThat(responseNew).contains(ApiResultStatus.SUCCESS.value); } // getacls with topic search filter diff --git a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java index a21b7131fe..92fef8b961 100644 --- a/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java +++ b/src/test/java/io/aiven/klaw/UsersTeamsControllerIT.java @@ -74,7 +74,7 @@ public void createRequiredUsers() throws Exception { .getResponse() .getContentAsString(); - // assertThat(response, CoreMatchers.containsString("success")); + // assertThat(response, CoreMatchers.containsString(ApiResultStatus.SUCCESS.value)); userInfoModel = mockMethods.getUserInfoModel(user2, role, "INFRATEAM"); jsonReq = OBJECT_MAPPER.writer().writeValueAsString(userInfoModel); @@ -91,7 +91,7 @@ public void createRequiredUsers() throws Exception { .getResponse() .getContentAsString(); - // assertThat(response, CoreMatchers.containsString("success")); + // assertThat(response, CoreMatchers.containsString(ApiResultStatus.SUCCESS.value)); } // Create team success @@ -113,7 +113,7 @@ public void createTeamSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -199,7 +199,7 @@ public void modifyTeamSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -260,7 +260,7 @@ public void deleteTeamSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -274,7 +274,7 @@ public void deleteTeamSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( @@ -329,7 +329,7 @@ public void deleteUserSuccess() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); response = mvc.perform( diff --git a/src/test/java/io/aiven/klaw/UtilMethods.java b/src/test/java/io/aiven/klaw/UtilMethods.java index 33ddad88f5..03c60378f5 100644 --- a/src/test/java/io/aiven/klaw/UtilMethods.java +++ b/src/test/java/io/aiven/klaw/UtilMethods.java @@ -131,7 +131,7 @@ public List getAcls() { List allTopicReqs = new ArrayList<>(); Acl topicRequest = new Acl(); topicRequest.setTeamId(3); - topicRequest.setTopictype("Producer"); + topicRequest.setTopictype(AclType.PRODUCER.value); topicRequest.setTenantId(101); allTopicReqs.add(topicRequest); return allTopicReqs; @@ -141,7 +141,7 @@ public List getAclInfoList() { List allTopicReqs = new ArrayList<>(); AclInfo topicRequest = new AclInfo(); topicRequest.setTeamname("Seahorses"); - topicRequest.setTopictype("Producer"); + topicRequest.setTopictype(AclType.PRODUCER.value); allTopicReqs.add(topicRequest); return allTopicReqs; } @@ -153,7 +153,7 @@ public List> getClusterAcls() { aclbindingMap.put("host", "1.1.1.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "GROUP"); aclbindingMap.put("resourceName", "myconsumergroup1"); @@ -162,7 +162,7 @@ public List> getClusterAcls() { aclbindingMap = new HashMap<>(); aclbindingMap.put("host", "2.1.2.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "TOPIC"); aclbindingMap.put("resourceName", "testtopic1"); @@ -171,7 +171,7 @@ public List> getClusterAcls() { aclbindingMap = new HashMap<>(); aclbindingMap.put("host", "2.1.2.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "GROUP"); aclbindingMap.put("resourceName", "mygrp1"); @@ -187,7 +187,7 @@ public List> getClusterAcls2() { aclbindingMap.put("host", "1.1.1.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "GROUP"); aclbindingMap.put("resourceName", "myconsumergroup1"); @@ -196,7 +196,7 @@ public List> getClusterAcls2() { aclbindingMap = new HashMap<>(); aclbindingMap.put("host", "2.1.2.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "TOPIC"); aclbindingMap.put("resourceName", "testtopic"); @@ -205,7 +205,7 @@ public List> getClusterAcls2() { aclbindingMap = new HashMap<>(); aclbindingMap.put("host", "2.1.2.1"); aclbindingMap.put("principle", "User:*"); - aclbindingMap.put("operation", "READ"); + aclbindingMap.put("operation", AclPermissionType.READ.value); aclbindingMap.put("permissionType", "ALLOW"); aclbindingMap.put("resourceType", "GROUP"); aclbindingMap.put("resourceName", "mygrp1"); @@ -233,7 +233,7 @@ public List getAclsForDelete() { topicRequest.setConsumergroup("congrp"); topicRequest.setEnvironment("1"); topicRequest.setAclip("12.22.126.21"); - topicRequest.setTopictype("Producer"); + topicRequest.setTopictype(AclType.PRODUCER.value); allTopicReqs.add(topicRequest); return allTopicReqs; } @@ -242,7 +242,7 @@ public List getAllAcls() { List allTopicReqs = new ArrayList<>(); Acl acl = new Acl(); acl.setTeamId(3); - acl.setTopictype("Producer"); + acl.setTopictype(AclType.PRODUCER.value); allTopicReqs.add(acl); acl = new Acl(); @@ -250,7 +250,7 @@ public List getAllAcls() { acl.setConsumergroup("congrp"); acl.setEnvironment("1"); acl.setAclip("12.22.126.21"); - acl.setTopictype("Producer"); + acl.setTopictype(AclType.PRODUCER.value); acl.setOtherParams("101"); allTopicReqs.add(acl); @@ -304,7 +304,7 @@ public TopicRequest getTopicRequest(int topicId) { topicRequest.setTopicpartitions(2); topicRequest.setReplicationfactor("1"); topicRequest.setEnvironment("1"); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); topicRequest.setDescription("Test desc"); topicRequest.setTenantId(101); return topicRequest; @@ -320,7 +320,7 @@ public TopicRequestModel getTopicRequestModel(int topicId) { topicRequest.setTopicpartitions(2); topicRequest.setReplicationfactor("1"); topicRequest.setEnvironment("1"); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); topicRequest.setDescription("Test desc"); return topicRequest; } @@ -331,11 +331,11 @@ public AclRequests getAclRequest(String topicName) { aclRequest.setEnvironment("1"); aclRequest.setTopicname(topicName); aclRequest.setUsername("kwusera"); - aclRequest.setTopictype("Consumer"); - aclRequest.setAclType("Delete"); + aclRequest.setTopictype(AclType.CONSUMER.value); + aclRequest.setAclType(RequestOperationType.DELETE.value); aclRequest.setConsumergroup("congroup1"); aclRequest.setAcl_ip("10.11.112.113"); - aclRequest.setAclPatternType("LITERAL"); + aclRequest.setAclPatternType(AclPatternType.LITERAL.value); aclRequest.setOtherParams("101"); aclRequest.setTenantId(101); return aclRequest; @@ -347,11 +347,11 @@ public AclRequests getAclRequestCreate(String topicName) { aclRequest.setEnvironment("1"); aclRequest.setTopicname(topicName); aclRequest.setUsername("kwusera"); - aclRequest.setTopictype("Consumer"); - aclRequest.setAclType("Create"); + aclRequest.setTopictype(AclType.CONSUMER.value); + aclRequest.setAclType(RequestOperationType.CREATE.value); aclRequest.setConsumergroup("congroup1"); aclRequest.setAcl_ip("10.11.112.113"); - aclRequest.setAclPatternType("LITERAL"); + aclRequest.setAclPatternType(AclPatternType.LITERAL.value); return aclRequest; } @@ -385,8 +385,8 @@ public List getAclRequestsModel() { AclRequestsModel aclRequests1 = new AclRequestsModel(); aclRequests1.setTeamname("Seahorses"); aclRequests1.setRequestingteam(2); - aclRequests1.setAclType("Create"); - aclRequests1.setAclPatternType("LITERAL"); + aclRequests1.setAclType(RequestOperationType.CREATE.value); + aclRequests1.setAclPatternType(AclPatternType.LITERAL.value); aclRequests.add(aclRequests1); return aclRequests; } @@ -396,8 +396,8 @@ public List getAclRequests() { AclRequests aclRequests1 = new AclRequests(); aclRequests1.setTeamId(3); aclRequests1.setRequestingteam(3); - aclRequests1.setAclType("Create"); - aclRequests1.setAclPatternType("LITERAL"); + aclRequests1.setAclType(RequestOperationType.CREATE.value); + aclRequests1.setAclPatternType(AclPatternType.LITERAL.value); aclRequests.add(aclRequests1); return aclRequests; } @@ -487,13 +487,13 @@ public AclRequestsModel getAclRequestModel(String topic) { aclRequest.setEnvironment("1"); aclRequest.setTopicname(topic); aclRequest.setUsername("kwusera"); - aclRequest.setTopictype("Consumer"); + aclRequest.setTopictype(AclType.CONSUMER.value); aclRequest.setConsumergroup("mygrp1"); ArrayList ipList = new ArrayList<>(); ipList.add("2.1.2.1"); aclRequest.setAcl_ip(ipList); aclRequest.setAcl_ssl(null); - aclRequest.setAclPatternType("LITERAL"); + aclRequest.setAclPatternType(AclPatternType.LITERAL.value); aclRequest.setRequestingteam(1); aclRequest.setTeamname("INFRATEAM"); @@ -532,7 +532,7 @@ public List getSyncAclsUpdates() { SyncAclUpdates syncAclUpdates = new SyncAclUpdates(); syncAclUpdates.setTopicName("testtopic"); syncAclUpdates.setReq_no("101"); - syncAclUpdates.setAclType("Producer"); + syncAclUpdates.setAclType(AclType.PRODUCER.value); syncAclUpdates.setAclIp("12.2.4.55"); syncAclUpdates.setTeamSelected("Team2"); syncAclUpdates.setEnvSelected("DEV"); @@ -540,7 +540,7 @@ public List getSyncAclsUpdates() { SyncAclUpdates syncAclUpdates1 = new SyncAclUpdates(); syncAclUpdates1.setTopicName("testtopic1"); syncAclUpdates1.setReq_no("102"); - syncAclUpdates1.setAclType("Consumer"); + syncAclUpdates1.setAclType(AclType.CONSUMER.value); syncAclUpdates1.setAclIp("12.2.4.55"); syncAclUpdates1.setTeamSelected("Team2"); syncAclUpdates1.setEnvSelected("1"); diff --git a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java index 5a0e0f3913..811eed004f 100644 --- a/src/test/java/io/aiven/klaw/controller/AclControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/AclControllerTest.java @@ -83,7 +83,7 @@ public void createAcl() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -92,7 +92,7 @@ public void updateSyncAcls() throws Exception { String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(syncUpdates); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(aclSyncControllerService.updateSyncAcls(any())).thenReturn(apiResponse); String response = @@ -109,7 +109,7 @@ public void updateSyncAcls() throws Exception { ApiResponse actualResult = new ObjectMapper().readValue(response, new TypeReference<>() {}); - assertThat(actualResult.getResult()).isEqualTo("success"); + assertThat(actualResult.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -160,7 +160,7 @@ public void getCreatedAclRequests() throws Exception { @Test public void deleteAclRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(aclControllerService.deleteAclRequests(anyString())).thenReturn(apiResponse); String response = mvcAcls @@ -174,12 +174,12 @@ public void deleteAclRequests() throws Exception { .getResponse() .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void approveAclRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(aclControllerService.approveAclRequests(anyString())).thenReturn(apiResponse); String response = @@ -194,12 +194,12 @@ public void approveAclRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test public void declineAclRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(aclControllerService.declineAclRequests(anyString(), anyString())).thenReturn(apiResponse); String response = mvcAcls @@ -215,7 +215,7 @@ public void declineAclRequests() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test diff --git a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java index b72dd822eb..1b4679b354 100644 --- a/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/SchemaRegstryControllerTest.java @@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.aiven.klaw.UtilMethods; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SchemaRequestModel; import io.aiven.klaw.service.SchemaRegstryControllerService; import java.util.List; @@ -74,7 +75,7 @@ public void getSchemaRequests() throws Exception { @Test @Order(2) public void deleteSchemaRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(schemaRegstryControllerService.deleteSchemaRequests(anyString())).thenReturn(apiResponse); String response = @@ -88,13 +89,13 @@ public void deleteSchemaRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test @Order(3) public void execSchemaRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(schemaRegstryControllerService.execSchemaRequests(anyString())).thenReturn(apiResponse); String response = @@ -108,7 +109,7 @@ public void execSchemaRequests() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test @@ -116,7 +117,7 @@ public void execSchemaRequests() throws Exception { public void uploadSchema() throws Exception { SchemaRequestModel schemaRequest = utilMethods.getSchemaRequests().get(0); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(schemaRequest); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(schemaRegstryControllerService.uploadSchema(any())).thenReturn(apiResponse); String response = @@ -130,6 +131,6 @@ public void uploadSchema() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } } diff --git a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java index 11be53819d..83b78f879b 100644 --- a/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/TopicControllerTest.java @@ -11,6 +11,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.aiven.klaw.UtilMethods; import io.aiven.klaw.dao.TopicRequest; +import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SyncTopicUpdates; @@ -88,7 +89,7 @@ public void createTopics() throws Exception { .getContentAsString(); Map actualResult = new ObjectMapper().readValue(response, new TypeReference<>() {}); - assertThat(actualResult).containsEntry("result", "success"); + assertThat(actualResult).containsEntry("result", ApiResultStatus.SUCCESS.value); } @Test @@ -96,7 +97,7 @@ public void createTopics() throws Exception { public void updateSyncTopics() throws Exception { List syncTopicUpdates = utilMethods.getSyncTopicUpdates(); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(syncTopicUpdates); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(topicSyncControllerService.updateSyncTopics(any())).thenReturn(apiResponse); String response = @@ -113,7 +114,7 @@ public void updateSyncTopics() throws Exception { ApiResponse actualResult = new ObjectMapper().readValue(response, new TypeReference<>() {}); - assertThat(actualResult.getResult()).isEqualTo("success"); + assertThat(actualResult.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -144,7 +145,8 @@ public void getTopicTeam() throws Exception { String topicName = "testtopic"; Map teamMap = new HashMap<>(); teamMap.put("team", "Team1"); - when(topicControllerService.getTopicTeamOnly(topicName, "LITERAL")).thenReturn(teamMap); + when(topicControllerService.getTopicTeamOnly(topicName, AclPatternType.LITERAL.value)) + .thenReturn(teamMap); String res = mvc.perform( @@ -185,7 +187,7 @@ public void getCreatedTopicRequests() throws Exception { @Test @Order(6) public void deleteTopicRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(topicControllerService.deleteTopicRequests(anyString())).thenReturn(apiResponse); String response = @@ -200,7 +202,7 @@ public void deleteTopicRequests() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -222,13 +224,13 @@ public void approveTopicRequests() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(8) public void declineTopicRequests() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(topicControllerService.declineTopicRequests(anyString(), anyString())) .thenReturn(apiResponse); @@ -245,7 +247,7 @@ public void declineTopicRequests() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test diff --git a/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java b/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java index 38f236df96..4410f463d1 100644 --- a/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java +++ b/src/test/java/io/aiven/klaw/controller/UiConfigControllerTest.java @@ -22,7 +22,6 @@ import io.aiven.klaw.service.EnvsClustersTenantsControllerService; import io.aiven.klaw.service.UiConfigControllerService; import io.aiven.klaw.service.UsersTeamsControllerService; -import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; @@ -218,7 +217,8 @@ public void getAllTeamsSUOnly() throws Exception { public void addNewEnv() throws Exception { EnvModel env = utilMethods.getEnvList().get(0); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(env); - when(envsClustersTenantsControllerService.addNewEnv(any())).thenReturn("success"); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); + when(envsClustersTenantsControllerService.addNewEnv(any())).thenReturn(apiResponse); String response = mvcEnvs @@ -232,16 +232,16 @@ public void addNewEnv() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).isEqualTo("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(9) public void deleteEnv() throws Exception { - Map hashMap = new HashMap<>(); - hashMap.put("result", "success"); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(envsClustersTenantsControllerService.deleteEnvironment(anyString(), anyString())) - .thenReturn(hashMap); + .thenReturn(apiResponse); String response = mvcEnvs @@ -256,7 +256,8 @@ public void deleteEnv() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -278,13 +279,13 @@ public void deleteTeam() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(11) public void deleteUser() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(usersTeamsControllerService.deleteUser(anyString(), anyBoolean())).thenReturn(apiResponse); String response = @@ -300,13 +301,13 @@ public void deleteUser() throws Exception { .getContentAsString(); ApiResponse objectResponse = new ObjectMapper().readValue(response, ApiResponse.class); - assertThat(objectResponse.getResult()).isEqualTo("success"); + assertThat(objectResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(12) public void addNewUser() throws Exception { - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); UserInfoModel userInfo = utilMethods.getUserInfoMock(); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(userInfo); when(usersTeamsControllerService.addNewUser(any(), anyBoolean())).thenReturn(apiResponse); @@ -323,7 +324,7 @@ public void addNewUser() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test @@ -331,7 +332,7 @@ public void addNewUser() throws Exception { public void addNewTeam() throws Exception { Team team = utilMethods.getTeams().get(0); String jsonReq = OBJECT_MAPPER.writer().writeValueAsString(team); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(usersTeamsControllerService.addNewTeam(any(), anyBoolean())).thenReturn(apiResponse); String response = @@ -346,7 +347,7 @@ public void addNewTeam() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test @@ -367,7 +368,7 @@ public void changePwd() throws Exception { .getResponse() .getContentAsString(); - assertThat(response).contains("success"); + assertThat(response).contains(ApiResultStatus.SUCCESS.value); } @Test diff --git a/src/test/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbcTest.java b/src/test/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbcTest.java index 461a626a32..37eac64ab5 100644 --- a/src/test/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbcTest.java +++ b/src/test/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbcTest.java @@ -6,6 +6,7 @@ import io.aiven.klaw.UtilMethods; import io.aiven.klaw.dao.Env; import io.aiven.klaw.dao.EnvID; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.repository.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,19 +52,19 @@ public void setUp() { @Test public void deleteTopicRequest() { String result = deleteDataJdbc.deleteTopicRequest(1001, 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void deleteSchemaRequest() { String result = deleteDataJdbc.deleteSchemaRequest(1001, 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void deleteAclRequest() { String result = deleteDataJdbc.deleteAclRequest(1001, 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -77,19 +78,19 @@ public void deleteEnvironmentRequest() { when(envRepo.findById(env)).thenReturn(java.util.Optional.of(envObj)); String result = deleteDataJdbc.deleteEnvironment("1", 101); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void deleteUserRequest() { String result = deleteDataJdbc.deleteUserRequest("uiuser1"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void deleteTeamRequest() { String result = deleteDataJdbc.deleteTeamRequest(1, 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -97,6 +98,6 @@ public void deletePrevAclRecs() { when(aclRepo.findAllByTenantId(101)).thenReturn(utilMethods.getAllAcls()); String result = deleteDataJdbc.deletePrevAclRecs(utilMethods.getAclRequest("testtopic")); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } } diff --git a/src/test/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbcTest.java b/src/test/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbcTest.java index a5e9726785..e76c738061 100644 --- a/src/test/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbcTest.java +++ b/src/test/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbcTest.java @@ -13,6 +13,7 @@ import io.aiven.klaw.dao.Topic; import io.aiven.klaw.dao.TopicRequest; import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.repository.AclRepo; import io.aiven.klaw.repository.AclRequestsRepo; import io.aiven.klaw.repository.ActivityLogRepo; @@ -90,7 +91,7 @@ public void insertIntoRequestTopic() { when(activityLogRepo.getNextActivityLogRequestId(anyInt())).thenReturn(101); Map result = insertData.insertIntoRequestTopic(topicRequest); - assertThat(result).containsEntry("result", "success"); + assertThat(result).containsEntry("result", ApiResultStatus.SUCCESS.value); } @Test @@ -98,7 +99,7 @@ public void insertIntoTopicSOT() { List topics = utilMethods.getTopics(); when(topicRepo.getNextTopicRequestId(anyInt())).thenReturn(101); String result = insertData.insertIntoTopicSOT(topics, true); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -109,7 +110,7 @@ public void insertIntoRequestAcl() { when(jdbcSelectHelper.selectUserInfo(anyString())).thenReturn(userInfo, userInfo); String result = insertData.insertIntoRequestAcl(utilMethods.getAclRequest("testtopic")).get("result"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -117,7 +118,7 @@ public void insertIntoAclsSOT() { List acls = utilMethods.getAcls(); when(aclRepo.getNextAclId(anyInt())).thenReturn(101); String result = insertData.insertIntoAclsSOT(acls, true); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -129,7 +130,7 @@ public void insertIntoRequestSchema() { when(jdbcSelectHelper.selectUserInfo(anyString())).thenReturn(userInfo, userInfo); String result = insertData.insertIntoRequestSchema(schemaRequest); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -137,26 +138,26 @@ public void insertIntoMessageSchemaSOT() { List schemas = utilMethods.getMSchemas(); when(messageSchemaRepo.getNextSchemaId(anyInt())).thenReturn(101); String result = insertData.insertIntoMessageSchemaSOT(schemas); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void insertIntoUsers() { String result = insertData.insertIntoUsers(utilMethods.getUserInfoMockDao()); when(userInfoRepo.findById(anyString())).thenReturn(java.util.Optional.of(new UserInfo())); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void insertIntoTeams() { String result = insertData.insertIntoTeams(utilMethods.getTeams().get(0)); when(teamRepo.getNextTeamId(anyInt())).thenReturn(101); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void insertIntoEnvs() { String result = insertData.insertIntoEnvs(new Env()); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } } diff --git a/src/test/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbcTest.java b/src/test/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbcTest.java index 91e5990581..058314da2d 100644 --- a/src/test/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbcTest.java +++ b/src/test/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbcTest.java @@ -6,6 +6,7 @@ import io.aiven.klaw.UtilMethods; import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.repository.AclRequestsRepo; import io.aiven.klaw.repository.SchemaRequestRepo; import io.aiven.klaw.repository.TopicRequestsRepo; @@ -55,38 +56,40 @@ public void setUp() throws Exception { @Test public void declineTopicRequest() { String result = updateData.declineTopicRequest(utilMethods.getTopicRequest(1001), "uiuser2"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void updateTopicRequest() { - when(insertDataJdbcHelper.insertIntoTopicSOT(any(), eq(false))).thenReturn("success"); + when(insertDataJdbcHelper.insertIntoTopicSOT(any(), eq(false))) + .thenReturn(ApiResultStatus.SUCCESS.value); when(insertDataJdbcHelper.getNextTopicRequestId(anyString(), anyInt())).thenReturn(1001); String result = updateData.updateTopicRequest(utilMethods.getTopicRequest(1001), "uiuser2"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void updateAclRequest() { - when(insertDataJdbcHelper.insertIntoAclsSOT(any(), eq(false))).thenReturn("success"); + when(insertDataJdbcHelper.insertIntoAclsSOT(any(), eq(false))) + .thenReturn(ApiResultStatus.SUCCESS.value); String result = updateData.updateAclRequest(utilMethods.getAclRequestCreate("testtopic"), "uiuser2", "{}"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void updateAclRequest1() { - when(deleteDataJdbcHelper.deletePrevAclRecs(any())).thenReturn("success"); + when(deleteDataJdbcHelper.deletePrevAclRecs(any())).thenReturn(ApiResultStatus.SUCCESS.value); String result = updateData.updateAclRequest(utilMethods.getAclRequest("testtopic"), "uiuser2", "{}"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void declineAclRequest() { String result = updateData.declineAclRequest(utilMethods.getAclRequest("testtopic"), "uiuser2"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -94,13 +97,13 @@ public void updatePassword() { String user = "uiuser1"; when(userInfoRepo.findById(user)).thenReturn(Optional.of(userInfo)); String result = updateData.updatePassword(user, "pwd"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test public void updateSchemaRequest() { String result = updateData.updateSchemaRequest(utilMethods.getSchemaRequestsDao().get(0), "uiuser1"); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } } diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index 39fc2df4c1..ea7f4ba1e2 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -21,7 +21,9 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclInfo; +import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.AclRequestsModel; +import io.aiven.klaw.model.AclType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SyncAclUpdates; @@ -117,27 +119,27 @@ public void createAcl() throws KlawException { copyProperties(aclRequests, aclRequestsDao); List topicList = utilMethods.getTopics(); Map hashMap = new HashMap<>(); - hashMap.put("result", "success"); + hashMap.put("result", ApiResultStatus.SUCCESS.value); when(handleDbRequests.getTopics(anyString(), anyInt())).thenReturn(topicList); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); stubUserInfo(); ApiResponse resultResp = aclControllerService.createAcl(aclRequests); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(2) public void updateSyncAcls() throws KlawException { stubUserInfo(); - when(handleDbRequests.addToSyncacls(anyList())).thenReturn("success"); + when(handleDbRequests.addToSyncacls(anyList())).thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); ApiResponse resultResp = aclSyncControllerService.updateSyncAcls(utilMethods.getSyncAclsUpdates()); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -232,7 +234,8 @@ public void getCreatedAclRequests() { @Order(9) public void deleteAclRequests() throws KlawException { String req_no = "1001"; - when(handleDbRequests.deleteAclRequest(Integer.parseInt(req_no), 1)).thenReturn("success"); + when(handleDbRequests.deleteAclRequest(Integer.parseInt(req_no), 1)) + .thenReturn(ApiResultStatus.SUCCESS.value); ApiResponse result = aclControllerService.deleteAclRequests(req_no); // assertThat(result).isEqualTo("{\"result\":\"null\"}"); } @@ -255,15 +258,16 @@ public void approveAclRequests() throws KlawException { stubUserInfo(); when(handleDbRequests.selectAcl(anyInt(), anyInt())).thenReturn(aclReq); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(clusterApiService.approveAclRequests(any(), anyInt())) .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); - when(handleDbRequests.updateAclRequest(any(), any(), anyString())).thenReturn("success"); + when(handleDbRequests.updateAclRequest(any(), any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); ApiResponse apiResp = aclControllerService.approveAclRequests("112"); - assertThat(apiResp.getResult()).isEqualTo("success"); + assertThat(apiResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -295,7 +299,7 @@ public void approveAclRequestsFailure2() throws KlawException { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(clusterApiService.approveAclRequests(any(), anyInt())) .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(handleDbRequests.updateAclRequest(any(), any(), anyString())) @@ -331,10 +335,11 @@ public void declineAclRequests() throws KlawException { when(handleDbRequests.selectAcl(anyInt(), anyInt())).thenReturn(aclReq); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - when(handleDbRequests.declineAclRequest(any(), any())).thenReturn("success"); + when(handleDbRequests.declineAclRequest(any(), any())) + .thenReturn(ApiResultStatus.SUCCESS.value); ApiResponse resultResp = aclControllerService.declineAclRequests(req_no, ""); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -492,7 +497,7 @@ private List getAclsSOT0() { aclReq.setAclip("2.1.2.1"); aclReq.setAclssl(null); aclReq.setConsumergroup("mygrp1"); - aclReq.setTopictype("Consumer"); + aclReq.setTopictype(AclType.CONSUMER.value); aclList.add(aclReq); @@ -510,7 +515,7 @@ private List getAclsSOT(String topicName) { aclReq.setAclssl(null); aclReq.setEnvironment("1"); aclReq.setConsumergroup("mygrp1"); - aclReq.setTopictype("Consumer"); + aclReq.setTopictype(AclType.CONSUMER.value); aclList.add(aclReq); @@ -524,7 +529,7 @@ private AclRequestsModel getAclRequest() { aclReq.setRequestingteam(1); aclReq.setReq_no(112); aclReq.setEnvironment("1"); - aclReq.setAclPatternType("LITERAL"); + aclReq.setAclPatternType(AclPatternType.LITERAL.value); return aclReq; } diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index c8dddd78f4..ce04dc8f94 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -19,6 +19,8 @@ import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.AclIPPrincipleType; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.RequestOperationType; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -67,7 +69,7 @@ public class ClusterApiServiceTest { public void setUp() { utilMethods = new UtilMethods(); clusterApiService = new ClusterApiService(manageDatabase); - response = new ResponseEntity<>("success", HttpStatus.OK); + response = new ResponseEntity<>(ApiResultStatus.SUCCESS.value, HttpStatus.OK); this.env = new Env(); env.setName("DEV"); @@ -83,13 +85,13 @@ public void getStatusSuccess() { when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(String.class))) .thenReturn(response); String result = clusterApiService.getClusterApiStatus("/topics/getApiStatus", false, 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); result = clusterApiService.getSchemaClusterStatus("", 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); result = clusterApiService.getKafkaClusterStatus("", "PLAINTEXT", "", "", 1); - assertThat(result).isEqualTo("success"); + assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -179,7 +181,7 @@ public void approveTopicRequestsSuccess() throws KlawException { TopicRequest topicRequest = new TopicRequest(); topicRequest.setTopicname("testtopic"); topicRequest.setEnvironment("DEV"); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); @@ -191,8 +193,9 @@ public void approveTopicRequestsSuccess() throws KlawException { .thenReturn(response); ResponseEntity response = - clusterApiService.approveTopicRequests(topicName, "Create", 1, "1", "", 1); - assertThat(response.getBody()).isEqualTo("success"); + clusterApiService.approveTopicRequests( + topicName, RequestOperationType.CREATE.value, 1, "1", "", 1); + assertThat(response.getBody()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -202,7 +205,7 @@ public void approveTopicRequestsFailure() throws KlawException { TopicRequest topicRequest = new TopicRequest(); topicRequest.setTopicname("testtopic"); topicRequest.setEnvironment("DEV"); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getClusters(anyString(), anyInt())).thenReturn(clustersHashMap); @@ -214,7 +217,9 @@ public void approveTopicRequestsFailure() throws KlawException { .thenThrow(new RuntimeException("error")); assertThatThrownBy( - () -> clusterApiService.approveTopicRequests(topicName, "Create", 1, "1", "", 1)) + () -> + clusterApiService.approveTopicRequests( + topicName, RequestOperationType.CREATE.value, 1, "1", "", 1)) .isInstanceOf(KlawException.class); } @@ -225,10 +230,10 @@ public void approveAclRequestsSuccess1() throws KlawException { aclRequests.setReq_no(1001); aclRequests.setEnvironment("DEV"); aclRequests.setTopicname("testtopic"); - aclRequests.setAclType("Create"); + aclRequests.setAclType(RequestOperationType.CREATE.value); aclRequests.setAclIpPrincipleType(AclIPPrincipleType.IP_ADDRESS); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); ResponseEntity responseEntity = new ResponseEntity<>(apiResponse, HttpStatus.OK); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); @@ -246,7 +251,7 @@ public void approveAclRequestsSuccess1() throws KlawException { .thenReturn(responseEntity); ResponseEntity response = clusterApiService.approveAclRequests(aclRequests, 1); - assertThat(response.getBody().getResult()).isEqualTo("success"); + assertThat(response.getBody().getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -256,10 +261,10 @@ public void approveAclRequestsSuccess2() throws KlawException { aclRequests.setReq_no(1001); aclRequests.setEnvironment("DEV"); aclRequests.setTopicname("testtopic"); - aclRequests.setAclType("Delete"); + aclRequests.setAclType(RequestOperationType.DELETE.value); aclRequests.setAclIpPrincipleType(AclIPPrincipleType.IP_ADDRESS); - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); ResponseEntity responseEntity = new ResponseEntity<>(apiResponse, HttpStatus.OK); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); @@ -277,7 +282,7 @@ public void approveAclRequestsSuccess2() throws KlawException { .thenReturn(responseEntity); ResponseEntity response = clusterApiService.approveAclRequests(aclRequests, 1); - assertThat(response.getBody().getResult()).isEqualTo("success"); + assertThat(response.getBody().getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -287,7 +292,7 @@ public void approveAclRequestsFailure() throws KlawException { aclRequests.setReq_no(1001); aclRequests.setEnvironment("DEV"); aclRequests.setTopicname("testtopic"); - aclRequests.setAclType("Create"); + aclRequests.setAclType(RequestOperationType.CREATE.value); assertThatThrownBy(() -> clusterApiService.approveAclRequests(aclRequests, 1)) .isInstanceOf(KlawException.class); @@ -301,7 +306,7 @@ public void postSchemaSucess() throws KlawException { String envSel = "DEV"; String topicName = "testtopic"; - ApiResponse apiResponse = ApiResponse.builder().result("success").build(); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); ResponseEntity response = new ResponseEntity<>(apiResponse, HttpStatus.OK); when(handleDbRequests.selectEnvDetails(anyString(), anyInt())).thenReturn(this.env); @@ -315,7 +320,7 @@ public void postSchemaSucess() throws KlawException { ResponseEntity result = clusterApiService.postSchema(schemaRequest, envSel, topicName, 1); - assertThat(result.getBody().getResult()).isEqualTo("success"); + assertThat(result.getBody().getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test diff --git a/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java index 56edd187d7..bc704eeb5a 100644 --- a/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java @@ -15,6 +15,7 @@ import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; import io.aiven.klaw.model.ApiResponse; +import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SchemaRequestModel; import java.sql.Timestamp; import java.util.ArrayList; @@ -119,9 +120,10 @@ public void deleteSchemaRequestsSuccess() throws KlawException { int schemaReqId = 1001; stubUserInfo(); - when(handleDbRequests.deleteSchemaRequest(anyInt(), anyInt())).thenReturn("success"); + when(handleDbRequests.deleteSchemaRequest(anyInt(), anyInt())) + .thenReturn(ApiResultStatus.SUCCESS.value); ApiResponse resultResp = schemaRegstryControllerService.deleteSchemaRequests("" + schemaReqId); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -157,14 +159,15 @@ public void execSchemaRequestsSuccess() throws KlawException { when(handleDbRequests.selectSchemaRequest(anyInt(), anyInt())).thenReturn(schemaRequest); when(clusterApiService.postSchema(any(), anyString(), anyString(), anyInt())) .thenReturn(response); - when(handleDbRequests.updateSchemaRequest(any(), anyString())).thenReturn("success"); + when(handleDbRequests.updateSchemaRequest(any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); ApiResponse resultResp = schemaRegstryControllerService.execSchemaRequests("" + schemaReqId); - assertThat(resultResp.getResult()).contains("success"); + assertThat(resultResp.getResult()).contains(ApiResultStatus.SUCCESS.value); } @Test @@ -184,7 +187,8 @@ public void execSchemaRequestsFailure1() throws KlawException { when(handleDbRequests.selectSchemaRequest(anyInt(), anyInt())).thenReturn(schemaRequest); when(clusterApiService.postSchema(any(), anyString(), anyString(), anyInt())) .thenReturn(response); - when(handleDbRequests.updateSchemaRequest(any(), anyString())).thenReturn("success"); + when(handleDbRequests.updateSchemaRequest(any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); @@ -247,11 +251,11 @@ public void uploadSchemaSuccess() throws KlawException { .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); - when(handleDbRequests.requestForSchema(any())).thenReturn("success"); + when(handleDbRequests.requestForSchema(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(handleDbRequests.getTopicTeam(anyString(), anyInt())).thenReturn(List.of(topic)); ApiResponse resultResp = schemaRegstryControllerService.uploadSchema(schemaRequest); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index c65200e905..dd28b4e6f1 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -20,6 +20,7 @@ import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwTenantConfigModel; +import io.aiven.klaw.model.RequestOperationType; import io.aiven.klaw.model.SyncTopicUpdates; import io.aiven.klaw.model.TopicInfo; import io.aiven.klaw.model.TopicRequestModel; @@ -127,7 +128,7 @@ private void loginMock() { @Order(1) public void createTopicsSuccess() throws KlawException { Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); + resultMap.put("result", ApiResultStatus.SUCCESS.value); when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); @@ -142,14 +143,14 @@ public void createTopicsSuccess() throws KlawException { ApiResponse apiResponse = topicControllerService.createTopicsRequest(getCorrectTopic()); - assertThat(apiResponse.getResult()).isEqualTo("success"); + assertThat(apiResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(2) public void createTopicsSuccess1() throws KlawException { Map resultMap = new HashMap<>(); - resultMap.put("result", "success"); + resultMap.put("result", ApiResultStatus.SUCCESS.value); when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); @@ -164,7 +165,7 @@ public void createTopicsSuccess1() throws KlawException { ApiResponse apiResponse = topicControllerService.createTopicsRequest(getFailureTopic()); - assertThat(apiResponse.getResult()).isEqualTo("success"); + assertThat(apiResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } // invalid partitions @@ -220,12 +221,12 @@ public void updateSyncTopicsSuccess() throws KlawException { when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - when(handleDbRequests.addToSynctopics(any())).thenReturn("success"); + when(handleDbRequests.addToSynctopics(any())).thenReturn(ApiResultStatus.SUCCESS.value); ApiResponse result = topicSyncControllerService.updateSyncTopics(utilMethods.getSyncTopicUpdates()); - assertThat(result.getResult()).isEqualTo("success"); + assertThat(result.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -312,10 +313,11 @@ public void getCreatedTopicRequests2() { @Test @Order(12) public void deleteTopicRequests() throws KlawException { - when(handleDbRequests.deleteTopicRequest(anyInt(), anyInt())).thenReturn("success"); + when(handleDbRequests.deleteTopicRequest(anyInt(), anyInt())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); ApiResponse resultResp = topicControllerService.deleteTopicRequests("1001"); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -327,16 +329,17 @@ public void approveTopicRequestsSuccess() throws KlawException { stubUserInfo(); when(handleDbRequests.selectTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); - when(handleDbRequests.updateTopicRequest(any(), anyString())).thenReturn("success"); + when(handleDbRequests.updateTopicRequest(any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(clusterApiService.approveTopicRequests( anyString(), anyString(), anyInt(), anyString(), anyString(), anyInt())) - .thenReturn(new ResponseEntity<>("success", HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(ApiResultStatus.SUCCESS.value, HttpStatus.OK)); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); ApiResponse apiResponse = topicControllerService.approveTopicRequests(topicId + ""); - assertThat(apiResponse.getResult()).isEqualTo("success"); + assertThat(apiResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -348,7 +351,8 @@ public void approveTopicRequestsFailure1() throws KlawException { stubUserInfo(); when(handleDbRequests.selectTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); - when(handleDbRequests.updateTopicRequest(any(), anyString())).thenReturn("success"); + when(handleDbRequests.updateTopicRequest(any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); when(clusterApiService.approveTopicRequests( anyString(), anyString(), anyInt(), anyString(), anyString(), anyInt())) .thenReturn(new ResponseEntity<>("failure", HttpStatus.OK)); @@ -451,10 +455,11 @@ public void declineTopicRequests() throws KlawException { when(commonUtilsService.isNotAuthorizedUser(any(), any())).thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - when(handleDbRequests.declineTopicRequest(any(), anyString())).thenReturn("success"); + when(handleDbRequests.declineTopicRequest(any(), anyString())) + .thenReturn(ApiResultStatus.SUCCESS.value); ApiResponse resultResp = topicControllerService.declineTopicRequests(topicId + "", "Reason"); - assertThat(resultResp.getResult()).isEqualTo("success"); + assertThat(resultResp.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -552,7 +557,7 @@ private TopicRequest getTopicRequest(String name) { topicRequest.setTeamId(101); topicRequest.setTopicstatus("created"); topicRequest.setRequestor("kwuserb"); - topicRequest.setTopictype("Create"); + topicRequest.setTopictype(RequestOperationType.CREATE.value); return topicRequest; } From a70d8a3efb54ceca1763493810a13728cce9c803 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Thu, 6 Oct 2022 11:41:12 +0200 Subject: [PATCH 12/15] Updating api responses for cluster apis --- .../aiven/klaw/service/ClusterApiService.java | 28 +++++++---------- .../KafkaConnectControllerService.java | 31 +++++++++++-------- .../klaw/service/TopicControllerService.java | 6 ++-- .../service/TopicSyncControllerService.java | 7 +++-- .../io/aiven/klaw/TopicAclControllerIT.java | 3 +- .../klaw/service/ClusterApiServiceTest.java | 28 +++++++++++------ .../service/TopicControllerServiceTest.java | 12 ++++--- 7 files changed, 65 insertions(+), 50 deletions(-) diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index 1f02389c95..c468a80973 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -134,21 +134,19 @@ public String getClusterApiStatus(String clusterApiUrl, boolean testConnection, log.info( "getClusterApiStatus clusterApiUrl {} testConnection{}", clusterApiUrl, testConnection); getClusterApiProperties(tenantId); - String clusterStatus; try { String uriClusterApiStatus = "/topics/getApiStatus"; String uri; if (testConnection) uri = clusterApiUrl + uriClusterApiStatus; else uri = clusterConnUrl + uriClusterApiStatus; // from stored kw props - ResponseEntity resultBody = - getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); - clusterStatus = resultBody.getBody(); + ResponseEntity resultBody = + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), ClusterStatus.class); + return Objects.requireNonNull(resultBody.getBody()).value; } catch (Exception e) { log.error("Error from getClusterApiStatus ", e); return ClusterStatus.OFFLINE.value; } - return clusterStatus; } String getSchemaClusterStatus(String host, int tenantId) { @@ -157,14 +155,13 @@ String getSchemaClusterStatus(String host, int tenantId) { String clusterStatus; try { String uri = host + "/subjects"; - ResponseEntity resultBody = - getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); - clusterStatus = resultBody.getBody(); + ResponseEntity resultBody = + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), ClusterStatus.class); + return Objects.requireNonNull(resultBody.getBody()).value; } catch (Exception e) { log.error("Error from getSchemaClusterStatus ", e); return ClusterStatus.OFFLINE.value; } - return clusterStatus; } String getKafkaClusterStatus( @@ -188,14 +185,13 @@ String getKafkaClusterStatus( + "/" + clusterType; - ResponseEntity resultBody = - getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), String.class); - clusterStatus = resultBody.getBody(); + ResponseEntity resultBody = + getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), ClusterStatus.class); + return Objects.requireNonNull(resultBody.getBody()).value; } catch (Exception e) { log.error("Error from getKafkaClusterStatus ", e); return ClusterStatus.NOT_KNOWN.value; } - return clusterStatus; } public List> getConsumerOffsets( @@ -431,7 +427,7 @@ public String approveConnectorRequests( } } - public ResponseEntity approveTopicRequests( + public ResponseEntity approveTopicRequests( String topicName, String topicRequestType, int topicPartitions, @@ -441,7 +437,7 @@ public ResponseEntity approveTopicRequests( throws KlawException { log.info("approveTopicRequests {} {}", topicName, topicEnvId); getClusterApiProperties(tenantId); - ResponseEntity response; + ResponseEntity response; ClusterTopicRequest clusterTopicRequest; try { Env envSelected = manageDatabase.getHandleDbRequests().selectEnvDetails(topicEnvId, tenantId); @@ -477,7 +473,7 @@ public ResponseEntity approveTopicRequests( HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity<>(clusterTopicRequest, headers); - response = getRestTemplate().postForEntity(uri, request, String.class); + response = getRestTemplate().postForEntity(uri, request, ApiResponse.class); } catch (Exception e) { log.error("approveTopicRequests {}", topicName, e); throw new KlawException("Could not approve topic request. Please contact Administrator."); diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index a1d8726b60..b3d4cb1b68 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -688,7 +688,7 @@ public ApiResponse createConnectorDeleteRequest(String connectorName, String env int tenantId = commonUtilsService.getTenantId(getUserName()); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); - KafkaConnectorRequest topicRequestReq = new KafkaConnectorRequest(); + KafkaConnectorRequest kafkaConnectorRequest = new KafkaConnectorRequest(); List topics = getConnectorsFromName(connectorName, tenantId); Integer userTeamId = getMyTeamId(userDetails); @@ -701,24 +701,26 @@ public ApiResponse createConnectorDeleteRequest(String connectorName, String env .build(); } - topicRequestReq.setRequestor(userDetails); - topicRequestReq.setUsername(userDetails); - topicRequestReq.setTeamId(userTeamId); - topicRequestReq.setEnvironment(envId); - topicRequestReq.setConnectorName(connectorName); - topicRequestReq.setConnectortype(TopicRequestTypes.Delete.name()); + kafkaConnectorRequest.setRequestor(userDetails); + kafkaConnectorRequest.setUsername(userDetails); + kafkaConnectorRequest.setTeamId(userTeamId); + kafkaConnectorRequest.setEnvironment(envId); + kafkaConnectorRequest.setConnectorName(connectorName); + kafkaConnectorRequest.setConnectortype(TopicRequestTypes.Delete.name()); + kafkaConnectorRequest.setTenantId(tenantId); Optional topicOb = getConnectorsFromName(connectorName, tenantId).stream() .filter( - topic -> Objects.equals(topic.getEnvironment(), topicRequestReq.getEnvironment())) + topic -> + Objects.equals(topic.getEnvironment(), kafkaConnectorRequest.getEnvironment())) .findFirst(); if (manageDatabase .getHandleDbRequests() .selectConnectorRequests( - topicRequestReq.getConnectorName(), - topicRequestReq.getEnvironment(), + kafkaConnectorRequest.getConnectorName(), + kafkaConnectorRequest.getEnvironment(), RequestStatus.created.name(), tenantId) .size() @@ -730,9 +732,9 @@ public ApiResponse createConnectorDeleteRequest(String connectorName, String env if (topicOb.isPresent()) { - topicRequestReq.setConnectorConfig(topicOb.get().getConnectorConfig()); + kafkaConnectorRequest.setConnectorConfig(topicOb.get().getConnectorConfig()); mailService.sendMail( - topicRequestReq.getConnectorName(), + kafkaConnectorRequest.getConnectorName(), null, "", userDetails, @@ -742,7 +744,10 @@ public ApiResponse createConnectorDeleteRequest(String connectorName, String env try { String result = - manageDatabase.getHandleDbRequests().requestForConnector(topicRequestReq).get("result"); + manageDatabase + .getHandleDbRequests() + .requestForConnector(kafkaConnectorRequest) + .get("result"); return ApiResponse.builder().result(result).build(); } catch (Exception e) { log.error(e.getMessage()); diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index 1230712f0f..56fef84c93 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -723,7 +723,7 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) updateTopicReqStatus = dbHandle.updateTopicRequestStatus(topicRequest, userDetails); } else { - ResponseEntity response = + ResponseEntity response = clusterApiService.approveTopicRequests( topicRequest.getTopicname(), topicRequest.getTopictype(), @@ -732,9 +732,9 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { topicRequest.getEnvironment(), tenantId); - updateTopicReqStatus = response.getBody(); + updateTopicReqStatus = Objects.requireNonNull(response.getBody()).getResult(); - if (ApiResultStatus.SUCCESS.value.equals(response.getBody())) { + if (ApiResultStatus.SUCCESS.value.equals(response.getBody().getResult())) { setTopicHistory(topicRequest, userDetails, tenantId); updateTopicReqStatus = dbHandle.updateTopicRequest(topicRequest, userDetails); mailService.sendMail( diff --git a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index d0282c19fd..dfd61744c0 100644 --- a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -541,7 +541,7 @@ private void approveSyncBackTopics( Topic topicFound, int tenantId) { try { - ResponseEntity response = + ResponseEntity response = clusterApiService.approveTopicRequests( topicFound.getTopicname(), RequestOperationType.CREATE.value, @@ -550,9 +550,10 @@ private void approveSyncBackTopics( syncBackTopics.getTargetEnv(), tenantId); - if (!Objects.equals(response.getBody(), ApiResultStatus.SUCCESS.value)) { + if (!Objects.equals( + Objects.requireNonNull(response.getBody()).getResult(), ApiResultStatus.SUCCESS.value)) { log.error("Error in creating topic {} {}", topicFound, response.getBody()); - if (response.getBody().contains("TopicExistsException")) + if (Objects.requireNonNull(response.getBody()).getResult().contains("TopicExistsException")) logUpdateSyncBackTopics.add( "Error in Topic creation. Topic:" + topicFound.getTopicname() diff --git a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java index 411f48bcaa..8f6683abaa 100644 --- a/src/test/java/io/aiven/klaw/TopicAclControllerIT.java +++ b/src/test/java/io/aiven/klaw/TopicAclControllerIT.java @@ -297,10 +297,11 @@ public void approveTopic() throws Exception { String topicName = this.topicName + topicId; when(clusterApiService.getClusterApiStatus(anyString(), anyBoolean(), anyInt())) .thenReturn("ONLINE"); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); when(clusterApiService.approveTopicRequests( topicName, RequestOperationType.CREATE.value, 2, "1", "1", 101)) - .thenReturn(new ResponseEntity<>(ApiResultStatus.SUCCESS.value, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); String response = mvc.perform( diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index ce04dc8f94..0b387648c4 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -20,11 +20,13 @@ import io.aiven.klaw.model.AclIPPrincipleType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.ClusterStatus; import io.aiven.klaw.model.RequestOperationType; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; @@ -82,16 +84,18 @@ public void setUp() { @Order(1) public void getStatusSuccess() { - when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(String.class))) + ResponseEntity response = + new ResponseEntity<>(ClusterStatus.ONLINE, HttpStatus.OK); + when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(ClusterStatus.class))) .thenReturn(response); String result = clusterApiService.getClusterApiStatus("/topics/getApiStatus", false, 1); - assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); + assertThat(result).isEqualTo(ClusterStatus.ONLINE.value); result = clusterApiService.getSchemaClusterStatus("", 1); - assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); + assertThat(result).isEqualTo(ClusterStatus.ONLINE.value); result = clusterApiService.getKafkaClusterStatus("", "PLAINTEXT", "", "", 1); - assertThat(result).isEqualTo(ApiResultStatus.SUCCESS.value); + assertThat(result).isEqualTo(ClusterStatus.ONLINE.value); } @Test @@ -177,6 +181,11 @@ public void getAllTopicsFailure() throws Exception { @Test @Order(7) public void approveTopicRequestsSuccess() throws KlawException { + ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); + ResponseEntity response = + new ResponseEntity<>( + ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(), HttpStatus.OK); + String topicName = "testtopic"; TopicRequest topicRequest = new TopicRequest(); topicRequest.setTopicname("testtopic"); @@ -189,18 +198,19 @@ public void approveTopicRequestsSuccess() throws KlawException { when(kwClusters.getBootstrapServers()).thenReturn("clusters"); when(kwClusters.getProtocol()).thenReturn("PLAINTEXT"); when(kwClusters.getClusterName()).thenReturn("cluster"); - when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(String.class))) + when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(ApiResponse.class))) .thenReturn(response); - ResponseEntity response = + ResponseEntity response1 = clusterApiService.approveTopicRequests( topicName, RequestOperationType.CREATE.value, 1, "1", "", 1); - assertThat(response.getBody()).isEqualTo(ApiResultStatus.SUCCESS.value); + assertThat(Objects.requireNonNull(response1.getBody()).getResult()) + .isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @Order(8) - public void approveTopicRequestsFailure() throws KlawException { + public void approveTopicRequestsFailure() { String topicName = "testtopic"; TopicRequest topicRequest = new TopicRequest(); topicRequest.setTopicname("testtopic"); @@ -213,7 +223,7 @@ public void approveTopicRequestsFailure() throws KlawException { when(kwClusters.getBootstrapServers()).thenReturn("clusters"); when(kwClusters.getProtocol()).thenReturn("PLAINTEXT"); when(kwClusters.getClusterName()).thenReturn("cluster"); - when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(String.class))) + when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), eq(ApiResponse.class))) .thenThrow(new RuntimeException("error")); assertThatThrownBy( diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index dd28b4e6f1..29ed2726d4 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -326,6 +326,7 @@ public void approveTopicRequestsSuccess() throws KlawException { String topicName = "topic1"; int topicId = 1001; TopicRequest topicRequest = getTopicRequest(topicName); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); stubUserInfo(); when(handleDbRequests.selectTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); @@ -333,13 +334,13 @@ public void approveTopicRequestsSuccess() throws KlawException { .thenReturn(ApiResultStatus.SUCCESS.value); when(clusterApiService.approveTopicRequests( anyString(), anyString(), anyInt(), anyString(), anyString(), anyInt())) - .thenReturn(new ResponseEntity<>(ApiResultStatus.SUCCESS.value, HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - ApiResponse apiResponse = topicControllerService.approveTopicRequests(topicId + ""); + ApiResponse apiResponse1 = topicControllerService.approveTopicRequests(topicId + ""); - assertThat(apiResponse.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); + assertThat(apiResponse1.getResult()).isEqualTo(ApiResultStatus.SUCCESS.value); } @Test @@ -348,6 +349,7 @@ public void approveTopicRequestsFailure1() throws KlawException { String topicName = "topic1", env = "1"; int topicId = 1001; TopicRequest topicRequest = getTopicRequest(topicName); + ApiResponse apiResponse = ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); stubUserInfo(); when(handleDbRequests.selectTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); @@ -355,11 +357,11 @@ public void approveTopicRequestsFailure1() throws KlawException { .thenReturn(ApiResultStatus.SUCCESS.value); when(clusterApiService.approveTopicRequests( anyString(), anyString(), anyInt(), anyString(), anyString(), anyInt())) - .thenReturn(new ResponseEntity<>("failure", HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); - ApiResponse apiResponse = topicControllerService.approveTopicRequests("" + topicId); + ApiResponse apiResponse1 = topicControllerService.approveTopicRequests("" + topicId); assertThat(apiResponse.getResult()).isEqualTo("failure"); } From 3139801d56c6ecd6dfae6c19b8f7ccac668a53ef Mon Sep 17 00:00:00 2001 From: muralibasani Date: Thu, 6 Oct 2022 19:15:09 +0200 Subject: [PATCH 13/15] Adding Global ExceptionHandler, refactored if-else blocks --- .../klaw/auth/KwAuthenticationService.java | 7 +- .../auth/KwAuthenticationSuccessHandler.java | 15 +- .../io/aiven/klaw/auth/KwRequestFilter.java | 8 +- .../io/aiven/klaw/config/ManageDatabase.java | 87 ++++--- .../klaw/config/SecurityConfigNoSSO.java | 23 +- .../aiven/klaw/controller/AclController.java | 50 ++-- .../klaw/controller/AclSyncController.java | 23 +- .../EnvsClustersTenantsController.java | 66 ++---- .../controller/KafkaConnectController.java | 61 ++--- .../KafkaConnectSyncController.java | 12 +- .../RolesPermissionsController.java | 35 +-- .../controller/SchemaRegstryController.java | 47 ++-- .../controller/ServerConfigController.java | 12 +- .../klaw/controller/TopicController.java | 78 +++---- .../klaw/controller/TopicSyncController.java | 26 +-- .../klaw/controller/UsersTeamsController.java | 122 ++++------ .../klaw/error/KlawExceptionHandler.java | 25 ++ .../klaw/helpers/db/rdbms/DeleteDataJdbc.java | 8 +- .../klaw/helpers/db/rdbms/InsertDataJdbc.java | 88 ++++--- .../klaw/helpers/db/rdbms/SelectDataJdbc.java | 161 +++++++++---- .../klaw/helpers/db/rdbms/UpdateDataJdbc.java | 23 +- .../klaw/service/AclControllerService.java | 69 ++++-- .../service/AclSyncControllerService.java | 61 +++-- .../service/AnalyticsControllerService.java | 76 +++--- .../aiven/klaw/service/ClusterApiService.java | 47 ++-- .../klaw/service/CommonUtilsService.java | 52 ++--- .../klaw/service/DefaultDataService.java | 32 --- .../io/aiven/klaw/service/EmailService.java | 4 +- .../EnvsClustersTenantsControllerService.java | 81 +++++-- .../KafkaConnectControllerService.java | 48 ++-- .../KafkaConnectSyncControllerService.java | 7 +- .../java/io/aiven/klaw/service/MailUtils.java | 11 +- .../service/MetricsControllerService.java | 4 +- .../RolesPermissionsControllerService.java | 20 +- .../io/aiven/klaw/service/SaasService.java | 13 +- .../SchemaRegstryControllerService.java | 22 +- .../klaw/service/ServerConfigService.java | 65 ++++-- .../klaw/service/TopicControllerService.java | 39 ++-- .../service/TopicSyncControllerService.java | 76 +++--- .../service/UiConfigControllerService.java | 27 +-- .../service/UiControllerLoginService.java | 40 +++- .../service/UsersTeamsControllerService.java | 122 ++++++---- .../klaw/service/UtilControllerService.java | 218 +++++++++++------- .../klaw/service/ValidateCaptchaService.java | 4 +- .../io/aiven/klaw/uglify/UglifyFiles.java | 7 +- 45 files changed, 1173 insertions(+), 949 deletions(-) create mode 100644 src/main/java/io/aiven/klaw/error/KlawExceptionHandler.java diff --git a/src/main/java/io/aiven/klaw/auth/KwAuthenticationService.java b/src/main/java/io/aiven/klaw/auth/KwAuthenticationService.java index 00b633b937..9aeaceebf2 100644 --- a/src/main/java/io/aiven/klaw/auth/KwAuthenticationService.java +++ b/src/main/java/io/aiven/klaw/auth/KwAuthenticationService.java @@ -110,8 +110,11 @@ private DirContextOperations searchForUser(DirContext context, String username) String searchRoot = this.adRootDn != null ? this.adRootDn : this.searchRootFromPrincipal(bindPrincipal); String searchFilterUpdated; - if (adFilter != null && !adFilter.equals("")) searchFilterUpdated = adFilter; - else searchFilterUpdated = searchFilter; + if (adFilter != null && !adFilter.equals("")) { + searchFilterUpdated = adFilter; + } else { + searchFilterUpdated = searchFilter; + } try { return SpringSecurityLdapTemplate.searchForSingleEntryInternal( diff --git a/src/main/java/io/aiven/klaw/auth/KwAuthenticationSuccessHandler.java b/src/main/java/io/aiven/klaw/auth/KwAuthenticationSuccessHandler.java index abaa1e6295..a710c20e3f 100644 --- a/src/main/java/io/aiven/klaw/auth/KwAuthenticationSuccessHandler.java +++ b/src/main/java/io/aiven/klaw/auth/KwAuthenticationSuccessHandler.java @@ -32,14 +32,21 @@ private String validateUrl(String urlFromAddressBar) { if (urlFromAddressBar != null) { urlFromAddressBar = urlFromAddressBar.replace(contextPath + "/", ""); - if (urlFromAddressBar.contains("login")) urlFromAddressBar = "index"; + if (urlFromAddressBar.contains("login")) { + urlFromAddressBar = "index"; + } if (!urlFromAddressBar.contains("loggedin=true")) { - if (urlFromAddressBar.contains("?")) urlFromAddressBar += "&loggedin=true"; - else urlFromAddressBar += "?loggedin=true"; + if (urlFromAddressBar.contains("?")) { + urlFromAddressBar += "&loggedin=true"; + } else { + urlFromAddressBar += "?loggedin=true"; + } } - } else urlFromAddressBar = ""; + } else { + urlFromAddressBar = ""; + } return urlFromAddressBar; } diff --git a/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java b/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java index 2cdbef3758..cc5370f967 100644 --- a/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java +++ b/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java @@ -56,7 +56,9 @@ public Authentication attemptAuthentication( if ("saas".equals(kwInstallationType)) { String gRecaptchaResponse = request.getParameter("g-recaptcha-response"); boolean captchaResponse = validateCaptchaService.validateCaptcha(gRecaptchaResponse); - if (!captchaResponse) throw new AuthenticationServiceException("Invalid Captcha."); + if (!captchaResponse) { + throw new AuthenticationServiceException("Invalid Captcha."); + } } if ("ad".equals(authenticationType)) { @@ -68,7 +70,9 @@ public Authentication attemptAuthentication( // User in KW db return super.attemptAuthentication(request, response); } - } else return super.attemptAuthentication(request, response); + } else { + return super.attemptAuthentication(request, response); + } } @Override diff --git a/src/main/java/io/aiven/klaw/config/ManageDatabase.java b/src/main/java/io/aiven/klaw/config/ManageDatabase.java index 30d399b954..2c986f8a38 100644 --- a/src/main/java/io/aiven/klaw/config/ManageDatabase.java +++ b/src/main/java/io/aiven/klaw/config/ManageDatabase.java @@ -68,12 +68,6 @@ public class ManageDatabase implements ApplicationContextAware { // key tenantId, sub key clusterid Pertenant private static Map> kwKafkaConnectClustersPertenant; - // private static List kafkaEnvList; - - // private static List kafkaConnectEnvList; - // - // private static List schemaEnvList; - private static Map> kafkaEnvListPerTenant = new HashMap<>(); private static Map> schemaRegEnvListPerTenant = new HashMap<>(); private static Map> kafkaConnectEnvListPerTenant = new HashMap<>(); @@ -136,9 +130,10 @@ public void loadDb() throws Exception { private void loadStaticDataToDb() { // add tenant Optional kwTenants = handleDbRequests.getMyTenants(KwConstants.DEFAULT_TENANT_ID); - if (kwTenants.isEmpty()) + if (kwTenants.isEmpty()) { handleDbRequests.addNewTenant( defaultDataService.getDefaultTenant(KwConstants.DEFAULT_TENANT_ID)); + } // add teams String infraTeam = "INFRATEAM", stagingTeam = "STAGINGTEAM"; @@ -192,22 +187,16 @@ private void loadStaticDataToDb() { String productName = "Klaw"; Optional productDetails = handleDbRequests.selectProductDetails(productName); if (productDetails.isPresent()) { - if (!Objects.equals(productDetails.get().getVersion(), kwVersion)) + if (!Objects.equals(productDetails.get().getVersion(), kwVersion)) { handleDbRequests.insertProductDetails( defaultDataService.getProductDetails(productName, kwVersion)); - } else + } + } else { handleDbRequests.insertProductDetails( defaultDataService.getProductDetails(productName, kwVersion)); + } } - // @Autowired - // private CreateBulkTests createBulkTests; - // private void runPerfTests() { - // createBulkTests.createTopicRequests(); - //// createBulkTests.approveTopicRequests(); - //// createBulkTests.getTopics(); - // } - private void checkSSOAuthentication() { if ("db".equals(authenticationType) && "true".equals(ssoEnabled)) { log.error( @@ -252,22 +241,30 @@ public Integer getAllClustersSize() { } public List getKafkaEnvList(int tenantId) { - if (kafkaEnvListPerTenant.get(tenantId).isEmpty()) return new ArrayList<>(); + if (kafkaEnvListPerTenant.get(tenantId).isEmpty()) { + return new ArrayList<>(); + } return kafkaEnvListPerTenant.get(tenantId); } public List getSchemaRegEnvList(int tenantId) { - if (schemaRegEnvListPerTenant.get(tenantId).isEmpty()) return new ArrayList<>(); + if (schemaRegEnvListPerTenant.get(tenantId).isEmpty()) { + return new ArrayList<>(); + } return schemaRegEnvListPerTenant.get(tenantId); } public List getKafkaConnectEnvList(int tenantId) { - if (kafkaConnectEnvListPerTenant.get(tenantId).isEmpty()) return new ArrayList<>(); + if (kafkaConnectEnvListPerTenant.get(tenantId).isEmpty()) { + return new ArrayList<>(); + } return kafkaConnectEnvListPerTenant.get(tenantId); } public List getAllEnvList(int tenantId) { - if (allEnvListPerTenant.get(tenantId).isEmpty()) return new ArrayList<>(); + if (allEnvListPerTenant.get(tenantId).isEmpty()) { + return new ArrayList<>(); + } return allEnvListPerTenant.get(tenantId); } @@ -302,12 +299,14 @@ public Set getTeamsForTenant(int tenantId) { public Integer getTeamIdFromTeamName(int tenantId, String teamName) { Optional> optionalTeam; - if (teamName != null) + if (teamName != null) { optionalTeam = teamIdAndNamePerTenant.get(tenantId).entrySet().stream() .filter(a -> Objects.equals(a.getValue(), teamName)) .findFirst(); - else return null; + } else { + return null; + } // unknown team return optionalTeam.map(Map.Entry::getKey).orElse(null); @@ -345,14 +344,15 @@ public Map> getKwPropertiesMap(int tenantId) { } public String getKwPropertyValue(String kwKey, int tenantId) { - if (kwPropertiesMapPerTenant.get(tenantId) != null) + if (kwPropertiesMapPerTenant.get(tenantId) != null) { return kwPropertiesMapPerTenant.get(tenantId).get(kwKey).get("kwvalue"); - else return ""; + } else { + return ""; + } } private void loadEnvsForAllTenants() { envsOfTenantsMap = new HashMap<>(); // key is tenantid, value is list of envs - for (Integer tenantId : tenantMap.keySet()) { loadEnvsForOneTenant(tenantId); } @@ -394,7 +394,9 @@ private void loadTenantTeamsForAllTenants() { } public void loadTenantTeamsForOneTenant(List allTeams, Integer tenantId) { - if (allTeams == null) allTeams = handleDbRequests.selectAllTeams(tenantId); + if (allTeams == null) { + allTeams = handleDbRequests.selectAllTeams(tenantId); + } Map> teamsAndAllowedEnvs = new HashMap<>(); Map teamsAndNames = new HashMap<>(); @@ -420,8 +422,9 @@ public Map getTenantConfig() { public void setTenantConfig(TenantConfig config) { KwTenantConfigModel tenantModel = config.getTenantModel(); - if (tenantModel != null) + if (tenantModel != null) { tenantConfig.put(getTenantIdFromName(tenantModel.getTenantName()), tenantModel); + } } private void loadKwPropertiesforAllTenants() { @@ -439,10 +442,11 @@ private void loadKwPropertiesforAllTenants() { public void loadKwPropsPerOneTenant( Map>> kwPropertiesMap, Integer tenantId) { - if (kwPropertiesMap == null) kwPropertiesMap = handleDbRequests.selectAllKwProperties(); + if (kwPropertiesMap == null) { + kwPropertiesMap = handleDbRequests.selectAllKwProperties(); + } kwPropertiesMapPerTenant.put(tenantId, kwPropertiesMap.get(tenantId)); - updateKwTenantConfigPerTenant(tenantId); } @@ -497,14 +501,17 @@ public void loadClustersForOneTenant( List schemaRegistryClusters, List kafkaConnectClusters, Integer tenantId) { - if (kafkaClusters == null) + if (kafkaClusters == null) { kafkaClusters = handleDbRequests.getAllClusters(KafkaClustersType.KAFKA.value, tenantId); - if (schemaRegistryClusters == null) + } + if (schemaRegistryClusters == null) { schemaRegistryClusters = handleDbRequests.getAllClusters(KafkaClustersType.SCHEMA_REGISTRY.value, tenantId); - if (kafkaConnectClusters == null) + } + if (kafkaConnectClusters == null) { kafkaConnectClusters = handleDbRequests.getAllClusters(KafkaClustersType.KAFKA_CONNECT.value, tenantId); + } Map kwKafkaClusters = new HashMap<>(); Map kwSchemaRegClusters = new HashMap<>(); @@ -531,7 +538,6 @@ public void loadClustersForOneTenant( kwAllClusters.put(cluster.getClusterId(), cluster); }); kwKafkaConnectClustersPertenant.put(tenantId, kwKafkaConnectClusters); - kwAllClustersPertenant.put(tenantId, kwAllClusters); } @@ -622,9 +628,11 @@ public void loadEnvMapForOneTenant(Integer tenantId) { List partitions = new ArrayList<>(); for (int i = 1; i < maxPartitionsInt + 1; i++) { - if (defaultPartitions != null && defaultPartitions.equals(i + "")) + if (defaultPartitions != null && defaultPartitions.equals(i + "")) { partitions.add(i + " (default)"); - else partitions.add(i + ""); + } else { + partitions.add(i + ""); + } } oneEnvParamsMap.put("partitionsList", partitions); } else if (param.startsWith("default.replication.factor")) { @@ -638,8 +646,11 @@ public void loadEnvMapForOneTenant(Integer tenantId) { List rf = new ArrayList<>(); for (int i = 1; i < maxRfInt + 1; i++) { - if (defaultRf != null && defaultRf.equals(i + "")) rf.add(i + " (default)"); - else rf.add(i + ""); + if (defaultRf != null && defaultRf.equals(i + "")) { + rf.add(i + " (default)"); + } else { + rf.add(i + ""); + } } oneEnvParamsMap.put("replicationFactorList", rf); diff --git a/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java b/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java index 565c8623bd..b9a2a0f5d3 100644 --- a/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java +++ b/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java @@ -138,10 +138,11 @@ protected void configure(HttpSecurity http) throws Exception { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - if (authenticationType != null && authenticationType.equals("db")) dbAuthentication(auth); - else if (authenticationType != null && authenticationType.equals("ldap")) + if (authenticationType != null && authenticationType.equals("db")) { + dbAuthentication(auth); + } else if (authenticationType != null && authenticationType.equals("ldap")) { ldapAuthentication(auth); - else if (authenticationType != null && authenticationType.equals("ad")) { + } else if (authenticationType != null && authenticationType.equals("ad")) { auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()) .userDetailsService(userDetailsService()); } else { @@ -177,14 +178,18 @@ public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() { provider.setConvertSubErrorCodesToExceptions(true); provider.setUseAuthenticationRequestCredentials(true); - if (adFilter != null && !adFilter.equals("")) provider.setSearchFilter(adFilter); + if (adFilter != null && !adFilter.equals("")) { + provider.setSearchFilter(adFilter); + } return provider; } private void ldapAuthentication(AuthenticationManagerBuilder auth) throws Exception { try { log.info("Ldap authentication configured."); - if (!checkLdapConnectivity()) throw new KlawException("Cannot connect to Ldap !!"); + if (!checkLdapConnectivity()) { + throw new KlawException("Cannot connect to Ldap !!"); + } if (encryptionType != null && encryptionType.equals("bcrypt")) { auth.ldapAuthentication() @@ -217,7 +222,6 @@ public InMemoryUserDetailsManager inMemoryUserDetailsManager() throws Exception final Properties globalUsers = new Properties(); if (authenticationType != null && authenticationType.equals("db")) { log.info("Loading all users !!"); - List users; try { @@ -240,8 +244,11 @@ public InMemoryUserDetailsManager inMemoryUserDetailsManager() throws Exception userInfo = iter.next(); try { String secPwd = userInfo.getPwd(); - if (secPwd != null && secPwd.equals("")) secPwd = "gfGF%64GFDd766hfgfHFD$%#453"; - else secPwd = decodePwd(secPwd); + if (secPwd != null && secPwd.equals("")) { + secPwd = "gfGF%64GFDd766hfgfHFD$%#453"; + } else { + secPwd = decodePwd(secPwd); + } globalUsers.put( userInfo.getUsername(), encoder.encode(secPwd) + "," + userInfo.getRole() + ",enabled"); diff --git a/src/main/java/io/aiven/klaw/controller/AclController.java b/src/main/java/io/aiven/klaw/controller/AclController.java index 8e1e6603dd..d73bb20bf3 100644 --- a/src/main/java/io/aiven/klaw/controller/AclController.java +++ b/src/main/java/io/aiven/klaw/controller/AclController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.*; import io.aiven.klaw.service.AclControllerService; @@ -28,12 +26,9 @@ public class AclController { @Autowired AclControllerService aclControllerService; @PostMapping(value = "/createAcl") - public ResponseEntity createAcl(@Valid @RequestBody AclRequestsModel addAclRequest) { - try { - return new ResponseEntity<>(aclControllerService.createAcl(addAclRequest), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity createAcl(@Valid @RequestBody AclRequestsModel addAclRequest) + throws KlawException { + return new ResponseEntity<>(aclControllerService.createAcl(addAclRequest), HttpStatus.OK); } @RequestMapping( @@ -68,44 +63,31 @@ public ResponseEntity> getCreatedAclRequests( value = "/deleteAclRequests", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteAclRequests(@RequestParam("req_no") String req_no) { - try { - return new ResponseEntity<>(aclControllerService.deleteAclRequests(req_no), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteAclRequests(@RequestParam("req_no") String req_no) + throws KlawException { + return new ResponseEntity<>(aclControllerService.deleteAclRequests(req_no), HttpStatus.OK); } @PostMapping(value = "/execAclRequest") - public ResponseEntity approveAclRequests(@RequestParam("req_no") String req_no) { - try { - return new ResponseEntity<>(aclControllerService.approveAclRequests(req_no), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity approveAclRequests(@RequestParam("req_no") String req_no) + throws KlawException { + return new ResponseEntity<>(aclControllerService.approveAclRequests(req_no), HttpStatus.OK); } @PostMapping(value = "/createDeleteAclSubscriptionRequest") public ResponseEntity deleteAclSubscriptionRequest( - @RequestParam("req_no") String req_no) { - try { - return new ResponseEntity<>( - aclControllerService.createDeleteAclSubscriptionRequest(req_no), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("req_no") String req_no) throws KlawException { + return new ResponseEntity<>( + aclControllerService.createDeleteAclSubscriptionRequest(req_no), HttpStatus.OK); } @PostMapping(value = "/execAclRequestDecline") public ResponseEntity declineAclRequests( @RequestParam("req_no") String req_no, - @RequestParam("reasonForDecline") String reasonForDecline) { - try { - return new ResponseEntity<>( - aclControllerService.declineAclRequests(req_no, reasonForDecline), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("reasonForDecline") String reasonForDecline) + throws KlawException { + return new ResponseEntity<>( + aclControllerService.declineAclRequests(req_no, reasonForDecline), HttpStatus.OK); } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/controller/AclSyncController.java b/src/main/java/io/aiven/klaw/controller/AclSyncController.java index 36195d4120..a1b6cb6041 100644 --- a/src/main/java/io/aiven/klaw/controller/AclSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/AclSyncController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.ApiResponse; @@ -30,13 +28,9 @@ public class AclSyncController { @PostMapping(value = "/updateSyncAcls") public ResponseEntity updateSyncAcls( - @RequestBody List syncAclUpdates) { - try { - return new ResponseEntity<>( - aclSyncControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody List syncAclUpdates) throws KlawException { + return new ResponseEntity<>( + aclSyncControllerService.updateSyncAcls(syncAclUpdates), HttpStatus.OK); } @RequestMapping( @@ -56,13 +50,10 @@ public ResponseEntity> getSyncBackAcls( } @PostMapping(value = "/updateSyncBackAcls") - public ResponseEntity updateSyncBackAcls(@RequestBody SyncBackAcls syncBackAcls) { - try { - return new ResponseEntity<>( - aclSyncControllerService.updateSyncBackAcls(syncBackAcls), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity updateSyncBackAcls(@RequestBody SyncBackAcls syncBackAcls) + throws KlawException { + return new ResponseEntity<>( + aclSyncControllerService.updateSyncBackAcls(syncBackAcls), HttpStatus.OK); } // get acls from kafka cluster diff --git a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java index ab6f2045db..3d85668e9a 100644 --- a/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java +++ b/src/main/java/io/aiven/klaw/controller/EnvsClustersTenantsController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.EnvModel; @@ -79,13 +77,10 @@ public ResponseEntity> getEnvsBaseClusterFilteredForTeam() { } @PostMapping(value = "/deleteCluster") - public ResponseEntity deleteCluster(@RequestParam("clusterId") String clusterId) { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.deleteCluster(clusterId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteCluster(@RequestParam("clusterId") String clusterId) + throws KlawException { + return new ResponseEntity<>( + envsClustersTenantsControllerService.deleteCluster(clusterId), HttpStatus.OK); } @PostMapping(value = "/addNewCluster") @@ -182,24 +177,18 @@ public ResponseEntity> getSchemaRegEnvsStatus() { } @PostMapping(value = "/addNewEnv") - public ResponseEntity addNewEnv(@Valid @RequestBody EnvModel newEnv) { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.addNewEnv(newEnv), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity addNewEnv(@Valid @RequestBody EnvModel newEnv) + throws KlawException { + return new ResponseEntity<>( + envsClustersTenantsControllerService.addNewEnv(newEnv), HttpStatus.OK); } @PostMapping(value = "/deleteEnvironmentRequest") public ResponseEntity deleteEnvironment( - @RequestParam("envId") String envId, @RequestParam("envType") String envType) { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.deleteEnvironment(envId, envType), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("envId") String envId, @RequestParam("envType") String envType) + throws KlawException { + return new ResponseEntity<>( + envsClustersTenantsControllerService.deleteEnvironment(envId, envType), HttpStatus.OK); } @RequestMapping( @@ -221,36 +210,25 @@ public ResponseEntity> getExtensionPeriods() { } @PostMapping(value = "/addTenantId") - public ResponseEntity addTenantId(@Valid @RequestBody KwTenantModel kwTenantModel) { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.addTenantId(kwTenantModel, true), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity addTenantId(@Valid @RequestBody KwTenantModel kwTenantModel) + throws KlawException { + return new ResponseEntity<>( + envsClustersTenantsControllerService.addTenantId(kwTenantModel, true), HttpStatus.OK); } @PostMapping(value = "/deleteTenant") - public ResponseEntity deleteTenant() { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.deleteTenant(), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteTenant() throws KlawException { + return new ResponseEntity<>(envsClustersTenantsControllerService.deleteTenant(), HttpStatus.OK); } // Pattern a-zA-z and/or spaces. @PostMapping(value = "/udpateTenant") public ResponseEntity udpateTenant( @RequestParam("orgName") @Pattern(message = "Invalid Organization.", regexp = "^[a-zA-z ]*$") - String orgName) { - try { - return new ResponseEntity<>( - envsClustersTenantsControllerService.updateTenant(orgName), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + String orgName) + throws KlawException { + return new ResponseEntity<>( + envsClustersTenantsControllerService.updateTenant(orgName), HttpStatus.OK); } @PostMapping(value = "/udpateTenantExtension") diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java index 47c96376b2..5c727f6d3b 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ConnectorOverview; @@ -59,26 +57,18 @@ public ResponseEntity> getCreatedConnectorReque method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity deleteConnectorRequests( - @RequestParam("connectorId") String connectorId) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.deleteConnectorRequests(connectorId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("connectorId") String connectorId) throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.deleteConnectorRequests(connectorId), HttpStatus.OK); } @PostMapping( value = "/execConnectorRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity approveTopicRequests( - @RequestParam("connectorId") String connectorId) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.approveConnectorRequests(connectorId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("connectorId") String connectorId) throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.approveConnectorRequests(connectorId), HttpStatus.OK); } @PostMapping( @@ -86,28 +76,22 @@ public ResponseEntity approveTopicRequests( produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity declineConnectorRequests( @RequestParam("connectorId") String connectorId, - @RequestParam("reasonForDecline") String reasonForDecline) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.declineConnectorRequests(connectorId, reasonForDecline), - HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("reasonForDecline") String reasonForDecline) + throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.declineConnectorRequests(connectorId, reasonForDecline), + HttpStatus.OK); } @PostMapping( value = "/createConnectorDeleteRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity createConnectorDeleteRequest( - @RequestParam("connectorName") String topicName, @RequestParam("env") String envId) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.createConnectorDeleteRequest(topicName, envId), - HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("connectorName") String topicName, @RequestParam("env") String envId) + throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.createConnectorDeleteRequest(topicName, envId), + HttpStatus.OK); } @RequestMapping( @@ -154,14 +138,11 @@ public ResponseEntity getConnectorOverview( value = "/createClaimConnectorRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity createClaimConnectorRequest( - @RequestParam("connectorName") String connectorName, @RequestParam("env") String envId) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.createClaimConnectorRequest(connectorName, envId), - HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("connectorName") String connectorName, @RequestParam("env") String envId) + throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.createClaimConnectorRequest(connectorName, envId), + HttpStatus.OK); } @PostMapping(value = "/saveConnectorDocumentation") diff --git a/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java b/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java index 0e45f04268..cca2f672d6 100644 --- a/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/KafkaConnectSyncController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KafkaConnectorModel; @@ -28,13 +26,9 @@ public class KafkaConnectSyncController { @PostMapping(value = "/updateSyncConnectors") public ResponseEntity updateSyncConnectors( - @RequestBody List syncConnectorUpdates) { - try { - return new ResponseEntity<>( - kafkaConnectControllerService.updateSyncConnectors(syncConnectorUpdates), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody List syncConnectorUpdates) throws KlawException { + return new ResponseEntity<>( + kafkaConnectControllerService.updateSyncConnectors(syncConnectorUpdates), HttpStatus.OK); } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java b/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java index e140cc377f..985087dd5e 100644 --- a/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java +++ b/src/main/java/io/aiven/klaw/controller/RolesPermissionsController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KwRolesPermissionsModel; @@ -60,34 +58,23 @@ public ResponseEntity>>> getPermissions() } @PostMapping(value = "/deleteRole") - public ResponseEntity deleteRole(@RequestParam("roleId") String roleId) { - try { - return new ResponseEntity<>( - rolesPermissionsControllerService.deleteRole(roleId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteRole(@RequestParam("roleId") String roleId) + throws KlawException { + return new ResponseEntity<>( + rolesPermissionsControllerService.deleteRole(roleId), HttpStatus.OK); } @PostMapping(value = "/addRoleId") - public ResponseEntity addRoleId(@RequestParam("roleId") String roleId) { - try { - return new ResponseEntity<>( - rolesPermissionsControllerService.addRoleId(roleId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity addRoleId(@RequestParam("roleId") String roleId) + throws KlawException { + return new ResponseEntity<>(rolesPermissionsControllerService.addRoleId(roleId), HttpStatus.OK); } @PostMapping(value = "/updatePermissions") public ResponseEntity updatePermissions( - @RequestBody KwRolesPermissionsModel[] kwRolesPermissionsModels) { - try { - return new ResponseEntity<>( - rolesPermissionsControllerService.updatePermissions(kwRolesPermissionsModels), - HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody KwRolesPermissionsModel[] kwRolesPermissionsModels) throws KlawException { + return new ResponseEntity<>( + rolesPermissionsControllerService.updatePermissions(kwRolesPermissionsModels), + HttpStatus.OK); } } diff --git a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java index a05e015d59..87ba4ced66 100644 --- a/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java +++ b/src/main/java/io/aiven/klaw/controller/SchemaRegstryController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SchemaRequestModel; @@ -52,26 +50,18 @@ public ResponseEntity> getCreatedSchemaRequests( value = "/deleteSchemaRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity deleteSchemaRequests( - @RequestParam("req_no") String avroSchemaReqId) { - try { - return new ResponseEntity<>( - schemaRegstryControllerService.deleteSchemaRequests(avroSchemaReqId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("req_no") String avroSchemaReqId) throws KlawException { + return new ResponseEntity<>( + schemaRegstryControllerService.deleteSchemaRequests(avroSchemaReqId), HttpStatus.OK); } @PostMapping( value = "/execSchemaRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity execSchemaRequests( - @RequestParam("avroSchemaReqId") String avroSchemaReqId) { - try { - return new ResponseEntity<>( - schemaRegstryControllerService.execSchemaRequests(avroSchemaReqId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("avroSchemaReqId") String avroSchemaReqId) throws KlawException { + return new ResponseEntity<>( + schemaRegstryControllerService.execSchemaRequests(avroSchemaReqId), HttpStatus.OK); } @PostMapping( @@ -79,26 +69,17 @@ public ResponseEntity execSchemaRequests( produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity execSchemaRequestsDecline( @RequestParam("avroSchemaReqId") String avroSchemaReqId, - @RequestParam("reasonForDecline") String reasonForDecline) { - - try { - return new ResponseEntity<>( - schemaRegstryControllerService.execSchemaRequestsDecline( - avroSchemaReqId, reasonForDecline), - HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("reasonForDecline") String reasonForDecline) + throws KlawException { + return new ResponseEntity<>( + schemaRegstryControllerService.execSchemaRequestsDecline(avroSchemaReqId, reasonForDecline), + HttpStatus.OK); } @PostMapping(value = "/uploadSchema") public ResponseEntity uploadSchema( - @Valid @RequestBody SchemaRequestModel addSchemaRequest) { - try { - return new ResponseEntity<>( - schemaRegstryControllerService.uploadSchema(addSchemaRequest), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @Valid @RequestBody SchemaRequestModel addSchemaRequest) throws KlawException { + return new ResponseEntity<>( + schemaRegstryControllerService.uploadSchema(addSchemaRequest), HttpStatus.OK); } } diff --git a/src/main/java/io/aiven/klaw/controller/ServerConfigController.java b/src/main/java/io/aiven/klaw/controller/ServerConfigController.java index 56918b458e..5276abff78 100644 --- a/src/main/java/io/aiven/klaw/controller/ServerConfigController.java +++ b/src/main/java/io/aiven/klaw/controller/ServerConfigController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.KwPropertiesModel; @@ -52,13 +50,9 @@ public ResponseEntity> resetCache() { @PostMapping(value = "/updateKwCustomProperty") public ResponseEntity updateKwCustomProperty( - @RequestBody KwPropertiesModel kwPropertiesModel) { - try { - return new ResponseEntity<>( - serverConfigService.updateKwCustomProperty(kwPropertiesModel), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody KwPropertiesModel kwPropertiesModel) throws KlawException { + return new ResponseEntity<>( + serverConfigService.updateKwCustomProperty(kwPropertiesModel), HttpStatus.OK); } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/controller/TopicController.java b/src/main/java/io/aiven/klaw/controller/TopicController.java index 30edf6a4b0..a0d7033693 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.TopicInfo; @@ -31,39 +29,29 @@ public class TopicController { @PostMapping(value = "/createTopics") public ResponseEntity createTopicsRequest( - @Valid @RequestBody TopicRequestModel addTopicRequest) { - try { - return new ResponseEntity<>( - topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @Valid @RequestBody TopicRequestModel addTopicRequest) throws KlawException { + return new ResponseEntity<>( + topicControllerService.createTopicsRequest(addTopicRequest), HttpStatus.OK); } @PostMapping( value = "/createTopicDeleteRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity createTopicDeleteRequest( - @RequestParam("topicName") String topicName, @RequestParam("env") String envId) { - try { - return new ResponseEntity<>( - topicControllerService.createTopicDeleteRequest(topicName, envId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("topicName") String topicName, @RequestParam("env") String envId) + throws KlawException { + return new ResponseEntity<>( + topicControllerService.createTopicDeleteRequest(topicName, envId), HttpStatus.OK); } @PostMapping( value = "/createClaimTopicRequest", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity createClaimTopicRequest( - @RequestParam("topicName") String topicName, @RequestParam("env") String envId) { - try { - return new ResponseEntity<>( - topicControllerService.createClaimTopicRequest(topicName, envId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("topicName") String topicName, @RequestParam("env") String envId) + throws KlawException { + return new ResponseEntity<>( + topicControllerService.createClaimTopicRequest(topicName, envId), HttpStatus.OK); } @RequestMapping( @@ -101,7 +89,6 @@ public ResponseEntity> getCreatedTopicRequests( @RequestParam("pageNo") String pageNo, @RequestParam(value = "currentPage", defaultValue = "") String currentPage, @RequestParam(value = "requestsType", defaultValue = "created") String requestsType) { - return new ResponseEntity<>( topicControllerService.getCreatedTopicRequests(pageNo, currentPage, requestsType), HttpStatus.OK); @@ -111,25 +98,18 @@ public ResponseEntity> getCreatedTopicRequests( value = "/deleteTopicRequests", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity deleteTopicRequests(@RequestParam("topicId") String topicId) { - try { - return new ResponseEntity<>( - topicControllerService.deleteTopicRequests(topicId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteTopicRequests(@RequestParam("topicId") String topicId) + throws KlawException { + return new ResponseEntity<>(topicControllerService.deleteTopicRequests(topicId), HttpStatus.OK); } @PostMapping( value = "/execTopicRequests", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity approveTopicRequests(@RequestParam("topicId") String topicId) { - try { - return new ResponseEntity<>( - topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity approveTopicRequests(@RequestParam("topicId") String topicId) + throws KlawException { + return new ResponseEntity<>( + topicControllerService.approveTopicRequests(topicId), HttpStatus.OK); } @PostMapping( @@ -137,13 +117,10 @@ public ResponseEntity approveTopicRequests(@RequestParam("topicId") produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity declineTopicRequests( @RequestParam("topicId") String topicId, - @RequestParam("reasonForDecline") String reasonForDecline) { - try { - return new ResponseEntity<>( - topicControllerService.declineTopicRequests(topicId, reasonForDecline), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("reasonForDecline") String reasonForDecline) + throws KlawException { + return new ResponseEntity<>( + topicControllerService.declineTopicRequests(topicId, reasonForDecline), HttpStatus.OK); } @RequestMapping( @@ -185,13 +162,10 @@ public ResponseEntity> getTopicDetailsPerEnv( } @PostMapping(value = "/saveTopicDocumentation") - public ResponseEntity saveTopicDocumentation(@RequestBody TopicInfo topicInfo) { - try { - return new ResponseEntity<>( - topicControllerService.saveTopicDocumentation(topicInfo), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity saveTopicDocumentation(@RequestBody TopicInfo topicInfo) + throws KlawException { + return new ResponseEntity<>( + topicControllerService.saveTopicDocumentation(topicInfo), HttpStatus.OK); } // getTopic Events from kafka cluster diff --git a/src/main/java/io/aiven/klaw/controller/TopicSyncController.java b/src/main/java/io/aiven/klaw/controller/TopicSyncController.java index 10e5411a74..eebbc81fdc 100644 --- a/src/main/java/io/aiven/klaw/controller/TopicSyncController.java +++ b/src/main/java/io/aiven/klaw/controller/TopicSyncController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.SyncBackTopics; @@ -30,24 +28,16 @@ public class TopicSyncController { @PostMapping(value = "/updateSyncTopics") public ResponseEntity updateSyncTopics( - @RequestBody List syncTopicUpdates) { - try { - return new ResponseEntity<>( - topicSyncControllerService.updateSyncTopics(syncTopicUpdates), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody List syncTopicUpdates) throws KlawException { + return new ResponseEntity<>( + topicSyncControllerService.updateSyncTopics(syncTopicUpdates), HttpStatus.OK); } @PostMapping(value = "/updateSyncTopicsBulk") public ResponseEntity updateSyncTopicsBulk( - @RequestBody SyncTopicsBulk syncTopicsBulk) { - try { - return new ResponseEntity<>( - topicSyncControllerService.updateSyncTopicsBulk(syncTopicsBulk), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestBody SyncTopicsBulk syncTopicsBulk) throws KlawException { + return new ResponseEntity<>( + topicSyncControllerService.updateSyncTopicsBulk(syncTopicsBulk), HttpStatus.OK); } // sync back topics @@ -61,9 +51,7 @@ public ResponseEntity> getTopicsRowView( @RequestParam(value = "currentPage", defaultValue = "") String currentPage, @RequestParam(value = "topicnamesearch", required = false) String topicNameSearch, @RequestParam(value = "teamName", required = false) String teamName, - @RequestParam(value = "topicType", required = false) String topicType) - throws Exception { - + @RequestParam(value = "topicType", required = false) String topicType) { return new ResponseEntity<>( topicSyncControllerService.getTopicsRowView( envId, pageNo, currentPage, topicNameSearch, teamName, topicType), diff --git a/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java b/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java index 88f5c3167c..f0acca62cb 100644 --- a/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java +++ b/src/main/java/io/aiven/klaw/controller/UsersTeamsController.java @@ -1,7 +1,5 @@ package io.aiven.klaw.controller; -import static io.aiven.klaw.service.UtilControllerService.handleException; - import io.aiven.klaw.error.KlawException; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.RegisterSaasUserInfoModel; @@ -53,74 +51,50 @@ public ResponseEntity> getAllTeamsSUOnly() { } @PostMapping(value = "/deleteTeamRequest") - public ResponseEntity deleteTeam(@RequestParam("teamId") Integer teamId) { - try { - return new ResponseEntity<>(usersTeamsControllerService.deleteTeam(teamId), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteTeam(@RequestParam("teamId") Integer teamId) + throws KlawException { + return new ResponseEntity<>(usersTeamsControllerService.deleteTeam(teamId), HttpStatus.OK); } @PostMapping(value = "/deleteUserRequest") - public ResponseEntity deleteUser(@RequestParam("userId") String userId) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.deleteUser(userId, true), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity deleteUser(@RequestParam("userId") String userId) + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.deleteUser(userId, true), HttpStatus.OK); } @PostMapping(value = "/updateUser") - public ResponseEntity updateUser(@Valid @RequestBody UserInfoModel updateUserObj) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.updateUser(updateUserObj), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity updateUser(@Valid @RequestBody UserInfoModel updateUserObj) + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.updateUser(updateUserObj), HttpStatus.OK); } @PostMapping(value = "/updateProfile") - public ResponseEntity updateProfile( - @Valid @RequestBody UserInfoModel updateUserObj) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.updateProfile(updateUserObj), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity updateProfile(@Valid @RequestBody UserInfoModel updateUserObj) + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.updateProfile(updateUserObj), HttpStatus.OK); } @PostMapping(value = "/addNewUser") - public ResponseEntity addNewUser(@Valid @RequestBody UserInfoModel newUser) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.addNewUser(newUser, true), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity addNewUser(@Valid @RequestBody UserInfoModel newUser) + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.addNewUser(newUser, true), HttpStatus.OK); } @PostMapping(value = "/registerUser") public ResponseEntity registerUser(@Valid @RequestBody RegisterUserInfoModel newUser) - throws Exception { - try { - return new ResponseEntity<>( - usersTeamsControllerService.registerUser(newUser, true), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.registerUser(newUser, true), HttpStatus.OK); } @PostMapping(value = "/registerUserSaas") public ResponseEntity registerUserSaas( @Valid @RequestBody RegisterSaasUserInfoModel newUser) throws Exception { - try { - return new ResponseEntity<>(saasService.registerUserSaas(newUser), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + return new ResponseEntity<>(saasService.registerUserSaas(newUser), HttpStatus.OK); } @RequestMapping( @@ -153,44 +127,29 @@ public ResponseEntity getRegistrationInfoFromId( @PostMapping(value = "/execNewUserRequestApprove") public ResponseEntity approveNewUserRequests( - @RequestParam("username") String username) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.approveNewUserRequests(username, true, 0, ""), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("username") String username) throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.approveNewUserRequests(username, true, 0, ""), HttpStatus.OK); } @PostMapping(value = "/execNewUserRequestDecline") public ResponseEntity declineNewUserRequests( - @RequestParam("username") String username) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.declineNewUserRequests(username), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + @RequestParam("username") String username) throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.declineNewUserRequests(username), HttpStatus.OK); } @PostMapping(value = "/addNewTeam") - public ResponseEntity addNewTeam(@Valid @RequestBody TeamModel newTeam) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.addNewTeam(newTeam, true), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity addNewTeam(@Valid @RequestBody TeamModel newTeam) + throws KlawException { + return new ResponseEntity<>( + usersTeamsControllerService.addNewTeam(newTeam, true), HttpStatus.OK); } @PostMapping(value = "/updateTeam") - public ResponseEntity updateTeam(@Valid @RequestBody TeamModel updateTeam) { - try { - return new ResponseEntity<>( - usersTeamsControllerService.updateTeam(updateTeam), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity updateTeam(@Valid @RequestBody TeamModel updateTeam) + throws KlawException { + return new ResponseEntity<>(usersTeamsControllerService.updateTeam(updateTeam), HttpStatus.OK); } @RequestMapping( @@ -205,12 +164,9 @@ public ResponseEntity getTeamDetails( } @PostMapping(value = "/chPwd") - public ResponseEntity changePwd(@RequestParam("changePwd") String changePwd) { - try { - return new ResponseEntity<>(usersTeamsControllerService.changePwd(changePwd), HttpStatus.OK); - } catch (KlawException e) { - return handleException(e); - } + public ResponseEntity changePwd(@RequestParam("changePwd") String changePwd) + throws KlawException { + return new ResponseEntity<>(usersTeamsControllerService.changePwd(changePwd), HttpStatus.OK); } @RequestMapping( diff --git a/src/main/java/io/aiven/klaw/error/KlawExceptionHandler.java b/src/main/java/io/aiven/klaw/error/KlawExceptionHandler.java new file mode 100644 index 0000000000..9d3a28cfec --- /dev/null +++ b/src/main/java/io/aiven/klaw/error/KlawExceptionHandler.java @@ -0,0 +1,25 @@ +package io.aiven.klaw.error; + +import io.aiven.klaw.model.ApiResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice +@Slf4j +public class KlawExceptionHandler extends ResponseEntityExceptionHandler { + public static final String ERROR_MSG = + "Unable to process the request. Please contact our Administrator !!"; + + @ExceptionHandler(KlawException.class) + protected ResponseEntity handleExceptionInternal( + KlawException ex, WebRequest request) { + ex.printStackTrace(); + return new ResponseEntity<>( + ApiResponse.builder().message(ERROR_MSG).build(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java index 1c6da5d8a0..066f99f466 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/DeleteDataJdbc.java @@ -168,7 +168,9 @@ public String deleteEnvironment(String envId, int tenantId) { // env.get().setEnvExists("false"); envRepo.delete(env.get()); return ApiResultStatus.SUCCESS.value; - } else return ApiResultStatus.FAILURE.value; + } else { + return ApiResultStatus.FAILURE.value; + } } public String deleteCluster(int clusterId, int tenantId) { @@ -186,7 +188,9 @@ public String deleteCluster(int clusterId, int tenantId) { kwClusterRepo.delete(clusters); envRepo.deleteAll(allAssociatedEnvs); return ApiResultStatus.SUCCESS.value; - } else return ApiResultStatus.FAILURE.value; + } else { + return ApiResultStatus.FAILURE.value; + } } public String deleteUserRequest(String userId) { diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java index bcaf081cea..13e0cd198e 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/InsertDataJdbc.java @@ -247,7 +247,9 @@ public synchronized String insertIntoAclsSOT(List acls, boolean isSyncAcls) acls.forEach( acl -> { log.debug("insertIntoAclsSOT {}", acl.getTopicname()); - if (acl.getReq_no() == null) acl.setReq_no(getNextAclId(acl.getTenantId())); + if (acl.getReq_no() == null) { + acl.setReq_no(getNextAclId(acl.getTenantId())); + } aclRepo.save(acl); }); return ApiResultStatus.SUCCESS.value; @@ -288,8 +290,9 @@ public synchronized String insertIntoMessageSchemaSOT(List schema for (MessageSchema mSchema : schemas) { log.debug("insertIntoMessageSchemaSOT {}", mSchema.getTopicname()); - if (mSchema.getReq_no() == null) + if (mSchema.getReq_no() == null) { mSchema.setReq_no(getNextSchemaRequestId("SCHEMA_ID", mSchema.getTenantId())); + } messageSchemaRepo.save(mSchema); } return ApiResultStatus.SUCCESS.value; @@ -298,7 +301,9 @@ public synchronized String insertIntoMessageSchemaSOT(List schema public String insertIntoUsers(UserInfo userInfo) { log.debug("insertIntoUsers {}", userInfo.getUsername()); Optional userExists = userInfoRepo.findById(userInfo.getUsername()); - if (userExists.isPresent()) return "Failure. User already exists"; + if (userExists.isPresent()) { + return "Failure. User already exists"; + } userInfoRepo.save(userInfo); return ApiResultStatus.SUCCESS.value; @@ -317,7 +322,9 @@ public String insertIntoTeams(Team team) { } Optional teamExists = teamRepo.findById(teamID); - if (teamExists.isPresent()) return "Failure. Team already exists"; + if (teamExists.isPresent()) { + return "Failure. Team already exists"; + } team.setApp(""); teamRepo.save(team); @@ -337,8 +344,11 @@ public String insertIntoClusters(KwClusters kwClusters) { if (kwClusters.getClusterId() == null) { lastClusterId = kwClusterRepo.getNextClusterId(kwClusters.getTenantId()); - if (lastClusterId == null) lastClusterId = 1; - else lastClusterId = lastClusterId + 1; + if (lastClusterId == null) { + lastClusterId = 1; + } else { + lastClusterId = lastClusterId + 1; + } kwClusters.setClusterId(lastClusterId); } @@ -369,46 +379,65 @@ public String insertIntoRegisterUsers(RegisterUserInfo userInfo) { public Integer getNextTeamId(int tenantId) { Integer teamId = teamRepo.getNextTeamId(tenantId); if (teamId == null) return 1001; - else return teamId + 1; + else { + return teamId + 1; + } } public Integer getNextAclRequestId(int tenantId) { Integer aclReqId = aclRequestsRepo.getNextAclRequestId(tenantId); - if (aclReqId == null) return 1001; - else return aclReqId + 1; + if (aclReqId == null) { + return 1001; + } else { + return aclReqId + 1; + } } public Integer getNextAclId(int tenantId) { Integer aclId = aclRepo.getNextAclId(tenantId); - if (aclId == null) return 1001; - else return aclId + 1; + if (aclId == null) { + return 1001; + } else { + return aclId + 1; + } } public synchronized Integer getNextActivityLogRequestId(int tenantId) { Integer activityLogId = activityLogRepo.getNextActivityLogRequestId(tenantId); - if (activityLogId == null) return 1001; - else return activityLogId + 1; + if (activityLogId == null) { + return 1001; + } else { + return activityLogId + 1; + } } public Integer getNextTopicRequestId(String idType, int tenantId) { Integer topicId = null; - if ("TOPIC_REQ_ID".equals(idType)) topicId = topicRequestsRepo.getNextTopicRequestId(tenantId); - else if ("TOPIC_ID".equals(idType)) topicId = topicRepo.getNextTopicRequestId(tenantId); + if ("TOPIC_REQ_ID".equals(idType)) { + topicId = topicRequestsRepo.getNextTopicRequestId(tenantId); + } else if ("TOPIC_ID".equals(idType)) { + topicId = topicRepo.getNextTopicRequestId(tenantId); + } return topicId == null ? 1001 : topicId + 1; } public Integer getNextConnectorRequestId(String idType, int tenantId) { Integer topicId; - if (idType.equals("CONNECTOR_REQ_ID")) + if (idType.equals("CONNECTOR_REQ_ID")) { topicId = kafkaConnectorRequestsRepo.getNextConnectorRequestId(tenantId); - else if (idType.equals("CONNECTOR_ID")) + } else if (idType.equals("CONNECTOR_ID")) { topicId = kafkaConnectorRepo.getNextConnectorRequestId(tenantId); - else topicId = null; + } else { + topicId = null; + } - if (topicId == null) return 1001; - else return topicId + 1; + if (topicId == null) { + return 1001; + } else { + return topicId + 1; + } } public Integer getNextSchemaRequestId(String idType, int tenantId) { @@ -424,8 +453,11 @@ public Integer getNextSchemaRequestId(String idType, int tenantId) { public String addNewTenant(KwTenants kwTenants) { Integer maxTenantId = tenantRepo.getMaxTenantId(); - if (maxTenantId == null) maxTenantId = 101; - else maxTenantId = maxTenantId + 1; + if (maxTenantId == null) { + maxTenantId = 101; + } else { + maxTenantId = maxTenantId + 1; + } kwTenants.setTenantId(maxTenantId); tenantRepo.save(kwTenants); return ApiResultStatus.SUCCESS.value; @@ -438,8 +470,11 @@ public String registerUserForAD(RegisterUserInfo newUser) { public String insertMetrics(KwMetrics kwMetrics) { Integer metricsId = metricsRepo.getNextId(); - if (metricsId == null) metricsId = 1001; - else metricsId += 1; + if (metricsId == null) { + metricsId = 1001; + } else { + metricsId += 1; + } kwMetrics.setMetricsId(metricsId); @@ -464,8 +499,9 @@ public String insertDefaultRolesPermissions(List kwRolesPerm public Integer getNextRolePermissionId(int tenantId) { Integer maxId = kwRolesPermsRepo.getMaxRolePermissionId(tenantId); - - if (maxId == null) maxId = 1; + if (maxId == null) { + maxId = 1; + } return maxId + 1; } diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java index 97d0570fd4..3f86111df3 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/SelectDataJdbc.java @@ -118,9 +118,11 @@ public List selectAclRequests( teamName = row.getRequestingteam(); } - if (showRequestsOfAllTeams) // show all requests of all teams - aclList.add(row); - else if (teamSelected != null && teamSelected.equals(teamName)) aclList.add(row); + if (showRequestsOfAllTeams) { // show all requests of all teams + aclList.add(row); + } else if (teamSelected != null && teamSelected.equals(teamName)) { + aclList.add(row); + } try { row.setRequesttimestring( @@ -146,9 +148,7 @@ public List selectSchemaRequests(boolean allReqs, String requesto for (SchemaRequest row : schemaListSub) { Integer teamId = row.getTeamId(); - Integer teamSelected = selectUserInfo(requestor).getTeamId(); - try { row.setRequesttimestring( (new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss")) @@ -156,7 +156,9 @@ public List selectSchemaRequests(boolean allReqs, String requesto } catch (Exception ignored) { } - if (teamSelected != null && teamSelected.equals(teamId)) schemaList.add(row); + if (teamSelected != null && teamSelected.equals(teamId)) { + schemaList.add(row); + } } return schemaList; @@ -172,16 +174,22 @@ public SchemaRequest selectSchemaRequest(int avroSchemaId, int tenantId) { public List selectTopicDetails(String topic, int tenantId) { List topicOpt = topicRepo.findAllByTopicnameAndTenantId(topic, tenantId); - if (topicOpt.size() > 0) return topicOpt; - else return new ArrayList<>(); + if (topicOpt.size() > 0) { + return topicOpt; + } else { + return new ArrayList<>(); + } } public List selectConnectorDetails(String connectorName, int tenantId) { List topicOpt = kafkaConnectorRepo.findAllByConnectorNameAndTenantId(connectorName, tenantId); - if (topicOpt.size() > 0) return topicOpt; - else return new ArrayList<>(); + if (topicOpt.size() > 0) { + return topicOpt; + } else { + return new ArrayList<>(); + } } // "All teams" @@ -191,10 +199,15 @@ public List selectSyncTopics(String env, Integer teamId, int tenantId) { if (teamId == null || teamId.equals(1)) { if (env == null || env.equals("ALL")) { return topicRepo.findAllByTenantId(tenantId); - } else return topicRepo.findAllByEnvironmentAndTenantId(env, tenantId); + } else { + return topicRepo.findAllByEnvironmentAndTenantId(env, tenantId); + } } else { - if ("ALL".equals(env)) return topicRepo.findAllByTeamIdAndTenantId(teamId, tenantId); - else return topicRepo.findAllByEnvironmentAndTeamIdAndTenantId(env, teamId, tenantId); + if ("ALL".equals(env)) { + return topicRepo.findAllByTeamIdAndTenantId(teamId, tenantId); + } else { + return topicRepo.findAllByEnvironmentAndTeamIdAndTenantId(env, teamId, tenantId); + } } } @@ -229,9 +242,11 @@ public List selectAllTopicsByTopictypeAndTeamname( log.debug("selectAllByTopictypeAndTeamname {} {}", isProducerConsumer, teamId); List topics = new ArrayList<>(); String topicType, aclPatternType; - if (isProducerConsumer != null && isProducerConsumer.equals(AclType.PRODUCER.value)) + if (isProducerConsumer != null && isProducerConsumer.equals(AclType.PRODUCER.value)) { topicType = AclType.PRODUCER.value; - else topicType = AclType.CONSUMER.value; + } else { + topicType = AclType.CONSUMER.value; + } List acls = aclRepo.findAllByTopictypeAndTeamIdAndTenantId(topicType, teamId, tenantId); Topic t; @@ -352,8 +367,9 @@ public List selectTopicRequestsByStatus( } catch (Exception ignored) { } - if (showRequestsOfAllTeams) topicRequestList.add(row); // no team filter - else if (teamSelected != null + if (showRequestsOfAllTeams) { + topicRequestList.add(row); // no team filter + } else if (teamSelected != null && (teamSelected.equals(teamName) || ("" + teamSelected).equals(row.getDescription()))) { topicRequestList.add(row); } @@ -415,9 +431,10 @@ public List selectConnectorRequestsByStatus( } topicRequestListSub.addAll(claimTopicReqs); - } else + } else { topicRequestListSub = Lists.newArrayList(kafkaConnectorRequestsRepo.findAllByTenantId(tenantId)); + } for (KafkaConnectorRequest row : topicRequestListSub) { Integer teamName = row.getTeamId(); @@ -428,8 +445,9 @@ public List selectConnectorRequestsByStatus( } catch (Exception ignored) { } - if (showRequestsOfAllTeams) topicRequestList.add(row); // no team filter - else if (teamSelected != null + if (showRequestsOfAllTeams) { + topicRequestList.add(row); // no team filter + } else if (teamSelected != null && (Objects.equals(teamSelected, teamName) || Objects.equals("" + teamSelected, row.getDescription()))) { topicRequestList.add(row); @@ -482,8 +500,11 @@ public List selectAllUsersInfoForTeam(Integer teamId, int tenantId) { } public List selectAllEnvs(String type, int tenantId) { - if ("all".equals(type)) return Lists.newArrayList(envRepo.findAllByTenantId(tenantId)); - else return Lists.newArrayList(envRepo.findAllByTypeAndTenantId(type, tenantId)); + if ("all".equals(type)) { + return Lists.newArrayList(envRepo.findAllByTenantId(tenantId)); + } else { + return Lists.newArrayList(envRepo.findAllByTypeAndTenantId(type, tenantId)); + } } public Env selectEnvDetails(String environmentId, int tenantId) { @@ -507,15 +528,18 @@ public List selectActivityLog( UserInfo userInfo = selectUserInfo(username); if (allReqs) { - if (env == null || env.equals("")) + if (env == null || env.equals("")) { activityList = Lists.newArrayList(activityLogRepo.findAllByTenantId(tenantId)); - else activityList = activityLogRepo.findAllByEnvAndTenantId(env, tenantId); + } else { + activityList = activityLogRepo.findAllByEnvAndTenantId(env, tenantId); + } } else { - if (env == null || env.equals("")) + if (env == null || env.equals("")) { activityList = activityLogRepo.findAllByTeamIdAndTenantId(userInfo.getTeamId(), tenantId); - else + } else { activityList = activityLogRepo.findAllByEnvAndTeamIdAndTenantId(env, userInfo.getTeamId(), tenantId); + } } for (ActivityLog row : activityList) { @@ -570,14 +594,20 @@ Acl selectSyncAclsFromReqNo(int reqNo, int tenantId) { public List getTopics(String topicName, boolean allTopics, int tenantId) { log.debug("getTopics {} {}", topicName, allTopics); - if (allTopics) return Lists.newArrayList(topicRepo.findAllByTenantId(tenantId)); - else return topicRepo.findAllByTopicnameAndTenantId(topicName, tenantId); + if (allTopics) { + return Lists.newArrayList(topicRepo.findAllByTenantId(tenantId)); + } else { + return topicRepo.findAllByTopicnameAndTenantId(topicName, tenantId); + } } public List getConnectors(String topicName, boolean allTopics, int tenantId) { log.debug("getConnectors {} {}", topicName, allTopics); - if (allTopics) return Lists.newArrayList(kafkaConnectorRepo.findAllByTenantId(tenantId)); - else return kafkaConnectorRepo.findAllByConnectorNameAndTenantId(topicName, tenantId); + if (allTopics) { + return Lists.newArrayList(kafkaConnectorRepo.findAllByTenantId(tenantId)); + } else { + return kafkaConnectorRepo.findAllByConnectorNameAndTenantId(topicName, tenantId); + } } public Optional getTopicFromId(int topicId, int tenantId) { @@ -620,8 +650,11 @@ public Team selectTeamDetails(Integer teamId, int tenantId) { public Team selectTeamDetailsFromName(String teamName, int tenantId) { List teamList = teamRepo.findAllByTenantIdAndTeamname(tenantId, teamName); - if (!teamList.isEmpty()) return teamList.get(0); - else return null; + if (!teamList.isEmpty()) { + return teamList.get(0); + } else { + return null; + } } public List> selectActivityLogByTeam( @@ -651,8 +684,9 @@ public List> selectActivityLogForLastDays( try { List activityCount = activityLogRepo.findActivityLogForLastDays(envIdList, tenantId); - if (activityCount.size() > numberOfDays) + if (activityCount.size() > numberOfDays) { activityCount = activityCount.subList(0, numberOfDays - 1); + } Map hashMap; for (Object[] actvty : activityCount) { hashMap = new HashMap<>(); @@ -690,8 +724,11 @@ public List> selectPartitionsCountByEnv(Integer teamId, Inte List> totalPartitionsCount = new ArrayList<>(); try { List topics; - if (teamId != null) topics = topicRepo.findAllPartitionsForTeamGroupByEnv(teamId, tenantId); - else topics = topicRepo.findAllPartitionsGroupByEnv(tenantId); + if (teamId != null) { + topics = topicRepo.findAllPartitionsForTeamGroupByEnv(teamId, tenantId); + } else { + topics = topicRepo.findAllPartitionsGroupByEnv(tenantId); + } Map hashMap; for (Object[] topic : topics) { @@ -711,8 +748,11 @@ public List> selectAclsCountByEnv(Integer teamId, Integer te List> totalAclsCount = new ArrayList<>(); try { List topics; - if (teamId != null) topics = aclRepo.findAllAclsforTeamGroupByEnv(teamId, tenantId); - else topics = aclRepo.findAllAclsGroupByEnv(tenantId); + if (teamId != null) { + topics = aclRepo.findAllAclsforTeamGroupByEnv(teamId, tenantId); + } else { + topics = aclRepo.findAllAclsGroupByEnv(tenantId); + } Map hashMap; for (Object[] topic : topics) { @@ -732,8 +772,11 @@ public List> selectTopicsCountByTeams(Integer teamId, int te List> totalTopicCount = new ArrayList<>(); try { List topics; - if (teamId != null) topics = topicRepo.findAllTopicsForTeam(teamId, tenantId); - else topics = topicRepo.findAllTopicsGroupByTeamId(tenantId); + if (teamId != null) { + topics = topicRepo.findAllTopicsForTeam(teamId, tenantId); + } else { + topics = topicRepo.findAllTopicsGroupByTeamId(tenantId); + } Map hashMap; for (Object[] topic : topics) { @@ -804,7 +847,9 @@ public List> selectAllTopicsForTeamGroupByEnv(Integer teamId hashMap.put("cluster", selectEnvDetails((String) topic[0], tenantId).getName()); hashMap.put("topicscount", "" + ((BigInteger) topic[1]).intValue()); totalTopicCount.add(hashMap); - } else log.error("Error: Environment not found for env {}", topic[0]); + } else { + log.error("Error: Environment not found for env {}", topic[0]); + } } } catch (Exception e) { log.error("Error from selectAllTopicsForTeamGroupByEnv ", e); @@ -863,12 +908,19 @@ public List selectAllKwPropertiesPerTenant(int tenantId) { public Integer getNextTopicRequestId(String idType, int tenantId) { Integer topicId; - if (idType.equals("TOPIC_REQ_ID")) topicId = topicRequestsRepo.getNextTopicRequestId(tenantId); - else if (idType.equals("TOPIC_ID")) topicId = topicRepo.getNextTopicRequestId(tenantId); - else topicId = null; + if (idType.equals("TOPIC_REQ_ID")) { + topicId = topicRequestsRepo.getNextTopicRequestId(tenantId); + } else if (idType.equals("TOPIC_ID")) { + topicId = topicRepo.getNextTopicRequestId(tenantId); + } else { + topicId = null; + } - if (topicId == null) return 1001; - else return topicId + 1; + if (topicId == null) { + return 1001; + } else { + return topicId + 1; + } } public Integer getNextConnectorRequestId(String idType, int tenantId) { @@ -898,11 +950,12 @@ public List getRolesPermissionsPerTenant(int tenantId) { } public List getAllClusters(String typeOfCluster, int tenantId) { - if ("all".equals(typeOfCluster)) + if ("all".equals(typeOfCluster)) { return Lists.newArrayList(kwClusterRepo.findAllByTenantId(tenantId)); - else + } else { return Lists.newArrayList( kwClusterRepo.findAllByClusterTypeAndTenantId(typeOfCluster, tenantId)); + } } public KwClusters getClusterDetails(int id, int tenantId) { @@ -932,9 +985,13 @@ public String getRegistrationId(String userId) { registerInfoRepo.findAllByUsernameAndStatus(userId, "STAGING"); List registerInfoList1 = registerInfoRepo.findAllByUsernameAndStatus(userId, "PENDING"); - if (registerInfoList.size() > 0) return registerInfoList.get(0).getRegistrationId(); - else if (registerInfoList1.size() > 0) return "PENDING_ACTIVATION"; - else return null; + if (registerInfoList.size() > 0) { + return registerInfoList.get(0).getRegistrationId(); + } else if (registerInfoList1.size() > 0) { + return "PENDING_ACTIVATION"; + } else { + return null; + } } public RegisterUserInfo getRegistrationDetails(String registrationId, String status) { @@ -975,7 +1032,9 @@ public List selectSyncConnectors(String env, Integer teamId, i if (teamId == null || teamId.equals(1)) { if (env == null || env.equals("ALL")) { return kafkaConnectorRepo.findAllByTenantId(tenantId); - } else return kafkaConnectorRepo.findAllByEnvironmentAndTenantId(env, tenantId); + } else { + return kafkaConnectorRepo.findAllByEnvironmentAndTenantId(env, tenantId); + } } else { if ("ALL".equals(env)) { return kafkaConnectorRepo.findAllByTeamIdAndTenantId(teamId, tenantId); diff --git a/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java b/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java index f27d168090..6b6c133bf9 100644 --- a/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java +++ b/src/main/java/io/aiven/klaw/helpers/db/rdbms/UpdateDataJdbc.java @@ -316,8 +316,11 @@ public void updateNewUserRequest(String username, String approver, boolean isApp log.debug("updateNewUserRequest {} {} {}", username, approver, isApprove); Optional registerUser = registerInfoRepo.findById(username); String status; - if (isApprove) status = "APPROVED"; - else status = "DECLINED"; + if (isApprove) { + status = "APPROVED"; + } else { + status = "DECLINED"; + } if (registerUser.isPresent()) { RegisterUserInfo registerUserInfo = registerUser.get(); if ("PENDING".equals(registerUserInfo.getStatus())) { @@ -333,7 +336,9 @@ public void updateNewUserRequest(String username, String approver, boolean isApp public String updateUser(UserInfo userInfo) { log.debug("updateUser {}", userInfo.getUsername()); Optional userExists = userInfoRepo.findById(userInfo.getUsername()); - if (!userExists.isPresent()) return "Failure. User doesn't exist"; + if (userExists.isEmpty()) { + return "Failure. User doesn't exist"; + } userInfoRepo.save(userInfo); return ApiResultStatus.SUCCESS.value; @@ -343,7 +348,9 @@ public String updateTeam(Team team) { log.debug("updateTeam {}", team); TeamID teamID = new TeamID(team.getTeamId(), team.getTenantId()); Optional teamExists = teamRepo.findById(teamID); - if (teamExists.isEmpty()) return "Failure. Team doesn't exist"; + if (teamExists.isEmpty()) { + return "Failure. Team doesn't exist"; + } teamRepo.save(team); return ApiResultStatus.SUCCESS.value; @@ -363,7 +370,6 @@ public String updateKwProperty(KwProperties kwProperties, int tenantId) { public Integer getNextRolePermissionId(int tenantId) { Integer maxId = kwRolesPermsRepo.getMaxRolePermissionId(tenantId); - if (maxId == null) maxId = 1; return maxId + 1; @@ -423,8 +429,11 @@ public String updateConnectorDocumentation(KwKafkaConnector topic) { public String setTenantActivestatus(int tenantId, boolean status) { Optional kwTenant = tenantRepo.findById(tenantId); if (kwTenant.isPresent()) { - if (status) kwTenant.get().setIsActive("true"); - else kwTenant.get().setIsActive("false"); + if (status) { + kwTenant.get().setIsActive("true"); + } else { + kwTenant.get().setIsActive("false"); + } tenantRepo.save(kwTenant.get()); } diff --git a/src/main/java/io/aiven/klaw/service/AclControllerService.java b/src/main/java/io/aiven/klaw/service/AclControllerService.java index 5f49f0cb50..7b55f83ba9 100644 --- a/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -99,7 +99,9 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { } } result = "Failure : Topic not found on target environment."; - if (!topicFound) return ApiResponse.builder().result(result).build(); + if (!topicFound) { + return ApiResponse.builder().result(result).build(); + } } if (AclType.CONSUMER.value.equals(aclReq.getTopictype())) { @@ -128,7 +130,9 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { for (int i = 0; i < aclReq.getAcl_ip().size(); i++) { if (i == 0) { aclStr.append(aclReq.getAcl_ip().get(i)); - } else aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ip().get(i)); + } else { + aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ip().get(i)); + } } aclRequestsDao.setAcl_ip(aclStr.toString()); } @@ -137,13 +141,16 @@ public ApiResponse createAcl(AclRequestsModel aclReq) throws KlawException { for (int i = 0; i < aclReq.getAcl_ssl().size(); i++) { if (i == 0) { aclStr.append(aclReq.getAcl_ssl().get(i)); - } else aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ssl().get(i)); + } else { + aclStr = new StringBuilder(aclStr + separatorAcl + aclReq.getAcl_ssl().get(i)); + } } aclRequestsDao.setAcl_ssl(aclStr.toString()); } - if (aclReq.getAcl_ssl() == null || aclReq.getAcl_ssl().equals("null")) + if (aclReq.getAcl_ssl() == null || aclReq.getAcl_ssl().equals("null")) { aclRequestsDao.setAcl_ssl("User:*"); + } aclRequestsDao.setTenantId(tenantId); try { @@ -254,8 +261,9 @@ private String updateApprovingInfo( for (UserInfo userInfo : userList) { if (approverRoles.contains(userInfo.getRole()) - && !Objects.equals(requestor, userInfo.getUsername())) + && !Objects.equals(requestor, userInfo.getUsername())) { approvingInfo.append(userInfo.getUsername()).append(","); + } } return String.valueOf(approvingInfo); } @@ -343,16 +351,17 @@ public List getCreatedAclRequests( // get requests relevant to your teams or all teams if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { createdAclReqs = manageDatabase .getHandleDbRequests() .getCreatedAclRequestsByStatus(userDetails, requestsType, false, tenantId); - else + } else { createdAclReqs = manageDatabase .getHandleDbRequests() .getCreatedAclRequestsByStatus(userDetails, requestsType, true, tenantId); + } // tenant filtering List allowedEnvIdList = getEnvsFromUserId(userDetails); @@ -410,8 +419,9 @@ public ApiResponse createDeleteAclSubscriptionRequest(String req_no) throws Klaw dbHandle.selectSyncAclsFromReqNo( Integer.parseInt(req_no), commonUtilsService.getTenantId(getUserName())); - if (!getEnvsFromUserId(userDetails).contains(acl.getEnvironment())) + if (!getEnvsFromUserId(userDetails).contains(acl.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } AclRequests aclReq = new AclRequests(); @@ -450,18 +460,20 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); AclRequests aclReq = dbHandle.selectAcl(Integer.parseInt(req_no), tenantId); - if (Objects.equals(aclReq.getUsername(), userDetails)) + if (Objects.equals(aclReq.getUsername(), userDetails)) { return ApiResponse.builder() .result("You are not allowed to approve your own subscription requests.") .build(); + } if (!RequestStatus.created.name().equals(aclReq.getAclstatus())) { return ApiResponse.builder().result("This request does not exist anymore.").build(); } // tenant filtering - if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) + if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } String allIps = aclReq.getAcl_ip(); String allSsl = aclReq.getAcl_ssl(); @@ -494,12 +506,14 @@ public ApiResponse approveAclRequests(String req_no) throws KlawException { String jsonParams = "", aivenAclIdKey = "aivenaclid"; if (responseBody.getData() instanceof Map) { Map dataMap = (Map) responseBody.getData(); - if (dataMap.containsKey(aivenAclIdKey)) + if (dataMap.containsKey(aivenAclIdKey)) { jsonParams = "{\"" + aivenAclIdKey + "\":\"" + dataMap.get(aivenAclIdKey) + "\"}"; + } } updateAclReqStatus = dbHandle.updateAclRequest(aclReq, userDetails, jsonParams); - - } else return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } else { + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } } catch (Exception e) { log.error("Exception ", e); return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); @@ -538,8 +552,9 @@ public ApiResponse declineAclRequests(String req_no, String reasonToDecline) } // tenant filtering - if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) + if (!getEnvsFromUserId(userDetails).contains(aclReq.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } String updateAclReqStatus; @@ -568,10 +583,10 @@ public ApiResponse declineAclRequests(String req_no, String reasonToDecline) private List getAclsFromSOT( String env, String topicNameSearch, boolean regex, int tenantId) { List aclsFromSOT; - if (!regex) + if (!regex) { aclsFromSOT = manageDatabase.getHandleDbRequests().getSyncAcls(env, topicNameSearch, tenantId); - else { + } else { aclsFromSOT = manageDatabase.getHandleDbRequests().getSyncAcls(env, tenantId); List topicFilteredList = aclsFromSOT; // Filter topics on topic name for search @@ -592,8 +607,9 @@ private Map getTopicPromotionEnv( String topicSearch, List topics, int tenantId) { Map hashMap = new HashMap<>(); try { - if (topics == null) + if (topics == null) { topics = manageDatabase.getHandleDbRequests().getTopics(topicSearch, tenantId); + } hashMap.put("topicName", topicSearch); @@ -635,11 +651,12 @@ private List getFilteredTopicsForTenant(List topicsFromSOT) { // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (topicsFromSOT != null) + if (topicsFromSOT != null) { topicsFromSOT = topicsFromSOT.stream() .filter(topic -> allowedEnvIdList.contains(topic.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception exception) { log.error("No environments/clusters found."); return new ArrayList<>(); @@ -653,8 +670,11 @@ public TopicOverview getAcls(String topicNameSearch) { HandleDbRequests handleDb = manageDatabase.getHandleDbRequests(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); - else return null; + if (topicNameSearch != null) { + topicNameSearch = topicNameSearch.trim(); + } else { + return null; + } Integer loggedInUserTeam = getMyTeamId(userDetails); List topics = handleDb.getTopics(topicNameSearch, tenantId); @@ -671,7 +691,9 @@ public TopicOverview getAcls(String topicNameSearch) { if (topics.size() == 0) { topicOverview.setTopicExists(false); return topicOverview; - } else topicOverview.setTopicExists(true); + } else { + topicOverview.setTopicExists(true); + } String syncCluster; String[] reqTopicsEnvs; @@ -750,7 +772,9 @@ public TopicOverview getAcls(String topicNameSearch) { .collect(Collectors.groupingBy(AclInfo::getTopicname)) .get(topicNameSearch); - if (tmpAcl != null) aclInfo.addAll(tmpAcl); + if (tmpAcl != null) { + aclInfo.addAll(tmpAcl); + } allPrefixedAcls = handleDb.getPrefixedAclsSOT(topicInfo.getClusterId(), tenantId); if (allPrefixedAcls != null && allPrefixedAcls.size() > 0) { @@ -771,7 +795,6 @@ public TopicOverview getAcls(String topicNameSearch) { } aclInfo = aclInfo.stream().distinct().collect(Collectors.toList()); - List transactionalAcls = aclInfo.stream() .filter(aclRec -> aclRec.getTransactionalId() != null) diff --git a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java index b0d12c84a7..e5e72645c8 100644 --- a/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java @@ -264,7 +264,9 @@ private List> groupAcls( if (topicNameSearch != null) { return "TOPIC".equals(hItem.get("resourceType")) && hItem.get("resourceName").contains(topicNameSearch); - } else return "TOPIC".equals(hItem.get("resourceType")); + } else { + return "TOPIC".equals(hItem.get("resourceType")); + } } else { return Objects.equals(hItem.get("resourceName"), topicNameSearch); } @@ -306,10 +308,13 @@ public List getSyncAcls( boolean isReconciliation = !Boolean.parseBoolean(showAllAcls); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); + if (topicNameSearch != null) { + topicNameSearch = topicNameSearch.trim(); + } - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { return null; + } List> aclList; @@ -345,13 +350,17 @@ public List getSyncBackAcls( int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) return null; + getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { + return null; + } List aclsFromSOT; - if (topicNameSearch != null && topicNameSearch.trim().length() > 0) + if (topicNameSearch != null && topicNameSearch.trim().length() > 0) { aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, false, tenantId); - else aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, true, tenantId); + } else { + aclsFromSOT = getAclsFromSOT(envId, topicNameSearch, true, tenantId); + } List aclInfoList; Integer loggedInUserTeam = getMyTeamId(getUserName()); @@ -385,7 +394,9 @@ private List applyFiltersAclsForSOT( if (aclSotItem.getTeamId() != null && aclSotItem.getTeamId().equals(loggedInUserTeam)) mp.setShowDeleteAcl(true); - if (aclSotItem.getAclip() != null || aclSotItem.getAclssl() != null) aclList.add(mp); + if (aclSotItem.getAclip() != null || aclSotItem.getAclssl() != null) { + aclList.add(mp); + } } return aclList; } @@ -405,23 +416,25 @@ private List applyFiltersAcls( for (Map aclListItem : aclList) { AclInfo mp = new AclInfo(); mp.setEnvironment(env); - mp.setPossibleTeams(teamList); mp.setTeamname(""); String tmpPermType = aclListItem.get("operation"); - if (AclPermissionType.WRITE.value.equals(tmpPermType)) + if (AclPermissionType.WRITE.value.equals(tmpPermType)) { mp.setTopictype(AclType.PRODUCER.value); - else if (AclPermissionType.READ.value.equals(tmpPermType)) { + } else if (AclPermissionType.READ.value.equals(tmpPermType)) { mp.setTopictype(AclType.CONSUMER.value); - if (aclListItem.get("consumerGroup") != null) + if (aclListItem.get("consumerGroup") != null) { mp.setConsumergroup(aclListItem.get("consumerGroup")); - else continue; + } else { + continue; + } } - if ("topic".equalsIgnoreCase(aclListItem.get("resourceType"))) + if ("topic".equalsIgnoreCase(aclListItem.get("resourceType"))) { mp.setTopicname(aclListItem.get("resourceName")); + } mp.setAcl_ip(aclListItem.get("host")); mp.setAcl_ssl(aclListItem.get("principle")); @@ -430,8 +443,9 @@ else if (AclPermissionType.READ.value.equals(tmpPermType)) { String acl_ssl = aclSotItem.getAclssl(); String acl_host = aclSotItem.getAclip(); - if (acl_ssl == null || acl_ssl.equals("")) acl_ssl = "User:*"; - else { + if (acl_ssl == null || acl_ssl.equals("")) { + acl_ssl = "User:*"; + } else { if (!KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value.equals(kafkaFlavor) && !"User:*".equals(acl_ssl) && !acl_ssl.startsWith("User:")) { @@ -439,7 +453,9 @@ else if (AclPermissionType.READ.value.equals(tmpPermType)) { } } - if (acl_host == null || acl_host.equals("")) acl_host = "*"; + if (acl_host == null || acl_host.equals("")) { + acl_host = "*"; + } if (aclSotItem.getTopicname() != null && Objects.equals(aclListItem.get("resourceName"), aclSotItem.getTopicname()) @@ -452,14 +468,19 @@ else if (AclPermissionType.READ.value.equals(tmpPermType)) { } } - if (mp.getTeamname() == null) mp.setTeamname("Unknown"); + if (mp.getTeamname() == null) { + mp.setTeamname("Unknown"); + } if (isReconciliation) { - if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) aclListMap.add(mp); + if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) { + aclListMap.add(mp); + } } else { if (teamList.contains(mp.getTeamname())) aclListMap.add(mp); - else if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) + else if ("Unknown".equals(mp.getTeamname()) || "".equals(mp.getTeamname())) { aclListMap.add(mp); + } } } return aclListMap; @@ -475,9 +496,7 @@ private List tenantFiltering(List teamList) { getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { // tenant filtering int tenantId = commonUtilsService.getTenantId(getUserName()); - List teams = manageDatabase.getHandleDbRequests().selectAllTeams(tenantId); - teams = teams.stream() .filter(t -> Objects.equals(t.getTenantId(), tenantId)) diff --git a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java index 211f33fcd3..97e51166c0 100644 --- a/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java @@ -145,9 +145,11 @@ public ChartsJsOverview getProducerAclsTeamsOverview(Integer teamId, Integer ten .selectAclsCountByTeams(AclType.PRODUCER.value, teamId, tenantId); String title = "Producer Acls"; - if (teamId != null) + if (teamId != null) { title += " (" + manageDatabase.getTeamNameFromTeamId(tenantId, teamId) + ")"; - else title += " (all teams)"; + } else { + title += " (all teams)"; + } return commonUtilsService.getChartsJsOverview( producerAclsPerTeamList, title, "aclscount", "teamid", "Teams", "Producer Acls", tenantId); @@ -160,9 +162,11 @@ public ChartsJsOverview getConsumerAclsTeamsOverview(Integer teamId, Integer ten .selectAclsCountByTeams(AclType.CONSUMER.value, teamId, tenantId); String title = "Consumer Acls"; - if (teamId != null) + if (teamId != null) { title += " (" + manageDatabase.getTeamNameFromTeamId(tenantId, teamId) + ")"; - else title += " (all teams)"; + } else { + title += " (all teams)"; + } return commonUtilsService.getChartsJsOverview( consumerAclsPerTeamList, title, "aclscount", "teamid", "Teams", "Consumer Acls", tenantId); @@ -173,9 +177,11 @@ public ChartsJsOverview getTopicsTeamsOverview(Integer teamId, Integer tenantId) List> teamCountList = manageDatabase.getHandleDbRequests().selectTopicsCountByTeams(teamId, tenantId); String title = "Topics in all clusters"; - if (teamId != null) + if (teamId != null) { title += " (" + manageDatabase.getTeamNameFromTeamId(tenantId, teamId) + ")"; - else title += " (all teams)"; + } else { + title += " (all teams)"; + } return commonUtilsService.getChartsJsOverview( teamCountList, title, "topicscount", "teamid", "Teams", "Topics", tenantId); @@ -235,8 +241,9 @@ public ChartsJsOverview getPartitionsEnvOverview(Integer teamId, Integer tenantI List> partitionsCountList = manageDatabase.getHandleDbRequests().selectPartitionsCountByEnv(teamId, tenantId); String title = "Partitions per cluster"; - if (teamId != null) + if (teamId != null) { title += " (" + manageDatabase.getTeamNameFromTeamId(tenantId, teamId) + ")"; + } // tenant filtering try { @@ -269,8 +276,9 @@ public ChartsJsOverview getAclsEnvOverview(Integer teamId, Integer tenantId) { List> aclsPerEnvList = manageDatabase.getHandleDbRequests().selectAclsCountByEnv(teamId, tenantId); String title = "Acls per cluster"; - if (teamId != null) + if (teamId != null) { title += " (" + manageDatabase.getTeamNameFromTeamId(tenantId, teamId) + ")"; + } // tenant filtering try { @@ -335,38 +343,6 @@ public List getTeamsOverview(String forTeam) { Integer userTeamId = getMyTeamId(getUserName()); - // All tenant reports - // if(!commonUtilsService.isNotAuthorizedUser(getPrincipal(), - // PermissionType.ALL_TENANTS_REPORTS)) { - // Map tenantMap = manageDatabase.getTenantMap(); - // for (Integer uniqueTenantId : tenantMap.keySet()) { - // teamOverview = new TeamOverview(); - // teamOverview.setTenantName(manageDatabase.getTenantMap().get(uniqueTenantId)); - // - // teamOverview.setTopicsPerEnvOverview(getTopicsEnvOverview(uniqueTenantId, - // PermissionType.ALL_TENANTS_REPORTS)); - // teamOverview.setPartitionsPerEnvOverview(getPartitionsEnvOverview(null, - // uniqueTenantId)); - // teamOverview.setAclsPerEnvOverview(getAclsEnvOverview(null, uniqueTenantId)); - // - // teamOverview.setTopicsPerTeamsOverview(getTopicsTeamsOverview(null, - // uniqueTenantId)); - // - // - // teamOverview.setProducerAclsPerTeamsOverview(getProducerAclsTeamsOverview(null, - // uniqueTenantId)); - // - // teamOverview.setConsumerAclsPerTeamsOverview(getConsumerAclsTeamsOverview(null, - // uniqueTenantId)); - // - // teamOverview.setActivityLogOverview(getActivityLogOverview(null, - // uniqueTenantId)); - // - // listTeamOverview.add(teamOverview); - // } - // } - // else - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -410,8 +386,9 @@ public TeamOverview getActivityLogForTeamOverview(String forTeam) { teamOverview.setTopicsPerTeamPerEnvOverview( getTopicsPerTeamEnvOverview(commonUtilsService.getTenantId(getUserName()))); - if (forTeam != null && forTeam.equals("true")) + if (forTeam != null && forTeam.equals("true")) { teamOverview.setActivityLogOverview(getActivityLogOverview(userTeamId, 101)); + } return teamOverview; } @@ -440,9 +417,11 @@ public File generateReport() { String actualFileName; for (TeamOverview totalOverview : totalOverviewList) { - if (totalOverview.getTenantName() != null) + if (totalOverview.getTenantName() != null) { actualFileName = "Klaw-" + totalOverview.getTenantName() + ".xlsx"; - else actualFileName = "KlawReport" + ".xlsx"; + } else { + actualFileName = "KlawReport" + ".xlsx"; + } String fileName = kwReportsLocation + actualFileName; File reportFile = new File(fileName); @@ -515,7 +494,9 @@ private void addTopicNamesPerEnvToReport( List> allTopicLists = new ArrayList<>(); for (String envName : envNames) { allTopicLists.add(topicNames.get(envName)); - if (topicNames.get(envName).size() > maxSize) maxSize = topicNames.get(envName).size(); + if (topicNames.get(envName).size() > maxSize) { + maxSize = topicNames.get(envName).size(); + } } // set content @@ -523,8 +504,11 @@ private void addTopicNamesPerEnvToReport( for (int i = 0; i < maxSize; i++) { rowValList = new ArrayList<>(); for (List allTopicList : allTopicLists) { - if (allTopicList.size() > i) rowValList.add(allTopicList.get(i)); - else rowValList.add(""); + if (allTopicList.size() > i) { + rowValList.add(allTopicList.get(i)); + } else { + rowValList.add(""); + } } data.put(id, new Object[] {id - 1, rowValList}); id++; diff --git a/src/main/java/io/aiven/klaw/service/ClusterApiService.java b/src/main/java/io/aiven/klaw/service/ClusterApiService.java index c468a80973..a89206d8ab 100644 --- a/src/main/java/io/aiven/klaw/service/ClusterApiService.java +++ b/src/main/java/io/aiven/klaw/service/ClusterApiService.java @@ -137,8 +137,11 @@ public String getClusterApiStatus(String clusterApiUrl, boolean testConnection, try { String uriClusterApiStatus = "/topics/getApiStatus"; String uri; - if (testConnection) uri = clusterApiUrl + uriClusterApiStatus; - else uri = clusterConnUrl + uriClusterApiStatus; // from stored kw props + if (testConnection) { + uri = clusterApiUrl + uriClusterApiStatus; + } else { + uri = clusterConnUrl + uriClusterApiStatus; // from stored kw props + } ResponseEntity resultBody = getRestTemplate().exchange(uri, HttpMethod.GET, getHttpEntity(), ClusterStatus.class); @@ -350,10 +353,10 @@ public List> getAllTopics( getClusterApiProperties(tenantId); List> topicsList; try { - String URI_GET_TOPICS = "/topics/getTopics/"; + String uriGetTopics = "/topics/getTopics/"; String uriGetTopicsFull = clusterConnUrl - + URI_GET_TOPICS + + uriGetTopics + bootstrapHost + "/" + protocol @@ -397,13 +400,15 @@ public String approveConnectorRequests( .build(); String uri; - String URI_GET_TOPICS = "/topics/"; + String uriGetTopics = "/topics/"; if (RequestOperationType.CREATE.value.equals(connectorType)) { - uri = clusterConnUrl + URI_GET_TOPICS + "postConnector"; + uri = clusterConnUrl + uriGetTopics + "postConnector"; } else if (RequestOperationType.UPDATE.value.equals(connectorType)) { - uri = clusterConnUrl + URI_GET_TOPICS + "updateConnector"; - } else uri = clusterConnUrl + URI_GET_TOPICS + "deleteConnector"; + uri = clusterConnUrl + uriGetTopics + "updateConnector"; + } else { + uri = clusterConnUrl + uriGetTopics + "deleteConnector"; + } HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); headers.setContentType(MediaType.APPLICATION_JSON); @@ -468,7 +473,9 @@ public ResponseEntity approveTopicRequests( .partitions(topicPartitions) .replicationFactor(Short.parseShort(replicationFactor)) .build(); - } else uri = clusterConnUrl + URI_DELETE_TOPICS; + } else { + uri = clusterConnUrl + URI_DELETE_TOPICS; + } HttpHeaders headers = createHeaders(clusterApiUser, clusterApiPwd); headers.setContentType(MediaType.APPLICATION_JSON); @@ -512,18 +519,20 @@ public ResponseEntity approveAclRequests(AclRequests aclReq, int te .username(aclReq.getAcl_ssl()) .build(); - if (Objects.equals(aclReq.getTopictype(), AclType.PRODUCER.value)) + if (Objects.equals(aclReq.getTopictype(), AclType.PRODUCER.value)) { clusterAclRequest = clusterAclRequest.toBuilder().permission("write").build(); - else clusterAclRequest = clusterAclRequest.toBuilder().permission("read").build(); + } else { + clusterAclRequest = clusterAclRequest.toBuilder().permission("read").build(); + } if (Objects.equals(RequestOperationType.DELETE.value, aclReq.getAclType()) && null != aclReq.getJsonParams()) { Map jsonObj = OBJECT_MAPPER.readValue(aclReq.getJsonParams(), Map.class); String aivenAclKey = "aivenaclid"; - if (jsonObj.containsKey(aivenAclKey)) + if (jsonObj.containsKey(aivenAclKey)) { clusterAclRequest = clusterAclRequest.toBuilder().aivenAclKey(jsonObj.get(aivenAclKey)).build(); - else { + } else { log.error("Error from approveAclRequests : AclId - aivenaclid not found"); throw new KlawException( "Could not approve acl request. AclId - Aiven acl id not found."); @@ -658,9 +667,9 @@ public Map getConnectorDetails( log.info("getConnectorDetails {} {}", connectorName, kafkaConnectHost); getClusterApiProperties(tenantId); try { - String URI_GET_TOPICS = + String uriGetTopics = "/topics/getConnectorDetails/" + connectorName + "/" + kafkaConnectHost + "/" + protocol; - String uriGetConnectorsFull = clusterConnUrl + URI_GET_TOPICS; + String uriGetConnectorsFull = clusterConnUrl + uriGetTopics; ResponseEntity> s = getRestTemplate() @@ -682,8 +691,8 @@ public ArrayList getAllKafkaConnectors(String kafkaConnectHost, int tena log.info("getAllKafkaConnectors {}", kafkaConnectHost); getClusterApiProperties(tenantId); try { - String URI_GET_TOPICS = "/topics/getAllConnectors/" + kafkaConnectHost; - String uriGetConnectorsFull = clusterConnUrl + URI_GET_TOPICS; + String uriGetTopics = "/topics/getAllConnectors/" + kafkaConnectHost; + String uriGetConnectorsFull = clusterConnUrl + uriGetTopics; ResponseEntity> s = getRestTemplate() @@ -705,12 +714,12 @@ public Map retrieveMetrics(String jmxUrl, String objectName) log.info("retrieveMetrics {} {}", jmxUrl, objectName); getClusterApiProperties(101); try { - String URI_GET_TOPICS = "/metrics/getMetrics"; + String uriGetTopics = "/metrics/getMetrics"; MultiValueMap params = new LinkedMultiValueMap<>(); params.add("jmxUrl", jmxUrl); params.add("objectName", objectName); - String uriGetTopicsFull = clusterConnUrl + URI_GET_TOPICS; + String uriGetTopicsFull = clusterConnUrl + uriGetTopics; RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = diff --git a/src/main/java/io/aiven/klaw/service/CommonUtilsService.java b/src/main/java/io/aiven/klaw/service/CommonUtilsService.java index d52a4c04ce..3a51701bfd 100644 --- a/src/main/java/io/aiven/klaw/service/CommonUtilsService.java +++ b/src/main/java/io/aiven/klaw/service/CommonUtilsService.java @@ -90,7 +90,9 @@ String getAuthority(Object principal) { Object[] authorities = defaultOAuth2User.getAuthorities().toArray(); if (authorities.length > 0) { return (String) authorities[0]; - } else return ""; + } else { + return ""; + } } else if (principal instanceof String) { return manageDatabase.getHandleDbRequests().getUsersInfo((String) principal).getRole(); } else if (principal instanceof UserDetails) { @@ -98,13 +100,20 @@ String getAuthority(Object principal) { if (authorities.length > 0) { SimpleGrantedAuthority sag = (SimpleGrantedAuthority) authorities[0]; return sag.getAuthority(); - } else return ""; + } else { + return ""; + } - } else return ""; + } else { + return ""; + } } else { UserInfo userInfo = manageDatabase.getHandleDbRequests().getUsersInfo(getUserName(principal)); - if (userInfo != null) return userInfo.getRole(); - else return null; + if (userInfo != null) { + return userInfo.getRole(); + } else { + return null; + } } } @@ -159,11 +168,13 @@ public ChartsJsOverview getChartsJsOverview( totalCount += Integer.parseInt(hashMap.get(yaxisCount)); data.add(Integer.parseInt(hashMap.get(yaxisCount))); - if ("teamid".equals(xaxisLabel)) + if ("teamid".equals(xaxisLabel)) { labels.add( manageDatabase.getTeamNameFromTeamId( tenantId, Integer.parseInt(hashMap.get(xaxisLabel)))); - else labels.add(hashMap.get(xaxisLabel)); + } else { + labels.add(hashMap.get(xaxisLabel)); + } colors.add("Green"); } @@ -180,23 +191,6 @@ public ChartsJsOverview getChartsJsOverview( title1.setFontColor("red"); options.setTitle(title1); - - // Scales scales = new Scales(); - // List yAxList = new ArrayList<>(); - // List xAxList = new ArrayList<>(); - // - // YAx yAx = new YAx(); - // yAx.setDisplay(true); - // yAx.setId("hello"); - // yAx.setPosition("bottom"); - // yAx.setType("linear"); - // yAxList.add(yAx); - // - // - // scales.setYAxes(yAxList); - // scales.setXAxes(xAxList); - // - // options.setScales(scales); chartsJsOverview.setOptions(options); chartsJsOverview.setTitleForReport(title); @@ -309,17 +303,19 @@ public void updateMetadata( public synchronized void updateMetadata(KwMetadataUpdates kwMetadataUpdates) { final EntityType entityType = EntityType.of(kwMetadataUpdates.getEntityType()); - if (entityType == null) return; + if (entityType == null) { + return; + } final MetadataOperationType operationType = MetadataOperationType.of(kwMetadataUpdates.getOperationType()); if (entityType == EntityType.TEAM) { manageDatabase.loadEnvsForOneTenant(kwMetadataUpdates.getTenantId()); manageDatabase.loadTenantTeamsForOneTenant(null, kwMetadataUpdates.getTenantId()); - } else if (entityType == EntityType.CLUSTER && operationType == MetadataOperationType.DELETE) + } else if (entityType == EntityType.CLUSTER && operationType == MetadataOperationType.DELETE) { manageDatabase.deleteCluster(kwMetadataUpdates.getTenantId()); - else if (entityType == EntityType.CLUSTER && operationType == MetadataOperationType.CREATE) + } else if (entityType == EntityType.CLUSTER && operationType == MetadataOperationType.CREATE) { manageDatabase.loadClustersForOneTenant(null, null, null, kwMetadataUpdates.getTenantId()); - else if (entityType == EntityType.ENVIRONMENT + } else if (entityType == EntityType.ENVIRONMENT && operationType == MetadataOperationType.CREATE) { manageDatabase.loadEnvsForOneTenant(kwMetadataUpdates.getTenantId()); manageDatabase.loadEnvMapForOneTenant(kwMetadataUpdates.getTenantId()); diff --git a/src/main/java/io/aiven/klaw/service/DefaultDataService.java b/src/main/java/io/aiven/klaw/service/DefaultDataService.java index faf39f886f..7394ee1d37 100644 --- a/src/main/java/io/aiven/klaw/service/DefaultDataService.java +++ b/src/main/java/io/aiven/klaw/service/DefaultDataService.java @@ -247,38 +247,6 @@ public List createDefaultProperties(int tenantId, String mailId) { "Standard names of environments"); kwPropertiesList.add(kwProperties24); - // KwProperties kwProperties25 = new KwProperties("klaw.mail.transport.protocol", - // tenantId, MAIL_PROTOCOL,"Smtp Config Mail transport protocol"); - // kwPropertiesList.add(kwProperties25); - // - // KwProperties kwProperties26 = new KwProperties("klaw.mail.host", - // tenantId, MAIL_HOST,"Smtp Config Mail host"); - // kwPropertiesList.add(kwProperties26); - // - // KwProperties kwProperties27 = new KwProperties("klaw.mail.port", - // tenantId, MAIL_PORT,"Smtp Config Mail port"); - // kwPropertiesList.add(kwProperties27); - // - // KwProperties kwProperties28 = new KwProperties("klaw.mail.username", - // tenantId, MAIL_USERNAME,"Smtp Config Mail username"); - // kwPropertiesList.add(kwProperties28); - // - // KwProperties kwProperties29 = new KwProperties("klaw.mail.password", - // tenantId, MAIL_PASSWORD,"Smtp Config Mail password"); - // kwPropertiesList.add(kwProperties29); - // - // KwProperties kwProperties30 = new KwProperties("klaw.mail.smtp.auth", - // tenantId, MAIL_SMTP_AUTH,"Smtp Config Mail Smtp Auth true/false"); - // kwPropertiesList.add(kwProperties30); - // - // KwProperties kwProperties31 = new KwProperties("klaw.mail.smtp.starttls.enable", - // tenantId, MAIL_SMTP_TLS,"Smtp Config Mail Smtp TLS enable true/false"); - // kwPropertiesList.add(kwProperties31); - // - // KwProperties kwProperties32 = new KwProperties("klaw.mail.debug", - // tenantId, MAIL_DEBUG,"Smtp Config Mail debug"); - // kwPropertiesList.add(kwProperties32); - KwProperties kwProperties19 = new KwProperties( "klaw.mail.notifications.enable", diff --git a/src/main/java/io/aiven/klaw/service/EmailService.java b/src/main/java/io/aiven/klaw/service/EmailService.java index dd83b6626e..e92dcb3f0d 100644 --- a/src/main/java/io/aiven/klaw/service/EmailService.java +++ b/src/main/java/io/aiven/klaw/service/EmailService.java @@ -80,7 +80,9 @@ public void sendSimpleMessage( try { MimeMessage message = emailSender.createMimeMessage(); message.setRecipients(Message.RecipientType.TO, to); - if (cc != null) message.setRecipients(Message.RecipientType.CC, cc); + if (cc != null) { + message.setRecipients(Message.RecipientType.CC, cc); + } message.setSubject(subject); Address address = new InternetAddress(noReplyMailId); diff --git a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 48fc6f4634..f76be0041b 100644 --- a/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -76,7 +76,9 @@ public synchronized EnvModel getEnvDetails(String envSelected, String clusterTyp if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) { // tenant filtering - if (!getEnvsFromUserId().contains(envSelected)) return null; + if (!getEnvsFromUserId().contains(envSelected)) { + return null; + } } Env env = manageDatabase.getHandleDbRequests().selectEnvDetails(envSelected, tenantId); @@ -146,7 +148,9 @@ public UserInfoModel getUserDetails(String userId) { copyProperties(userInfo, userInfoModel); userInfoModel.setUserPassword("*******"); return userInfoModel; - } else return null; + } else { + return null; + } } public List getClusters(String typeOfCluster) { @@ -273,9 +277,11 @@ public List> getSyncEnvs() { hMap = new HashMap<>(); hMap.put("id", env.getId()); String baseClusterDropDownStr = " (Base Sync cluster)"; - if (Objects.equals(syncCluster, env.getId())) + if (Objects.equals(syncCluster, env.getId())) { hMap.put("name", env.getName() + baseClusterDropDownStr); - else hMap.put("name", env.getName()); + } else { + hMap.put("name", env.getName()); + } envsOnly.add(hMap); } @@ -318,9 +324,7 @@ public List getEnvsForRequestTopicsClusterFiltered() { public List getKafkaEnvs() { int tenantId = getUserDetails(getUserName()).getTenantId(); String orderOfEnvs = mailService.getEnvProperty(tenantId, "ORDER_OF_ENVS"); - List listEnvs = manageDatabase.getKafkaEnvList(tenantId); - List envModelList = getEnvModels(listEnvs, KafkaClustersType.KAFKA.value, tenantId); envModelList.forEach( envModel -> @@ -473,7 +477,9 @@ private List getEnvModels(List listEnvs, String clusterType, int .get(envModel.getClusterId()) .getClusterName()); envModelList.add(envModel); - } else log.error("Error : Environment/cluster not loaded :{}", listEnv); + } else { + log.error("Error : Environment/cluster not loaded :{}", listEnv); + } } return envModelList; } @@ -575,7 +581,9 @@ public List getSchemaRegEnvsStatus() { .get(oneEnv.getClusterId()) .getBootstrapServers(), tenantId); - else status = "NOT_KNOWN"; + else { + status = "NOT_KNOWN"; + } oneEnv.setEnvStatus(status); newListEnvs.add(oneEnv); } @@ -586,17 +594,21 @@ public List getSchemaRegEnvsStatus() { public ApiResponse addNewEnv(EnvModel newEnv) throws KlawException { log.info("addNewEnv {}", newEnv); int tenantId = getUserDetails(getUserName()).getTenantId(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) + if (commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } newEnv.setTenantId(tenantId); - if (newEnv.getClusterId() == null) + if (newEnv.getClusterId() == null) { return ApiResponse.builder().result("Please select a cluster.").build(); + } if (newEnv.getName().length() > 3 - && Objects.equals(newEnv.getType(), KafkaClustersType.KAFKA.value)) + && Objects.equals(newEnv.getType(), KafkaClustersType.KAFKA.value)) { newEnv.setName(newEnv.getName().substring(0, 3)); + } newEnv.setName(newEnv.getName().toUpperCase()); String envIdAlreadyExistsInDeleteStatus = ""; @@ -616,7 +628,9 @@ public ApiResponse addNewEnv(EnvModel newEnv) throws KlawException { if (updatedList.isPresent()) { int nextId = updatedList.get() + 1; newEnv.setId(String.valueOf(nextId)); - } else newEnv.setId("1"); + } else { + newEnv.setId("1"); + } // Same name per type (kafka, kafkaconnect) in tenant not posssible. List envActualList = manageDatabase.getHandleDbRequests().selectAllEnvs(tenantId); @@ -649,14 +663,17 @@ public ApiResponse addNewEnv(EnvModel newEnv) throws KlawException { && en.getTenantId().equals(newEnv.getTenantId()) && en.getEnvExists().equals("false")) .findFirst(); - if (envAlreadyExistsInDeleted.isPresent()) + if (envAlreadyExistsInDeleted.isPresent()) { envIdAlreadyExistsInDeleteStatus = envAlreadyExistsInDeleted.get().getId(); + } } } Env env = new Env(); copyProperties(newEnv, env); - if (!"".equals(envIdAlreadyExistsInDeleteStatus)) env.setId(envIdAlreadyExistsInDeleteStatus); + if (!"".equals(envIdAlreadyExistsInDeleteStatus)) { + env.setId(envIdAlreadyExistsInDeleteStatus); + } env.setEnvExists("true"); try { @@ -733,7 +750,9 @@ private boolean savePublicKey( if (pubKeyFileCreated) { return commonUtilsService.addPublicKeyToTrustStore( kwCluster.getClusterName().toUpperCase(), tenantId); - } else return false; + } else { + return false; + } } catch (Exception e) { log.error( tenantId + " tenantId. Error in adding cluster --" + kwClustersModel.getClusterName(), e); @@ -748,7 +767,9 @@ private boolean createPublicKeyFile(String clusterName, int tenantId, String pub try { clientCertFile = new File(clientCertsLocation + "/" + fileName); - if (clientCertFile.exists()) clientCertFile.delete(); + if (clientCertFile.exists()) { + clientCertFile.delete(); + } outputStream = new FileOutputStream(clientCertFile); outputStream.write(Base64.getDecoder().decode(publicKey)); @@ -762,7 +783,9 @@ private boolean createPublicKeyFile(String clusterName, int tenantId, String pub return false; } finally { try { - if (outputStream != null) outputStream.close(); + if (outputStream != null) { + outputStream.close(); + } } catch (Exception ex) { log.error("Error in closing the BufferedWriter ", ex); } @@ -948,18 +971,24 @@ public ApiResponse addTenantId(KwTenantModel kwTenantModel, boolean isExternal) kwTenants.setInTrial(kwTenantModel.isInTrialPhase() + ""); kwTenants.setContactPerson(kwTenantModel.getContactPerson()); kwTenants.setOrgName("Our Organization"); - if (isExternal) kwTenantModel.setActiveTenant(true); + if (isExternal) { + kwTenantModel.setActiveTenant(true); + } - if (kwTenantModel.isActiveTenant()) kwTenants.setIsActive("true"); - else kwTenants.setIsActive("false"); + if (kwTenantModel.isActiveTenant()) { + kwTenants.setIsActive("true"); + } else { + kwTenants.setIsActive("false"); + } - if ("saas".equals(kwInstallationType)) + if ("saas".equals(kwInstallationType)) { kwTenants.setLicenseExpiry( new Timestamp(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(DAYS_TRIAL_PERIOD))); - else + } else { kwTenants.setLicenseExpiry( new Timestamp( System.currentTimeMillis() + TimeUnit.DAYS.toMillis(DAYS_EXPIRY_DEFAULT_TENANT))); + } try { String addNewTenantStatus = manageDatabase.getHandleDbRequests().addNewTenant(kwTenants); @@ -1020,7 +1049,9 @@ public KwTenantModel getMyTenantInfo() { if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { kwTenantModel.setAuthorizedToDelete(false); - } else kwTenantModel.setAuthorizedToDelete(true); + } else { + kwTenantModel.setAuthorizedToDelete(true); + } } return kwTenantModel; } @@ -1204,7 +1235,9 @@ public Map getClusterInfoFromEnv(String envSelected, String clus if (commonUtilsService.isNotAuthorizedUser( getPrincipal(), PermissionType.ADD_EDIT_DELETE_ENVS)) { // tenant filtering - if (!getEnvsFromUserId().contains(envSelected)) return null; + if (!getEnvsFromUserId().contains(envSelected)) { + return null; + } } Env env = manageDatabase.getHandleDbRequests().selectEnvDetails(envSelected, tenantId); diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index b3d4cb1b68..f0bf80fb5d 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -262,7 +262,9 @@ private List> getPagedList(List t i++; } - if (innerList.size() > 0) newList.add(innerList); + if (innerList.size() > 0) { + newList.add(innerList); + } return newList; } @@ -270,14 +272,17 @@ private List> getPagedList(List t private void updateTeamNamesForDisplay(List topicListUpdated) { topicListUpdated.forEach( topicInfo -> { - if (topicInfo.getTeamName().length() > 9) + if (topicInfo.getTeamName().length() > 9) { topicInfo.setTeamName(topicInfo.getTeamName().substring(0, 8) + "..."); + } }); } private List getConnectorsPaginated( String env, String pageNo, String currentPage, String connectorNameSearch, String teamName) { - if (connectorNameSearch != null) connectorNameSearch = connectorNameSearch.trim(); + if (connectorNameSearch != null) { + connectorNameSearch = connectorNameSearch.trim(); + } int tenantId = commonUtilsService.getTenantId(getUserName()); HandleDbRequests handleDbRequests = manageDatabase.getHandleDbRequests(); @@ -344,7 +349,9 @@ private List getConnectorModelsList( int requestPageNo = Integer.parseInt(pageNo); List topicsListMap = null; - if (totalRecs > 0) topicsListMap = new ArrayList<>(); + if (totalRecs > 0) { + topicsListMap = new ArrayList<>(); + } int startVar = (requestPageNo - 1) * recsPerPage; int lastVar = (requestPageNo) * (recsPerPage); @@ -543,8 +550,9 @@ public ApiResponse approveConnectorRequests(String connectorId) throws KlawExcep } updateTopicReqStatus = dbHandle.addToSyncConnectors(allTopics); - if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) + if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) { updateTopicReqStatus = dbHandle.updateConnectorRequestStatus(connectorRequest, userDetails); + } } else { Env envSelected = manageDatabase @@ -638,8 +646,9 @@ public ApiResponse declineConnectorRequests(String connectorId, String reasonFor throws KlawException { log.info("declineConnectorRequests {} {}", connectorId, reasonForDecline); String userDetails = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -653,8 +662,9 @@ public ApiResponse declineConnectorRequests(String connectorId, String reasonFor // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (!allowedEnvIdList.contains(connectorRequest.getEnvironment())) + if (!allowedEnvIdList.contains(connectorRequest.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } try { String result = dbHandle.declineConnectorRequest(connectorRequest, userDetails); @@ -870,8 +880,11 @@ public ConnectorOverview getConnectorOverview(String connectorNamesearch) { int tenantId = commonUtilsService.getTenantId(getUserName()); - if (connectorNamesearch != null) connectorNamesearch = connectorNamesearch.trim(); - else return null; + if (connectorNamesearch != null) { + connectorNamesearch = connectorNamesearch.trim(); + } else { + return null; + } Integer loggedInUserTeam = getMyTeamId(userDetails); @@ -889,7 +902,9 @@ public ConnectorOverview getConnectorOverview(String connectorNamesearch) { if (connectors.size() == 0) { topicOverview.setConnectorExists(false); return topicOverview; - } else topicOverview.setConnectorExists(true); + } else { + topicOverview.setConnectorExists(true); + } String syncCluster; String[] reqTopicsEnvs; @@ -1122,7 +1137,9 @@ public ApiResponse saveConnectorDocumentation(KafkaConnectorModel topicInfo) { return ApiResponse.builder() .result(manageDatabase.getHandleDbRequests().updateConnectorDocumentation(topic)) .build(); - } else return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } else { + return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); + } } private List getConnectorRequestModels( @@ -1179,8 +1196,9 @@ private String updateApproverInfo( for (UserInfo userInfo : userList) { if (approverRoles.contains(userInfo.getRole()) - && !Objects.equals(requestor, userInfo.getUsername())) + && !Objects.equals(requestor, userInfo.getUsername())) { approvingInfo.append(userInfo.getUsername()).append(","); + } } return String.valueOf(approvingInfo); @@ -1236,11 +1254,12 @@ private List getConnectorRequestsFilteredForTenant( // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (createdTopicReqList != null) + if (createdTopicReqList != null) { createdTopicReqList = createdTopicReqList.stream() .filter(topicRequest -> allowedEnvIdList.contains(topicRequest.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); @@ -1253,11 +1272,12 @@ private List getFilteredConnectorsForTenant( // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (connectorsFromSOT != null) + if (connectorsFromSOT != null) { connectorsFromSOT = connectorsFromSOT.stream() .filter(connector -> allowedEnvIdList.contains(connector.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); diff --git a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java index 896ec98193..dabb0018f5 100644 --- a/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java @@ -269,7 +269,9 @@ private List handleConnectorDeletes( for (SyncConnectorUpdates updatedSyncTopic : updatedSyncTopics) { if ("REMOVE FROM KLAW".equals(updatedSyncTopic.getTeamSelected())) { updatedSyncTopicsDelete.add(Integer.parseInt(updatedSyncTopic.getSequence())); - } else updatedSyncTopicsUpdated.add(updatedSyncTopic); + } else { + updatedSyncTopicsUpdated.add(updatedSyncTopic); + } } // delete topic @@ -468,11 +470,12 @@ private List getFilteredConnectorsForTenant( // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (connectorsFromSOT != null) + if (connectorsFromSOT != null) { connectorsFromSOT = connectorsFromSOT.stream() .filter(connector -> allowedEnvIdList.contains(connector.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); diff --git a/src/main/java/io/aiven/klaw/service/MailUtils.java b/src/main/java/io/aiven/klaw/service/MailUtils.java index dc92420bfc..df481093ab 100644 --- a/src/main/java/io/aiven/klaw/service/MailUtils.java +++ b/src/main/java/io/aiven/klaw/service/MailUtils.java @@ -333,8 +333,11 @@ private void sendMail( String emailIdTeam; try { - if (registrationRequest) emailId = otherMailId; - else emailId = dbHandle.getUsersInfo(username).getMailid(); + if (registrationRequest) { + emailId = otherMailId; + } else { + emailId = dbHandle.getUsersInfo(username).getMailid(); + } try { emailIdTeam = dbHandle.selectAllTeamsOfUsers(username, tenantId).get(0).getTeammail(); @@ -346,7 +349,9 @@ private void sendMail( if (emailId != null) { emailService.sendSimpleMessage( emailId, emailIdTeam, subject, formattedStr, tenantId, loginUrl); - } else log.error("Email id not found. Notification not sent !!"); + } else { + log.error("Email id not found. Notification not sent !!"); + } } catch (Exception e) { log.error("Email id not found. Notification not sent !! ", e); } diff --git a/src/main/java/io/aiven/klaw/service/MetricsControllerService.java b/src/main/java/io/aiven/klaw/service/MetricsControllerService.java index 40824450f2..6b58703f01 100644 --- a/src/main/java/io/aiven/klaw/service/MetricsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/MetricsControllerService.java @@ -50,7 +50,9 @@ private Integer getMyTeamId(String userName) { fixedRateString = "${klaw.monitoring.metrics.collectinterval.ms:60000}", initialDelay = 60000) private void loadMetricsScheduler() { - if ("false".equals(enableMetrics)) return; + if ("false".equals(enableMetrics)) { + return; + } log.info("Scheduled job : Collect metrics"); diff --git a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java index 19e93b6293..38b822aaf1 100644 --- a/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java @@ -40,7 +40,9 @@ public List getRoles() { getPrincipal(), PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) return Arrays.asList( manageDatabase.getKwPropertyValue("klaw.adduser.roles", tenantId).split(",")); - else return new ArrayList<>(manageDatabase.getRolesPermissionsPerTenant(tenantId).keySet()); + else { + return new ArrayList<>(manageDatabase.getRolesPermissionsPerTenant(tenantId).keySet()); + } } catch (Exception e) { log.error("Exception:", e); return Arrays.asList( @@ -133,17 +135,23 @@ public ApiResponse updatePermissions(KwRolesPermissionsModel[] permissionsSet) tmpKwRolePermModel.setRoleId(permKey.substring(0, indexOfDelimiter)); tmpKwRolePermModel.setPermission(permKey.substring(indexOfDelimiter + 5)); - if ("true".equals(isPermEnabled)) kwRolesPermissionsAdd.add(tmpKwRolePermModel); - else if ("false".equals(isPermEnabled)) kwRolesPermissionsDelete.add(tmpKwRolePermModel); + if ("true".equals(isPermEnabled)) { + kwRolesPermissionsAdd.add(tmpKwRolePermModel); + } else if ("false".equals(isPermEnabled)) { + kwRolesPermissionsDelete.add(tmpKwRolePermModel); + } } - if (kwRolesPermissionsAdd.size() > 0) + if (kwRolesPermissionsAdd.size() > 0) { manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsAdd, "ADD"); - if (kwRolesPermissionsDelete.size() > 0) + } + if (kwRolesPermissionsDelete.size() > 0) { manageDatabase.getHandleDbRequests().updatePermissions(kwRolesPermissionsDelete, "DELETE"); + } - if (kwRolesPermissionsAdd.size() > 0 || kwRolesPermissionsDelete.size() > 0) + if (kwRolesPermissionsAdd.size() > 0 || kwRolesPermissionsDelete.size() > 0) { manageDatabase.loadRolesForAllTenants(); + } return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); } catch (Exception e) { log.error(e.getMessage()); diff --git a/src/main/java/io/aiven/klaw/service/SaasService.java b/src/main/java/io/aiven/klaw/service/SaasService.java index 28d44b4e7e..ac73768577 100644 --- a/src/main/java/io/aiven/klaw/service/SaasService.java +++ b/src/main/java/io/aiven/klaw/service/SaasService.java @@ -89,9 +89,9 @@ public Map approveUserSaas(RegisterUserInfoModel newUser) throws ApiResponse resultApproveUser = usersTeamsControllerService.approveNewUserRequests( newUser.getUsername(), false, tenantId, KwConstants.INFRATEAM); - if (resultApproveUser.getResult().contains(ApiResultStatus.SUCCESS.value)) + if (resultApproveUser.getResult().contains(ApiResultStatus.SUCCESS.value)) { updateStaticData(newUser, tenantId); - else { + } else { resultMap.put("error", "Something went wrong. Please try again."); return resultMap; } @@ -122,8 +122,9 @@ public ApiResponse registerUserSaas(RegisterSaasUserInfoModel newUser) throws Ex Map resultMap = new HashMap<>(); try { - if (handleValidations(newUser, tenantMap, resultMap)) + if (handleValidations(newUser, tenantMap, resultMap)) { return ApiResponse.builder().result(resultMap.get("result")).build(); + } RegisterUserInfoModel newUserTarget = new RegisterUserInfoModel(); copyProperties(newUser, newUserTarget); @@ -134,8 +135,9 @@ public ApiResponse registerUserSaas(RegisterSaasUserInfoModel newUser) throws Ex if (newUser.getTenantName() == null || newUser.getTenantName().equals("")) { // new user - if (createNewUserForActivation(resultMap, newUserTarget)) + if (createNewUserForActivation(resultMap, newUserTarget)) { return ApiResponse.builder().result(resultMap.get("error")).build(); + } } else if (!tenantMap.containsValue(newUser.getTenantName())) { resultMap.put("error", "Tenant does not exist."); return ApiResponse.builder() @@ -144,8 +146,9 @@ public ApiResponse registerUserSaas(RegisterSaasUserInfoModel newUser) throws Ex .build(); } else { // create user for existing tenant - if (createUserForExistingTenant(newUser, tenantMap, resultMap, newUserTarget)) + if (createUserForExistingTenant(newUser, tenantMap, resultMap, newUserTarget)) { return ApiResponse.builder().result(resultMap.get("error")).build(); + } } return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); diff --git a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java index ca0ace725b..e09d39dacc 100644 --- a/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java +++ b/src/main/java/io/aiven/klaw/service/SchemaRegstryControllerService.java @@ -57,14 +57,15 @@ public List getSchemaRequests( // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (schemaReqs != null) + if (schemaReqs != null) { schemaReqs = schemaReqs.stream() .filter(request -> allowedEnvIdList.contains(request.getEnvironment())) .collect(Collectors.toList()); + } // request status filtering - if (!"all".equals(requestsType) && EnumUtils.isValidEnum(RequestStatus.class, requestsType)) + if (!"all".equals(requestsType) && EnumUtils.isValidEnum(RequestStatus.class, requestsType)) { if (schemaReqs != null) { schemaReqs = schemaReqs.stream() @@ -72,6 +73,7 @@ public List getSchemaRequests( schemaRequest -> Objects.equals(schemaRequest.getTopicstatus(), requestsType)) .collect(Collectors.toList()); } + } Integer userTeamId = getMyTeamId(userDetails); List userList = @@ -114,8 +116,9 @@ private String updateApproverInfo( for (UserInfo userInfo : userList) { if (approverRoles.contains(userInfo.getRole()) - && !Objects.equals(requestor, userInfo.getUsername())) + && !Objects.equals(requestor, userInfo.getUsername())) { approvingInfo.append(userInfo.getUsername()).append(","); + } } return String.valueOf(approvingInfo); @@ -209,8 +212,9 @@ public ApiResponse execSchemaRequests(String avroSchemaId) throws KlawException List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) + if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } ResponseEntity response = clusterApiService.postSchema( @@ -236,7 +240,9 @@ public ApiResponse execSchemaRequests(String avroSchemaId) throws KlawException } else { String errStr = response.getBody().getResult(); - if (errStr.length() > 100) errStr = errStr.substring(0, 98) + "..."; + if (errStr.length() > 100) { + errStr = errStr.substring(0, 98) + "..."; + } return ApiResponse.builder().result("Failure in uploading schema. Error : " + errStr).build(); } } @@ -254,8 +260,9 @@ public ApiResponse execSchemaRequestsDecline(String avroSchemaId, String reasonF dbHandle.selectSchemaRequest(Integer.parseInt(avroSchemaId), tenantId); List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) + if (!allowedEnvIdList.contains(schemaRequest.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } try { String responseDb = dbHandle.updateSchemaRequestDecline(schemaRequest, userDetails); @@ -277,11 +284,12 @@ private List getFilteredTopicsForTenant(List topicsFromSOT) { // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (topicsFromSOT != null) + if (topicsFromSOT != null) { topicsFromSOT = topicsFromSOT.stream() .filter(topic -> allowedEnvIdList.contains(topic.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); diff --git a/src/main/java/io/aiven/klaw/service/ServerConfigService.java b/src/main/java/io/aiven/klaw/service/ServerConfigService.java index 96b8ea2a4c..6e75717c94 100644 --- a/src/main/java/io/aiven/klaw/service/ServerConfigService.java +++ b/src/main/java/io/aiven/klaw/service/ServerConfigService.java @@ -69,16 +69,19 @@ public void getAllProperties() { ServerConfigProperties props = new ServerConfigProperties(); props.setKey(key); - if (key.contains("password") || key.contains("license")) props.setValue("*******"); - else + if (key.contains("password") || key.contains("license")) { + props.setValue("*******"); + } else { props.setValue(WordUtils.wrap(propertySource.getProperty(key) + "", 125, "\n", true)); - + } if (!checkPropertyExists(listProps, key) && !key.toLowerCase().contains("path") && !key.contains("secretkey") && !key.contains("password") && !key.contains("username")) { - if (allowedKeys.stream().anyMatch(key::startsWith)) listProps.add(props); + if (allowedKeys.stream().anyMatch(key::startsWith)) { + listProps.add(props); + } } } } @@ -93,7 +96,9 @@ public List getAllProps() { private boolean checkPropertyExists(List props, String key) { for (ServerConfigProperties serverProps : props) { - if (Objects.equals(serverProps.getKey(), key)) return true; + if (Objects.equals(serverProps.getKey(), key)) { + return true; + } } return false; } @@ -144,11 +149,13 @@ public List> getAllEditableProps() { } } - if (tenantId != KwConstants.DEFAULT_TENANT_ID) + if (tenantId != KwConstants.DEFAULT_TENANT_ID) { return listMap.stream() .filter(item -> KwConstants.allowConfigForAdmins.contains(item.get("kwkey"))) .collect(Collectors.toList()); - else return listMap; + } else { + return listMap; + } } public ApiResponse updateKwCustomProperty(KwPropertiesModel kwPropertiesModel) @@ -219,14 +226,16 @@ private void updateEnvNameValues(TenantConfig dynamicObj, int tenantId) { KwTenantConfigModel tenant = dynamicObj.getTenantModel(); // syncClusterName update - if (tenant.getBaseSyncEnvironment() != null) + if (tenant.getBaseSyncEnvironment() != null) { tenant.setBaseSyncEnvironment( getEnvDetails(tenant.getBaseSyncEnvironment(), tenantId).getName()); + } // syncClusterKafkaConnectName update - if (tenant.getBaseSyncKafkaConnectCluster() != null) + if (tenant.getBaseSyncKafkaConnectCluster() != null) { tenant.setBaseSyncKafkaConnectCluster( getKafkaConnectEnvDetails(tenant.getBaseSyncKafkaConnectCluster(), tenantId).getName()); + } // kafka if (tenant.getOrderOfTopicPromotionEnvsList() != null) { @@ -248,8 +257,9 @@ private void updateEnvNameValues(TenantConfig dynamicObj, int tenantId) { .getOrderOfConnectorsPromotionEnvsList() .forEach( a -> { - if (getKafkaConnectEnvDetails(a, tenantId) != null) + if (getKafkaConnectEnvDetails(a, tenantId) != null) { tmpOrderList1.add(getKafkaConnectEnvDetails(a, tenantId).getName()); + } }); tenant.setOrderOfConnectorsPromotionEnvsList(tmpOrderList1); } @@ -261,8 +271,9 @@ private void updateEnvNameValues(TenantConfig dynamicObj, int tenantId) { .getRequestTopicsEnvironmentsList() .forEach( a -> { - if (getEnvDetails(a, tenantId) != null) + if (getEnvDetails(a, tenantId) != null) { tmpReqTopicList.add(getEnvDetails(a, tenantId).getName()); + } }); tenant.setRequestTopicsEnvironmentsList(tmpReqTopicList); } @@ -274,8 +285,9 @@ private void updateEnvNameValues(TenantConfig dynamicObj, int tenantId) { .getRequestConnectorsEnvironmentsList() .forEach( a -> { - if (getKafkaConnectEnvDetails(a, tenantId) != null) + if (getKafkaConnectEnvDetails(a, tenantId) != null) { tmpReqTopicList1.add(getKafkaConnectEnvDetails(a, tenantId).getName()); + } }); tenant.setRequestConnectorsEnvironmentsList(tmpReqTopicList1); } @@ -287,20 +299,22 @@ private void updateEnvIdValues(TenantConfig dynamicObj) { KwTenantConfigModel tenantModel = dynamicObj.getTenantModel(); // syncClusterName update - if (tenantModel.getBaseSyncEnvironment() != null) + if (tenantModel.getBaseSyncEnvironment() != null) { tenantModel.setBaseSyncEnvironment( getEnvDetailsFromName( tenantModel.getBaseSyncEnvironment(), getTenantIdFromName(tenantModel.getTenantName())) .getId()); + } // syncClusterKafkaConnectName update - if (tenantModel.getBaseSyncKafkaConnectCluster() != null) + if (tenantModel.getBaseSyncKafkaConnectCluster() != null) { tenantModel.setBaseSyncKafkaConnectCluster( getKafkaConnectEnvDetailsFromName( tenantModel.getBaseSyncKafkaConnectCluster(), getTenantIdFromName(tenantModel.getTenantName())) .getId()); + } // kafka if (tenantModel.getOrderOfTopicPromotionEnvsList() != null) { @@ -391,7 +405,9 @@ private boolean validateTenantConfig(TenantConfig dynamicObj, int tenantId) { // orderOfenvs check if (tenantModel.getOrderOfTopicPromotionEnvsList() != null) { for (String orderOfTopicPromotionEnv : tenantModel.getOrderOfTopicPromotionEnvsList()) { - if (!envListStr.contains(orderOfTopicPromotionEnv)) return false; + if (!envListStr.contains(orderOfTopicPromotionEnv)) { + return false; + } } } @@ -399,21 +415,27 @@ private boolean validateTenantConfig(TenantConfig dynamicObj, int tenantId) { if (tenantModel.getOrderOfConnectorsPromotionEnvsList() != null) { for (String orderOfConnectorsPromotionEnv : tenantModel.getOrderOfConnectorsPromotionEnvsList()) { - if (!envListKafkaConnectStr.contains(orderOfConnectorsPromotionEnv)) return false; + if (!envListKafkaConnectStr.contains(orderOfConnectorsPromotionEnv)) { + return false; + } } } // requestTopics check if (tenantModel.getRequestTopicsEnvironmentsList() != null) { for (String requestTopicEnvs : tenantModel.getRequestTopicsEnvironmentsList()) { - if (!envListStr.contains(requestTopicEnvs)) return false; + if (!envListStr.contains(requestTopicEnvs)) { + return false; + } } } // requestConnectors check if (tenantModel.getRequestConnectorsEnvironmentsList() != null) { for (String requestConnectorEnvs : tenantModel.getRequestConnectorsEnvironmentsList()) { - if (!envListKafkaConnectStr.contains(requestConnectorEnvs)) return false; + if (!envListKafkaConnectStr.contains(requestConnectorEnvs)) { + return false; + } } } } @@ -470,8 +492,11 @@ public Map testClusterApiConnection(String clusterApiUrl) { Map hashMap = new HashMap<>(); int tenantId = commonUtilsService.getTenantId(getUserName()); String clusterApiStatus = clusterApiService.getClusterApiStatus(clusterApiUrl, true, tenantId); - if ("ONLINE".equals(clusterApiStatus)) clusterApiStatus = "successful."; - else clusterApiStatus = "failure."; + if ("ONLINE".equals(clusterApiStatus)) { + clusterApiStatus = "successful."; + } else { + clusterApiStatus = "failure."; + } hashMap.put("result", clusterApiStatus); return hashMap; } diff --git a/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/src/main/java/io/aiven/klaw/service/TopicControllerService.java index 56fef84c93..85b3106ad2 100644 --- a/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -451,14 +451,14 @@ public List getTopicRequests( .sorted(Collections.reverseOrder(Comparator.comparing(TopicRequest::getRequesttime))) .collect(Collectors.toList()); - if (!"all".equals(requestsType) && EnumUtils.isValidEnum(RequestStatus.class, requestsType)) + if (!"all".equals(requestsType) && EnumUtils.isValidEnum(RequestStatus.class, requestsType)) { topicReqs = topicReqs.stream() .filter(topicRequest -> Objects.equals(topicRequest.getTopicstatus(), requestsType)) .collect(Collectors.toList()); + } topicReqs = getTopicRequestsPaged(topicReqs, pageNo, currentPage); - return getTopicRequestModels(topicReqs, true); } @@ -576,11 +576,12 @@ public List getCreatedTopicRequests( manageDatabase .getHandleDbRequests() .getCreatedTopicRequests(userDetails, requestsType, false, tenantId); - } else + } else { createdTopicReqList = manageDatabase .getHandleDbRequests() .getCreatedTopicRequests(userDetails, requestsType, true, tenantId); + } createdTopicReqList = getTopicRequestsFilteredForTenant(createdTopicReqList); createdTopicReqList = getTopicRequestsPaged(createdTopicReqList, pageNo, currentPage); @@ -632,13 +633,14 @@ private List getTopicRequestModels( manageDatabase.getTeamNameFromTeamId(tenantId, topics.get(0).getTeamId()), approverRoles, topicRequestModel.getRequestor())); - } else + } else { topicRequestModel.setApprovingTeamDetails( updateApproverInfo( userList, manageDatabase.getTeamNameFromTeamId(tenantId, userTeamId), approverRoles, topicRequestModel.getRequestor())); + } } } @@ -653,8 +655,9 @@ private String updateApproverInfo( for (UserInfo userInfo : userList) { if (approverRoles.contains(userInfo.getRole()) - && !Objects.equals(requestor, userInfo.getUsername())) + && !Objects.equals(requestor, userInfo.getUsername())) { approvingInfo.append(userInfo.getUsername()).append(","); + } } return String.valueOf(approvingInfo); @@ -720,8 +723,9 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { } updateTopicReqStatus = dbHandle.addToSynctopics(allTopics); - if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) + if (ApiResultStatus.SUCCESS.value.equals(updateTopicReqStatus)) { updateTopicReqStatus = dbHandle.updateTopicRequestStatus(topicRequest, userDetails); + } } else { ResponseEntity response = clusterApiService.approveTopicRequests( @@ -791,8 +795,9 @@ public ApiResponse declineTopicRequests(String topicId, String reasonForDecline) throws KlawException { log.info("declineTopicRequests {} {}", topicId, reasonForDecline); String userDetails = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); TopicRequest topicRequest = @@ -805,8 +810,9 @@ public ApiResponse declineTopicRequests(String topicId, String reasonForDecline) // tenant filtering List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) + if (!allowedEnvIdList.contains(topicRequest.getEnvironment())) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } try { String result = dbHandle.declineTopicRequest(topicRequest, userDetails); @@ -837,8 +843,6 @@ public List getAllTopics(boolean isMyTeamTopics) { if (isMyTeamTopics) { Integer userTeamId = getMyTeamId(getUserName()); - // String teamId = - // manageDatabase.getHandleDbRequests().getUsersInfo(getUserName()).getTeam(); topicsFromSOT = topicsFromSOT.stream() .filter(topic -> Objects.equals(topic.getTeamId(), userTeamId)) @@ -857,7 +861,6 @@ public ApiResponse saveTopicDocumentation(TopicInfo topicInfo) throws KlawExcept topic.setTopicid(topicInfo.getTopicid()); topic.setDocumentation(topicInfo.getDocumentation()); - HandleDbRequests handleDb = manageDatabase.getHandleDbRequests(); int tenantId = commonUtilsService.getTenantId(getUserName()); List topicsSearchList = manageDatabase.getHandleDbRequests().getTopicTeam(topicInfo.getTopicName(), tenantId); @@ -1129,7 +1132,9 @@ private List> getPagedList(List topicsList) { i++; } - if (innerList.size() > 0) newList.add(innerList); + if (innerList.size() > 0) { + newList.add(innerList); + } return newList; } @@ -1168,7 +1173,9 @@ private List getTopicInfoList( int requestPageNo = Integer.parseInt(pageNo); List topicsListMap = null; - if (totalRecs > 0) topicsListMap = new ArrayList<>(); + if (totalRecs > 0) { + topicsListMap = new ArrayList<>(); + } int startVar = (requestPageNo - 1) * recsPerPage; int lastVar = (requestPageNo) * (recsPerPage); @@ -1252,11 +1259,12 @@ private List getFilteredTopicsForTenant(List topicsFromSOT) { // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (topicsFromSOT != null) + if (topicsFromSOT != null) { topicsFromSOT = topicsFromSOT.stream() .filter(topic -> allowedEnvIdList.contains(topic.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); @@ -1269,11 +1277,12 @@ private List getTopicRequestsFilteredForTenant( // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (createdTopicReqList != null) + if (createdTopicReqList != null) { createdTopicReqList = createdTopicReqList.stream() .filter(topicRequest -> allowedEnvIdList.contains(topicRequest.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); diff --git a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index dfd61744c0..97d04cb25f 100644 --- a/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -140,9 +140,10 @@ public Map getReconTopics( }); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (!"-1".equals(pageNo)) // scheduler call - topicRequestModelList = + if (!"-1".equals(pageNo)) { // scheduler call + topicRequestModelList = getPagedTopicReqModels(pageNo, currentPage, topicRequestModelList, tenantId); + } syncTopicsObjectMap.put("resultSet", topicRequestModelList); syncTopicsObjectMap.put("allTopicsCount", allTopicsCount); @@ -164,8 +165,9 @@ public Map getSyncTopics( log.info("getSyncTopics {} {} {}", env, pageNo, topicNameSearch); if (!"-1".equals(pageNo)) { // ignore check for scheduler - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { return null; + } } List> topicFilteredList = getTopicsFromKafkaCluster(env, topicNameSearch); @@ -177,7 +179,6 @@ public Map getSyncTopics( .collect(Collectors.toList()); List deletedTopicsFromClusterList = new ArrayList<>(); - List sizeOfTopics = new ArrayList<>(); if (isReconciliation) { @@ -223,17 +224,19 @@ private List getSyncTopicList( List teamList = new ArrayList<>(); teamList = tenantFilterTeams(teamList); - if (!isBulkOption) + if (!isBulkOption) { updateClusterDeletedTopicsList( topicsList, deletedTopicsFromClusterList, topicsFromSOT, teamList, tenantId); + } List topicsListMap = new ArrayList<>(); for (int i = 0; i < topicsList.size(); i++) { counterInc = counterIncrement(); TopicRequest mp = new TopicRequest(); - if (createTopicRequest(topicsList, topicsFromSOT, teamList, i, counterInc, mp, tenantId)) + if (createTopicRequest(topicsList, topicsFromSOT, teamList, i, counterInc, mp, tenantId)) { topicsListMap.add(mp); + } } // topics which exist on cluster and not in kw, with no recon option. List topicRequestModelList = @@ -297,16 +300,20 @@ private List getSyncTopicListRecon( teamList = tenantFilterTeams(teamList); int counterInc; - if (!isBulkOption) + if (!isBulkOption) { updateClusterDeletedTopicsList( clusterTopicsList, deletedTopicsFromClusterList, topicsFromSOT, teamList, tenantId); + } for (int i = 0; i < clusterTopicsList.size(); i++) { counterInc = counterIncrement(); TopicRequest mp = new TopicRequest(); if (createTopicRequest( - clusterTopicsList, topicsFromSOT, teamList, i, counterInc, mp, tenantId)) - if (mp.getTeamId().equals(0) || mp.getTeamId() == null) topicsListMap.add(mp); + clusterTopicsList, topicsFromSOT, teamList, i, counterInc, mp, tenantId)) { + if (mp.getTeamId().equals(0) || mp.getTeamId() == null) { + topicsListMap.add(mp); + } + } } // topics which exist in cluster and not in kw. @@ -345,13 +352,14 @@ private List getTopicRequestModels( manageDatabase.getTeamNameFromTeamId(tenantId, topics.get(0).getTeamId()), approverRoles, topicRequestModel.getRequestor())); - } else + } else { topicRequestModel.setApprovingTeamDetails( updateApproverInfo( userList, manageDatabase.getTeamNameFromTeamId(tenantId, userTeamId), approverRoles, topicRequestModel.getRequestor())); + } } } @@ -366,8 +374,9 @@ private String updateApproverInfo( for (UserInfo userInfo : userList) { if (approverRoles.contains(userInfo.getRole()) - && !Objects.equals(requestor, userInfo.getUsername())) + && !Objects.equals(requestor, userInfo.getUsername())) { approvingInfo.append(userInfo.getUsername()).append(","); + } } return String.valueOf(approvingInfo); @@ -399,18 +408,21 @@ private boolean createTopicRequest( .filter(a -> Objects.equals(a.getTopicname(), tmpTopicName)) .findFirst(); - if (teamUpdatedFirst.isPresent()) + if (teamUpdatedFirst.isPresent()) { teamUpdated = manageDatabase.getTeamNameFromTeamId(tenantId, teamUpdatedFirst.get().getTeamId()); + } } catch (Exception e) { log.error("Error from getSyncTopicList ", e); } if (teamUpdated != null && !teamUpdated.equals("undefined")) { mp.setPossibleTeams(teamList); - if (teamList.contains(teamUpdated)) + if (teamList.contains(teamUpdated)) { mp.setTeamId(manageDatabase.getTeamIdFromTeamName(tenantId, teamUpdated)); - else return false; // belongs to different tenant + } else { + return false; // belongs to different tenant + } } else { mp.setPossibleTeams(teamList); mp.setTeamId(0); @@ -453,8 +465,10 @@ private void updateClusterDeletedTopicsList( topicRequestModel.setRemarks("DELETED"); // tenant teams - if (teamList.contains(manageDatabase.getTeamNameFromTeamId(tenantId, topicObj.getTeamId()))) + if (teamList.contains( + manageDatabase.getTeamNameFromTeamId(tenantId, topicObj.getTeamId()))) { sotTopics.put(topicObj.getTopicname(), topicRequestModel); + } } List deletedTopicsFromClusterListTmp = @@ -478,9 +492,7 @@ private List tenantFilterTeams(List teamList) { getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { // tenant filtering int tenantId = commonUtilsService.getTenantId(getUserName()); - List teams = manageDatabase.getHandleDbRequests().selectAllTeams(tenantId); - List teamListUpdated = new ArrayList<>(); for (Team teamsItem : teams) { teamListUpdated.add(teamsItem.getTeamname()); @@ -553,17 +565,20 @@ private void approveSyncBackTopics( if (!Objects.equals( Objects.requireNonNull(response.getBody()).getResult(), ApiResultStatus.SUCCESS.value)) { log.error("Error in creating topic {} {}", topicFound, response.getBody()); - if (Objects.requireNonNull(response.getBody()).getResult().contains("TopicExistsException")) + if (Objects.requireNonNull(response.getBody()) + .getResult() + .contains("TopicExistsException")) { logUpdateSyncBackTopics.add( "Error in Topic creation. Topic:" + topicFound.getTopicname() + " already exists. TopicExistsException"); - else + } else { logUpdateSyncBackTopics.add( "Error in Topic creation. Topic:" + topicFound.getTopicname() + " " + response.getBody()); + } } else { logUpdateSyncBackTopics.add("Topic created " + topicFound.getTopicname()); if (!Objects.equals(syncBackTopics.getSourceEnv(), syncBackTopics.getTargetEnv())) @@ -619,7 +634,9 @@ public List getTopicsRowView( getTopicsPaginated( env, pageNo, currentPage, topicNameSearch, teamName, topicType, tenantId); - if (topicListUpdated != null && topicListUpdated.size() > 0) return topicListUpdated; + if (topicListUpdated != null && topicListUpdated.size() > 0) { + return topicListUpdated; + } return new ArrayList<>(); } @@ -833,11 +850,6 @@ public ApiResponse updateSyncTopicsBulk(SyncTopicsBulk syncTopicsBulk) throws Kl return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } - // List resultStatus = new ArrayList<>(); - // resultStatus.add(ApiResultStatus.SUCCESS.value); - // - // resultMap.put("result", resultStatus); - if ("SELECTED_TOPICS".equals(syncTopicsBulk.getTypeOfSync())) { Object[] topicMap = syncTopicsBulk.getTopicDetails(); Map> hashMap = new HashMap<>(); @@ -894,7 +906,9 @@ private void invokeUpdateSyncAllTopics( private List> getTopicsFromKafkaCluster(String env, String topicNameSearch) throws Exception { - if (topicNameSearch != null) topicNameSearch = topicNameSearch.trim(); + if (topicNameSearch != null) { + topicNameSearch = topicNameSearch.trim(); + } int tenantId = commonUtilsService.getTenantId(getUserName()); Env envSelected = getEnvDetails(env); String bootstrapHost = @@ -1018,8 +1032,9 @@ public ApiResponse updateSyncTopics(List updatedSyncTopics) } else if (!Objects.equals(syncCluster, topicUpdate.getEnvSelected())) { erroredTopicsExist.append(topicUpdate.getTopicName()).append(" "); if (checkInPromotionOrder( - topicUpdate.getTopicName(), topicUpdate.getEnvSelected(), orderOfEnvs)) + topicUpdate.getTopicName(), topicUpdate.getEnvSelected(), orderOfEnvs)) { topicsDontExistInMainCluster = true; + } } boolean topicAdded = false; @@ -1145,7 +1160,9 @@ private List handleTopicDeletes( for (SyncTopicUpdates updatedSyncTopic : updatedSyncTopics) { if ("REMOVE FROM KLAW".equals(updatedSyncTopic.getTeamSelected())) { updatedSyncTopicsDelete.add(Integer.parseInt(updatedSyncTopic.getSequence())); - } else updatedSyncTopicsUpdated.add(updatedSyncTopic); + } else { + updatedSyncTopicsUpdated.add(updatedSyncTopic); + } } // delete topic @@ -1196,11 +1213,12 @@ private List getFilteredTopicsForTenant(List topicsFromSOT) { // tenant filtering try { List allowedEnvIdList = getEnvsFromUserId(getUserName()); - if (topicsFromSOT != null) + if (topicsFromSOT != null) { topicsFromSOT = topicsFromSOT.stream() .filter(topic -> allowedEnvIdList.contains(topic.getEnvironment())) .collect(Collectors.toList()); + } } catch (Exception e) { log.error("No environments/clusters found.", e); return new ArrayList<>(); diff --git a/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java b/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java index 9710114dbf..e61dc8e8eb 100644 --- a/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java @@ -29,8 +29,11 @@ public class UiConfigControllerService { public Map getDbAuth() { Map dbMap = new HashMap<>(); - if ("db".equals(authenticationType)) dbMap.put("dbauth", "true"); - else dbMap.put("dbauth", "false"); + if ("db".equals(authenticationType)) { + dbMap.put("dbauth", "true"); + } else { + dbMap.put("dbauth", "false"); + } return dbMap; } @@ -45,16 +48,17 @@ public List showActivityLog(String env, String pageNo, String curre List origActivityList; int tenantId = commonUtilsService.getTenantId(getUserName()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) + if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { origActivityList = manageDatabase .getHandleDbRequests() .selectActivityLog(userName, env, false, tenantId); // only your team reqs - else + } else { origActivityList = manageDatabase .getHandleDbRequests() .selectActivityLog(userName, env, true, tenantId); // all teams reqs + } return getActivityLogsPaginated(pageNo, origActivityList, currentPage, tenantId); } @@ -103,21 +107,22 @@ private List getActivityLogsPaginated( public String getEnvName(String envId, String activityName, int tenantId) { Optional envFound; - if ("SchemaRequest".equals(activityName)) + if ("SchemaRequest".equals(activityName)) { envFound = manageDatabase.getSchemaRegEnvList(tenantId).stream() .filter(env -> Objects.equals(env.getId(), envId)) .findFirst(); - else if ("ConnectorRequest".equals(activityName)) + } else if ("ConnectorRequest".equals(activityName)) { envFound = manageDatabase.getKafkaConnectEnvList(tenantId).stream() .filter(env -> Objects.equals(env.getId(), envId)) .findFirst(); - else + } else { envFound = manageDatabase.getKafkaEnvList(tenantId).stream() .filter(env -> Objects.equals(env.getId(), envId)) .findFirst(); + } return envFound.map(Env::getName).orElse(null); } @@ -136,14 +141,6 @@ public ApiResponse sendMessageToAdmin(String contactFormSubject, String contactF public List getRequestTypeStatuses() { return manageDatabase.getRequestStatusList(); - // if(userType.equals("USER")) - // return manageDatabase.getRequestStatusList(); - // else { - // ArrayList apprvrList = new - // ArrayList<>(manageDatabase.getRequestStatusList()); - // apprvrList.remove("deleted"); - // return apprvrList; - // } } private Object getPrincipal() { diff --git a/src/main/java/io/aiven/klaw/service/UiControllerLoginService.java b/src/main/java/io/aiven/klaw/service/UiControllerLoginService.java index 57fba75b24..8390e4d5ec 100644 --- a/src/main/java/io/aiven/klaw/service/UiControllerLoginService.java +++ b/src/main/java/io/aiven/klaw/service/UiControllerLoginService.java @@ -83,12 +83,16 @@ public String getReturningPage(String uri) { || uri.contains("registrationReview") || uri.contains("userActivation") || "forgotPassword.html".equals(uri) - || "newADUser.html".equals(uri)) return indexPage; + || "newADUser.html".equals(uri)) { + return indexPage; + } return uri; } - if ("db".equals(authenticationType) && "saas".equals(kwInstallationType)) + if ("db".equals(authenticationType) && "saas".equals(kwInstallationType)) { return defaultPageSaas; - else return defaultPage; + } else { + return defaultPage; + } } catch (Exception e) { log.error("Exception:", e); if ("login.html".equals(uri) @@ -102,9 +106,11 @@ public String getReturningPage(String uri) { || "terms.html".equals(uri) || "feedback.html".equals(uri)) return uri; - if ("db".equals(authenticationType) && "saas".equals(kwInstallationType)) + if ("db".equals(authenticationType) && "saas".equals(kwInstallationType)) { return defaultPageSaas; - else return defaultPage; + } else { + return defaultPage; + } } } @@ -129,8 +135,11 @@ public String checkAnonymousLogin( authorizedClientService.loadAuthorizedClient( ssoClientRegistrationId, (String) defaultOAuth2User.getAttributes().get("preferred_username")); - if (client == null) return oauthLoginPage; - else return uri; + if (client == null) { + return oauthLoginPage; + } else { + return uri; + } } catch (Exception e) { log.error("Exception:", e); return oauthLoginPage; @@ -152,12 +161,17 @@ public String checkAuth(String uri, HttpServletRequest request, HttpServletRespo && commonUtilsService.getTenantId(userDetails.getUsername()) == KwConstants.DEFAULT_TENANT_ID) { return getReturningPage(uri); - } else uri = "index"; + } else { + uri = "index"; + } } if ("true".equals(ssoEnabled)) { - if (uri.contains("register") || uri.equals("registrationReview.html")) return uri; - else return checkAnonymousLogin(uri, request, response); + if (uri.contains("register") || uri.equals("registrationReview.html")) { + return uri; + } else { + return checkAnonymousLogin(uri, request, response); + } } else { return getReturningPage(uri); } @@ -170,9 +184,11 @@ public String registerStagingUser(String userName, Object fullName) { manageDatabase.getHandleDbRequests().getRegistrationId(userName); if (existingRegistrationId != null) { - if ("PENDING_ACTIVATION".equals(existingRegistrationId)) + if ("PENDING_ACTIVATION".equals(existingRegistrationId)) { return "redirect:" + "registrationReview"; - else return "redirect:" + "register?userRegistrationId=" + existingRegistrationId; + } else { + return "redirect:" + "register?userRegistrationId=" + existingRegistrationId; + } } else { String randomId = UUID.randomUUID().toString(); diff --git a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index c29db67629..9f10601426 100644 --- a/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -81,7 +81,9 @@ public UserInfoModel getUserInfoDetails(String userId) { manageDatabase.getTeamNameFromTeamId(userInfo.getTenantId(), userInfoModel.getTeamId())); userInfoModel.setUserPassword("*******"); return userInfoModel; - } else return null; + } else { + return null; + } } public ApiResponse updateProfile(UserInfoModel updateUserObj) throws KlawException { @@ -102,8 +104,10 @@ public ApiResponse updateProfile(UserInfoModel updateUserObj) throws KlawExcepti public ApiResponse updateUser(UserInfoModel newUser) throws KlawException { log.info("updateUser {}", newUser.getUsername()); - if (commonUtilsService.isNotAuthorizedUser(getUserName(), PermissionType.ADD_EDIT_DELETE_USERS)) + if (commonUtilsService.isNotAuthorizedUser( + getUserName(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } UserInfo existingUserInfo = manageDatabase.getHandleDbRequests().getUsersInfo(newUser.getUsername()); @@ -124,7 +128,9 @@ public ApiResponse updateUser(UserInfoModel newUser) throws KlawException { String existingPwd; if ("*******".equals(pwdUpdated) && "db".equals(authenticationType)) { existingPwd = existingUserInfo.getPwd(); - if (!"".equals(existingPwd)) newUser.setUserPassword(decodePwd(existingPwd)); + if (!"".equals(existingPwd)) { + newUser.setUserPassword(decodePwd(existingPwd)); + } } try { @@ -170,8 +176,9 @@ public TeamModel getTeamDetails(Integer teamId, String tenantName) { if (teamDao != null) { TeamModel teamModel = new TeamModel(); copyProperties(teamDao, teamModel); - if (teamDao.getRequestTopicsEnvs() != null) + if (teamDao.getRequestTopicsEnvs() != null) { teamModel.setEnvList(Arrays.asList(teamDao.getRequestTopicsEnvs().split("\\s*,\\s*"))); + } teamModel.setTenantName(tenantName); teamModel.setTenantId(getTenantId(tenantName)); return teamModel; @@ -191,7 +198,9 @@ String generateRandomWord(int len) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi" + "jklmnopqrstuvwxyz"; Random rnd = new Random(); StringBuilder sb = new StringBuilder(len); - for (int i = 0; i < len; i++) sb.append(chars.charAt(rnd.nextInt(chars.length()))); + for (int i = 0; i < len; i++) { + sb.append(chars.charAt(rnd.nextInt(chars.length()))); + } return sb.toString(); } @@ -202,8 +211,9 @@ public Map resetPassword(String username) { userMap.put("passwordSent", "false"); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); - if (userInfoModel == null) userMap.put("userFound", "false"); - else { + if (userInfoModel == null) { + userMap.put("userFound", "false"); + } else { userMap.put("userFound", "true"); String newGeneratedPwd = generateRandomWord(15); PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); @@ -235,9 +245,9 @@ private List getTeamModels(List teams) { for (Team team : teams) { teamModel = new TeamModel(); copyProperties(team, teamModel); - if (team.getRequestTopicsEnvs() == null || team.getRequestTopicsEnvs().length() == 0) + if (team.getRequestTopicsEnvs() == null || team.getRequestTopicsEnvs().length() == 0) { teamModel.setEnvList(allList); - else { + } else { teamModel.setEnvList(Arrays.asList(team.getRequestTopicsEnvs().split("\\s*,\\s*"))); tmpConvertedList = new ArrayList<>(); try { @@ -309,7 +319,9 @@ public List getAllTeamsSUOnly() { teams.add(myTeamName); for (TeamModel team : teamsList) { - if (!team.getTeamname().equals(myTeamName)) teams.add(team.getTeamname()); + if (!team.getTeamname().equals(myTeamName)) { + teams.add(team.getTeamname()); + } } return teams; @@ -320,8 +332,9 @@ public ApiResponse deleteTeam(Integer teamId) throws KlawException { String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } int tenantId = commonUtilsService.getTenantId(getUserName()); if (manageDatabase.getHandleDbRequests().findAllComponentsCountForTeam(teamId, tenantId) > 0) { @@ -331,8 +344,9 @@ public ApiResponse deleteTeam(Integer teamId) throws KlawException { } // own team cannot be deleted - if (Objects.equals(getMyTeamId(userDetails), teamId)) + if (Objects.equals(getMyTeamId(userDetails), teamId)) { return ApiResponse.builder().result("Team cannot be deleted.").build(); + } try { String result = @@ -356,8 +370,9 @@ public ApiResponse deleteUser(String userId, boolean isExternal) throws KlawExce String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } UserInfo existingUserInfo = manageDatabase.getHandleDbRequests().getUsersInfo(userId); List permissions = @@ -365,14 +380,16 @@ public ApiResponse deleteUser(String userId, boolean isExternal) throws KlawExce .getRolesPermissionsPerTenant(commonUtilsService.getTenantId(getUserName())) .get(existingUserInfo.getRole()); if (permissions != null - && permissions.contains(PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES.name())) + && permissions.contains(PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES.name())) { return ApiResponse.builder() .result("Not Authorized. Cannot delete a user with SUPERADMIN access.") .build(); + } String envAddResult = "{\"result\":\"User cannot be deleted\"}"; - if (Objects.equals(userDetails, userId) && isExternal) + if (Objects.equals(userDetails, userId) && isExternal) { return ApiResponse.builder().result(envAddResult).build(); + } try { inMemoryUserDetailsManager.deleteUser(userId); @@ -390,8 +407,11 @@ private String encodePwd(String pwd) { } private String decodePwd(String pwd) { - if (pwd != null) return getJasyptEncryptor().decrypt(pwd); - else return ""; + if (pwd != null) { + return getJasyptEncryptor().decrypt(pwd); + } else { + return ""; + } } private BasicTextEncryptor getJasyptEncryptor() { @@ -422,8 +442,11 @@ public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws int tenantId; if (isExternal) { - if (newUser.getTenantId() == 0) tenantId = commonUtilsService.getTenantId(getUserName()); - else tenantId = newUser.getTenantId(); + if (newUser.getTenantId() == 0) { + tenantId = commonUtilsService.getTenantId(getUserName()); + } else { + tenantId = newUser.getTenantId(); + } newUser.setTenantId(tenantId); @@ -438,7 +461,9 @@ public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); } - if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) newUser.setRole("NA"); + if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) { + newUser.setRole("NA"); + } try { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); @@ -462,18 +487,19 @@ public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws // log.info("pwd : "+decodePwd(newUser.getUserPassword())); if (isExternal) { - if ("".equals(newUser.getUserPassword())) + if ("".equals(newUser.getUserPassword())) { mailService.sendMail( newUser.getUsername(), newUser.getUserPassword(), dbHandle, commonUtilsService.getLoginUrl()); - else + } else { mailService.sendMail( newUser.getUsername(), decodePwd(newUser.getUserPassword()), dbHandle, commonUtilsService.getLoginUrl()); + } } return ApiResponse.builder().result(result).build(); } catch (Exception e) { @@ -492,14 +518,17 @@ public ApiResponse addNewTeam(TeamModel newTeam, boolean isExternal) throws Klaw if (isExternal && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } int tenantId; if (isExternal) { tenantId = commonUtilsService.getTenantId(getUserName()); newTeam.setTenantId(tenantId); - } else tenantId = newTeam.getTenantId(); + } else { + tenantId = newTeam.getTenantId(); + } Team team = new Team(); copyProperties(newTeam, team); @@ -525,8 +554,9 @@ public ApiResponse updateTeam(TeamModel updatedTeam) throws KlawException { log.info("updateTeam {}", updatedTeam); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } int tenantId = commonUtilsService.getTenantId(getUserName()); Team team = new Team(); @@ -598,8 +628,12 @@ public List showUsers(String teamName, String userSearchStr, Stri if (teamName != null && !teamName.equals("")) { if (Objects.equals( manageDatabase.getTeamNameFromTeamId(tenantId, userInfoModel.getTeamId()), - teamName)) userInfoModels.add(userInfoModel); - } else userInfoModels.add(userInfoModel); + teamName)) { + userInfoModels.add(userInfoModel); + } + } else { + userInfoModels.add(userInfoModel); + } }); userInfoModels.forEach( userInfoModel -> { @@ -679,7 +713,7 @@ Map addTwoDefaultTeams( } public ApiResponse registerUser(RegisterUserInfoModel newUser, boolean isExternal) - throws Exception { + throws KlawException { log.info("registerUser {}", newUser.getUsername()); HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); @@ -754,8 +788,9 @@ public ApiResponse registerUser(RegisterUserInfoModel newUser, boolean isExterna } String resultRegister = dbHandle.registerUser(registerUserInfo); - if (resultRegister.contains("Failure")) + if (resultRegister.contains("Failure")) { return ApiResponse.builder().result("Registration already exists.").build(); + } if (isExternal) { mailService.sendMailRegisteredUser( @@ -773,10 +808,12 @@ public List getNewUserRequests() { int tenantId = commonUtilsService.getTenantId(getUserName()); List registerUserInfoList; - if ("saas".equals(kwInstallationType)) + if ("saas".equals(kwInstallationType)) { registerUserInfoList = manageDatabase.getHandleDbRequests().selectAllRegisterUsersInfoForTenant(tenantId); - else registerUserInfoList = manageDatabase.getHandleDbRequests().selectAllRegisterUsersInfo(); + } else { + registerUserInfoList = manageDatabase.getHandleDbRequests().selectAllRegisterUsersInfo(); + } List registerUserInfoModels = new ArrayList<>(); RegisterUserInfoModel registerUserInfoModel; @@ -801,14 +838,14 @@ public ApiResponse approveNewUserRequests( if (isExternal && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); try { RegisterUserInfo registerUserInfo = dbHandle.getRegisterUsersInfo(username); - if (!isExternal) // from saas new user requests for tenant owners - { + if (!isExternal) { // from saas new user requests for tenant owners registerUserInfo.setTenantId(tenantId); registerUserInfo.setTeamId(manageDatabase.getTeamIdFromTeamName(tenantId, teamName)); } @@ -824,15 +861,17 @@ public ApiResponse approveNewUserRequests( userInfo.setRole(registerUserInfo.getRole()); userInfo.setTenantId(tenantId); - if ("db".equals(authenticationType)) + if ("db".equals(authenticationType)) { userInfo.setUserPassword(decodePwd(registerUserInfo.getPwd())); - else userInfo.setUserPassword(""); + } else { + userInfo.setUserPassword(""); + } userInfo.setMailid(registerUserInfo.getMailid()); ApiResponse resultResp = addNewUser(userInfo, isExternal); - if (resultResp.getResult().contains(ApiResultStatus.SUCCESS.value)) + if (resultResp.getResult().contains(ApiResultStatus.SUCCESS.value)) { dbHandle.updateNewUserRequest(username, userDetails, true); - else { + } else { return ApiResponse.builder().result(ApiResultStatus.FAILURE.value).build(); } return ApiResponse.builder().result(ApiResultStatus.SUCCESS.value).build(); @@ -847,8 +886,9 @@ public ApiResponse declineNewUserRequests(String username) throws KlawException String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) + getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.builder().result(ApiResultStatus.NOT_AUTHORIZED.value).build(); + } HandleDbRequests dbHandle = manageDatabase.getHandleDbRequests(); try { @@ -868,7 +908,9 @@ public RegisterUserInfoModel getRegistrationInfoFromId(String registrationId, St RegisterUserInfoModel registerUserInfoModel = new RegisterUserInfoModel(); copyProperties(registerUserInfo, registerUserInfoModel); return registerUserInfoModel; - } else return null; + } else { + return null; + } } public Env getEnvDetailsFromId(String envId) { diff --git a/src/main/java/io/aiven/klaw/service/UtilControllerService.java b/src/main/java/io/aiven/klaw/service/UtilControllerService.java index 281bb4aef3..dab302849c 100644 --- a/src/main/java/io/aiven/klaw/service/UtilControllerService.java +++ b/src/main/java/io/aiven/klaw/service/UtilControllerService.java @@ -4,9 +4,7 @@ import io.aiven.klaw.config.ManageDatabase; import io.aiven.klaw.dao.*; -import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.HandleDbRequests; -import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwMetadataUpdates; import io.aiven.klaw.model.PermissionType; @@ -26,8 +24,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; @@ -37,9 +33,6 @@ @Slf4j public class UtilControllerService { - public static final String ERROR_MSG = - "Unable to process the request. Please contact our Administrator !!"; - @Autowired ManageDatabase manageDatabase; @Autowired MailUtils mailService; @@ -98,7 +91,9 @@ public String getTenantNameFromUser(String userId) { .get() .getValue(); - } else return null; + } else { + return null; + } } private List getEnvsFromUserId(String userDetails) { @@ -195,8 +190,11 @@ public Map getAllRequestsToBeApproved(String requestor, int tena countList.put("connectors", allConnectorReqs.size() + ""); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) countList.put("users", "0"); - else countList.put("users", allUserReqs.size() + ""); + getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + countList.put("users", "0"); + } else { + countList.put("users", allUserReqs.size() + ""); + } return countList; } @@ -206,11 +204,8 @@ public Map getAuth() { String userName = getUserName(); HandleDbRequests reqsHandle = manageDatabase.getHandleDbRequests(); if (userName != null) { - String teamName = manageDatabase.getTeamNameFromTeamId(tenantId, getMyTeamId(userName)); - String authority = commonUtilsService.getAuthority(getPrincipal()); - Map outstanding = getAllRequestsToBeApproved(userName, tenantId); String outstandingTopicReqs = outstanding.get("topics"); @@ -228,15 +223,25 @@ public Map getAuth() { String outstandingUserReqs = outstanding.get("users"); int outstandingUserReqsInt = Integer.parseInt(outstandingUserReqs); - if (outstandingTopicReqsInt <= 0) outstandingTopicReqs = "0"; + if (outstandingTopicReqsInt <= 0) { + outstandingTopicReqs = "0"; + } - if (outstandingAclReqsInt <= 0) outstandingAclReqs = "0"; + if (outstandingAclReqsInt <= 0) { + outstandingAclReqs = "0"; + } - if (outstandingSchemasReqsInt <= 0) outstandingSchemasReqs = "0"; + if (outstandingSchemasReqsInt <= 0) { + outstandingSchemasReqs = "0"; + } - if (outstandingConnectorReqsInt <= 0) outstandingConnectorReqs = "0"; + if (outstandingConnectorReqsInt <= 0) { + outstandingConnectorReqs = "0"; + } - if (outstandingUserReqsInt <= 0) outstandingUserReqs = "0"; + if (outstandingUserReqsInt <= 0) { + outstandingUserReqs = "0"; + } Map dashboardData = reqsHandle.getDashboardInfo(getMyTeamId(userName), tenantId); @@ -253,46 +258,64 @@ public Map getAuth() { String canUpdatePermissions, addEditRoles; - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) + if (commonUtilsService.isNotAuthorizedUser( + getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { canUpdatePermissions = "NotAuthorized"; - else canUpdatePermissions = ApiResultStatus.AUTHORIZED.value; + } else { + canUpdatePermissions = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) addEditRoles = "NotAuthorized"; - else addEditRoles = ApiResultStatus.AUTHORIZED.value; + getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { + addEditRoles = "NotAuthorized"; + } else { + addEditRoles = ApiResultStatus.AUTHORIZED.value; + } String canShutdownKw; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SHUTDOWN_KLAW)) { canShutdownKw = "NotAuthorized"; - } else canShutdownKw = ApiResultStatus.AUTHORIZED.value; + } else { + canShutdownKw = ApiResultStatus.AUTHORIZED.value; + } String syncBackTopics, syncBackAcls; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_BACK_TOPICS)) { syncBackTopics = "NotAuthorized"; - } else syncBackTopics = ApiResultStatus.AUTHORIZED.value; + } else { + syncBackTopics = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { syncBackAcls = "NotAuthorized"; - } else syncBackAcls = ApiResultStatus.AUTHORIZED.value; + } else { + syncBackAcls = ApiResultStatus.AUTHORIZED.value; + } String addUser, addTeams; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_USERS)) { addUser = "NotAuthorized"; - } else addUser = ApiResultStatus.AUTHORIZED.value; + } else { + addUser = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_TEAMS)) { addTeams = "NotAuthorized"; - } else addTeams = ApiResultStatus.AUTHORIZED.value; + } else { + addTeams = ApiResultStatus.AUTHORIZED.value; + } String viewKafkaConnect; if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.VIEW_CONNECTORS)) { viewKafkaConnect = "NotAuthorized"; - } else viewKafkaConnect = ApiResultStatus.AUTHORIZED.value; + } else { + viewKafkaConnect = ApiResultStatus.AUTHORIZED.value; + } String requestTopics; String requestAcls; @@ -302,28 +325,38 @@ public Map getAuth() { if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.REQUEST_CREATE_TOPICS)) { requestTopics = "NotAuthorized"; - } else requestTopics = ApiResultStatus.AUTHORIZED.value; + } else { + requestTopics = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { requestAcls = "NotAuthorized"; - } else requestAcls = ApiResultStatus.AUTHORIZED.value; + } else { + requestAcls = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.REQUEST_CREATE_SCHEMAS)) { requestSchemas = "NotAuthorized"; - } else requestSchemas = ApiResultStatus.AUTHORIZED.value; + } else { + requestSchemas = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser( userName, PermissionType.REQUEST_CREATE_CONNECTORS)) { requestConnector = "NotAuthorized"; - } else requestConnector = ApiResultStatus.AUTHORIZED.value; + } else { + requestConnector = ApiResultStatus.AUTHORIZED.value; + } if (ApiResultStatus.AUTHORIZED.value.equals(requestTopics) || ApiResultStatus.AUTHORIZED.value.equals(requestAcls) || ApiResultStatus.AUTHORIZED.value.equals(requestSchemas) - || ApiResultStatus.AUTHORIZED.value.equals(requestConnector)) + || ApiResultStatus.AUTHORIZED.value.equals(requestConnector)) { requestItems = ApiResultStatus.AUTHORIZED.value; - else requestItems = "NotAuthorized"; + } else { + requestItems = "NotAuthorized"; + } String approveDeclineTopics; String approveDeclineSubscriptions; @@ -334,43 +367,53 @@ public Map getAuth() { if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_TOPICS)) { approveDeclineTopics = "NotAuthorized"; - } else approveDeclineTopics = ApiResultStatus.AUTHORIZED.value; + } else { + approveDeclineTopics = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_SUBSCRIPTIONS)) { approveDeclineSubscriptions = "NotAuthorized"; - } else approveDeclineSubscriptions = ApiResultStatus.AUTHORIZED.value; + } else { + approveDeclineSubscriptions = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_SCHEMAS)) { approveDeclineSchemas = "NotAuthorized"; - } else approveDeclineSchemas = ApiResultStatus.AUTHORIZED.value; + } else { + approveDeclineSchemas = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.APPROVE_CONNECTORS)) { approveDeclineConnectors = "NotAuthorized"; - } else approveDeclineConnectors = ApiResultStatus.AUTHORIZED.value; + } else { + approveDeclineConnectors = ApiResultStatus.AUTHORIZED.value; + } if (ApiResultStatus.AUTHORIZED.value.equals(approveDeclineTopics) || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSubscriptions) || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSchemas) || ApiResultStatus.AUTHORIZED.value.equals(approveDeclineConnectors) - || ApiResultStatus.AUTHORIZED.value.equals(addUser)) + || ApiResultStatus.AUTHORIZED.value.equals(addUser)) { approveAtleastOneRequest = ApiResultStatus.AUTHORIZED.value; + } String redirectionPage = ""; if (ApiResultStatus.AUTHORIZED.value.equals(approveAtleastOneRequest)) { if (outstandingTopicReqsInt > 0 - && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineTopics)) + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineTopics)) { redirectionPage = "execTopics"; - else if (outstandingAclReqsInt > 0 - && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSubscriptions)) + } else if (outstandingAclReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSubscriptions)) { redirectionPage = "execAcls"; - else if (outstandingSchemasReqsInt > 0 - && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSchemas)) + } else if (outstandingSchemasReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineSchemas)) { redirectionPage = "execSchemas"; - else if (outstandingConnectorReqsInt > 0 - && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineConnectors)) + } else if (outstandingConnectorReqsInt > 0 + && ApiResultStatus.AUTHORIZED.value.equals(approveDeclineConnectors)) { redirectionPage = "execConnectors"; - else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(addUser)) + } else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(addUser)) { redirectionPage = "execUsers"; + } } String syncTopicsAcls, syncConnectors; @@ -378,11 +421,15 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_TOPICS) || commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_SUBSCRIPTIONS)) { syncTopicsAcls = "NotAuthorized"; - } else syncTopicsAcls = ApiResultStatus.AUTHORIZED.value; + } else { + syncTopicsAcls = ApiResultStatus.AUTHORIZED.value; + } if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.SYNC_CONNECTORS)) { syncConnectors = "NotAuthorized"; - } else syncConnectors = ApiResultStatus.AUTHORIZED.value; + } else { + syncConnectors = ApiResultStatus.AUTHORIZED.value; + } String addDeleteEditTenants; String addDeleteEditEnvs; @@ -390,14 +437,19 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a String updateServerConfig, showServerConfigEnvProperties; String viewTopics; - if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.UPDATE_SERVERCONFIG)) + if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.UPDATE_SERVERCONFIG)) { updateServerConfig = "NotAuthorized"; - else updateServerConfig = ApiResultStatus.AUTHORIZED.value; + } else { + updateServerConfig = ApiResultStatus.AUTHORIZED.value; + } if (tenantId == KwConstants.DEFAULT_TENANT_ID - && !commonUtilsService.isNotAuthorizedUser(userName, PermissionType.UPDATE_SERVERCONFIG)) + && !commonUtilsService.isNotAuthorizedUser( + userName, PermissionType.UPDATE_SERVERCONFIG)) { showServerConfigEnvProperties = ApiResultStatus.AUTHORIZED.value; - else showServerConfigEnvProperties = "NotAuthorized"; + } else { + showServerConfigEnvProperties = "NotAuthorized"; + } if (tenantId == KwConstants.DEFAULT_TENANT_ID && SUPERADMIN @@ -406,34 +458,47 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a manageDatabase .getHandleDbRequests() .getUsersInfo(userName) - .getRole())) // allow adding tenants only to "default" - addDeleteEditTenants = ApiResultStatus.AUTHORIZED.value; - else addDeleteEditTenants = "NotAuthorized"; + .getRole())) { // allow adding tenants only to "default" + addDeleteEditTenants = ApiResultStatus.AUTHORIZED.value; + } else { + addDeleteEditTenants = "NotAuthorized"; + } - if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_ENVS)) + if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_ENVS)) { addDeleteEditEnvs = "NotAuthorized"; - else addDeleteEditEnvs = ApiResultStatus.AUTHORIZED.value; + } else { + addDeleteEditEnvs = ApiResultStatus.AUTHORIZED.value; + } - if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) + if (commonUtilsService.isNotAuthorizedUser( + userName, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) { addDeleteEditClusters = "NotAuthorized"; - else addDeleteEditClusters = ApiResultStatus.AUTHORIZED.value; + } else { + addDeleteEditClusters = ApiResultStatus.AUTHORIZED.value; + } - if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) + if ("ad".equals(authenticationType) && "true".equals(adAuthRoleEnabled)) { dashboardData.put("adAuthRoleEnabled", "true"); - else dashboardData.put("adAuthRoleEnabled", "false"); + } else { + dashboardData.put("adAuthRoleEnabled", "false"); + } - if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.VIEW_TOPICS)) + if (commonUtilsService.isNotAuthorizedUser(userName, PermissionType.VIEW_TOPICS)) { viewTopics = "NotAuthorized"; - else viewTopics = ApiResultStatus.AUTHORIZED.value; + } else { + viewTopics = ApiResultStatus.AUTHORIZED.value; + } String companyInfo = manageDatabase.getTenantFullConfig(tenantId).getOrgName(); if (companyInfo == null || companyInfo.equals("")) { companyInfo = "Our Organization"; } - if ("saas".equals(kwInstallationType)) + if ("saas".equals(kwInstallationType)) { + dashboardData.put("supportlink", "https://github.com/aiven/klaw/issues"); + } else { dashboardData.put("supportlink", "https://github.com/aiven/klaw/issues"); - else dashboardData.put("supportlink", "https://github.com/aiven/klaw/issues"); + } // broadcast text String broadCastText = ""; @@ -443,8 +508,9 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a manageDatabase.getKwPropertyValue( KwConstants.broadCastTextProperty, KwConstants.DEFAULT_TENANT_ID); - if (broadCastTextLocal != null && !broadCastTextLocal.equals("")) + if (broadCastTextLocal != null && !broadCastTextLocal.equals("")) { broadCastText = "Announcement : " + broadCastTextLocal; + } if (broadCastTextGlobal != null && !broadCastTextGlobal.equals("") && tenantId != KwConstants.DEFAULT_TENANT_ID) { @@ -452,12 +518,10 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a } dashboardData.put("broadcastText", broadCastText); - dashboardData.put("saasEnabled", kwInstallationType); dashboardData.put( "tenantActiveStatus", manageDatabase.getTenantFullConfig(tenantId).getIsActive()); // true/false - dashboardData.put("username", userName); dashboardData.put("authenticationType", authenticationType); dashboardData.put("teamname", teamName); @@ -500,9 +564,6 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a dashboardData.put("showAddDeleteTenants", addDeleteEditTenants); dashboardData.put("addDeleteEditClusters", addDeleteEditClusters); dashboardData.put("addDeleteEditEnvs", addDeleteEditEnvs); - // if(manageDatabase.getIsTrialLicense()) - // dashboardData.put("larit","(Trial) "); - // else dashboardData.put("larit", ""); return dashboardData; @@ -511,13 +572,16 @@ else if (outstandingUserReqsInt > 0 && ApiResultStatus.AUTHORIZED.value.equals(a public void getLogoutPage(HttpServletRequest request, HttpServletResponse response) { Authentication authentication = commonUtilsService.getAuthentication(); - if (authentication != null) + if (authentication != null) { new SecurityContextLogoutHandler().logout(request, response, authentication); + } } public void shutdownContext() { int tenantId = commonUtilsService.getTenantId(getUserName()); - if (tenantId != KwConstants.DEFAULT_TENANT_ID) return; + if (tenantId != KwConstants.DEFAULT_TENANT_ID) { + return; + } if (!commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SHUTDOWN_KLAW)) { log.info("Klaw Shutdown requested by {}", getUserName()); @@ -571,10 +635,4 @@ public void resetCache(String tenantName, String entityType, String operationTyp log.error("Error from resetCache ", e); } } - - public static ResponseEntity handleException(KlawException e) { - log.error(e.getMessage()); - return new ResponseEntity<>( - ApiResponse.builder().message(ERROR_MSG).build(), HttpStatus.INTERNAL_SERVER_ERROR); - } } diff --git a/src/main/java/io/aiven/klaw/service/ValidateCaptchaService.java b/src/main/java/io/aiven/klaw/service/ValidateCaptchaService.java index c842958c46..5859e8f55c 100644 --- a/src/main/java/io/aiven/klaw/service/ValidateCaptchaService.java +++ b/src/main/java/io/aiven/klaw/service/ValidateCaptchaService.java @@ -45,7 +45,9 @@ public boolean validateCaptcha(final String captchaResponse) { // by the recaptcha client-side integration on your site. params.add("response", captchaResponse); - if (!validateRecaptcha) return true; + if (!validateRecaptcha) { + return true; + } CaptchaResponse apiResponse = null; try { diff --git a/src/main/java/io/aiven/klaw/uglify/UglifyFiles.java b/src/main/java/io/aiven/klaw/uglify/UglifyFiles.java index dacceb1c1f..396caef441 100644 --- a/src/main/java/io/aiven/klaw/uglify/UglifyFiles.java +++ b/src/main/java/io/aiven/klaw/uglify/UglifyFiles.java @@ -48,8 +48,11 @@ private void uglifyJsFiles(String osName, Runtime rt) { private void executeCommand(Runtime rt, String commandToExec, String osName) { String commandPrefix = ""; - if (osName.startsWith("Windows")) commandPrefix = "cmd.exe /c "; - else commandPrefix = ""; + if (osName.startsWith("Windows")) { + commandPrefix = "cmd.exe /c "; + } else { + commandPrefix = ""; + } commandToExec = commandPrefix + commandToExec; From 53f317c8d09d67e5aa7126558fd220b7fda7a1ef Mon Sep 17 00:00:00 2001 From: muralibasani Date: Mon, 10 Oct 2022 12:51:40 +0200 Subject: [PATCH 14/15] Fix circular dependency issue --- .../io/aiven/klaw/auth/KwRequestFilter.java | 5 +- .../io/aiven/klaw/config/ManageDatabase.java | 88 ++++++++++++------- .../klaw/config/SecurityConfigNoSSO.java | 7 +- src/main/resources/application.properties | 2 - .../service/AclControllerServiceTest.java | 4 +- .../klaw/service/ClusterApiServiceTest.java | 6 +- .../SchemaRegistryControllerServiceTest.java | 4 +- .../service/TopicControllerServiceTest.java | 4 +- .../UiConfigControllerServiceTest.java | 4 +- 9 files changed, 74 insertions(+), 50 deletions(-) diff --git a/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java b/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java index cc5370f967..5740e7c342 100644 --- a/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java +++ b/src/main/java/io/aiven/klaw/auth/KwRequestFilter.java @@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; @@ -36,7 +37,7 @@ public class KwRequestFilter extends UsernamePasswordAuthenticationFilter { @Autowired KwAuthenticationService kwAuthenticationService; - @Autowired private AuthenticationManager authenticationManager; + @Lazy private AuthenticationManager authenticationManager; @Autowired private KwAuthenticationFailureHandler kwAuthenticationFailureHandler; @@ -44,7 +45,7 @@ public class KwRequestFilter extends UsernamePasswordAuthenticationFilter { @Override @Autowired - public void setAuthenticationManager(AuthenticationManager authenticationManager) { + public void setAuthenticationManager(@Lazy AuthenticationManager authenticationManager) { super.setAuthenticationManager(authenticationManager); } diff --git a/src/main/java/io/aiven/klaw/config/ManageDatabase.java b/src/main/java/io/aiven/klaw/config/ManageDatabase.java index 2c986f8a38..b2a812955d 100644 --- a/src/main/java/io/aiven/klaw/config/ManageDatabase.java +++ b/src/main/java/io/aiven/klaw/config/ManageDatabase.java @@ -1,35 +1,52 @@ package io.aiven.klaw.config; import com.fasterxml.jackson.databind.ObjectMapper; -import io.aiven.klaw.dao.*; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.dao.Env; +import io.aiven.klaw.dao.KwClusters; +import io.aiven.klaw.dao.KwProperties; +import io.aiven.klaw.dao.KwRolesPermissions; +import io.aiven.klaw.dao.KwTenants; +import io.aiven.klaw.dao.ProductDetails; +import io.aiven.klaw.dao.Team; +import io.aiven.klaw.dao.UserInfo; +import io.aiven.klaw.error.KlawException; import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; -import io.aiven.klaw.helpers.db.rdbms.JdbcDataSourceCondition; -import io.aiven.klaw.model.*; +import io.aiven.klaw.model.ApiResultStatus; +import io.aiven.klaw.model.EnvModel; +import io.aiven.klaw.model.KafkaClustersType; +import io.aiven.klaw.model.KwTenantConfigModel; +import io.aiven.klaw.model.RequestStatus; +import io.aiven.klaw.model.TenantConfig; import io.aiven.klaw.service.DefaultDataService; import io.aiven.klaw.service.KwConstants; -import io.aiven.klaw.service.MailUtils; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration @Slf4j -public class ManageDatabase implements ApplicationContextAware { +public class ManageDatabase implements ApplicationContextAware, InitializingBean, DisposableBean { public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private HandleDbRequests handleDbRequests; + + @Autowired HandleDbRequestsJdbc handleDbRequests; private static Map>>> envParamsMapPerTenant; @@ -74,14 +91,11 @@ public class ManageDatabase implements ApplicationContextAware { private static Map> allEnvListPerTenant = new HashMap<>(); private static Map tenantConfig = new HashMap<>(); - ; private static List reqStatusList; private static boolean isTrialLicense; - @Autowired private MailUtils utils; - @Autowired private DefaultDataService defaultDataService; @Value("${klaw.org.name}") @@ -119,14 +133,38 @@ private void shutdownApp() { ((ConfigurableApplicationContext) contextApp).close(); } - @PostConstruct - public void loadDb() throws Exception { - handleDbRequests = handleJdbc(); - loadStaticDataToDb(); - updateStaticDataToMemory(); - checkSSOAuthentication(); + @Override + public void afterPropertiesSet() throws KlawException { + loadDb(); + } + + @Override + public void destroy() throws Exception { + shutdownApp(); + } + + public void loadDb() throws KlawException { + try { + loadStaticDataToDb(); + updateStaticDataToMemory(); + checkSSOAuthentication(); + } catch (Exception e) { + e.printStackTrace(); + log.error("Error in starting the application. {}", e.getMessage()); + throw new KlawException(e.getMessage()); + } } + public HandleDbRequestsJdbc getHandleDbRequests() { + return handleDbRequests; + } + + // @Bean() + // @Conditional(JdbcDataSourceCondition.class) + // HandleDbRequestsJdbc handleJdbc() { + // return new HandleDbRequestsJdbc(); + // } + private void loadStaticDataToDb() { // add tenant Optional kwTenants = handleDbRequests.getMyTenants(KwConstants.DEFAULT_TENANT_ID); @@ -205,16 +243,6 @@ private void checkSSOAuthentication() { } } - public HandleDbRequests getHandleDbRequests() { - return handleDbRequests; - } - - @Bean() - @Conditional(JdbcDataSourceCondition.class) - HandleDbRequestsJdbc handleJdbc() { - return new HandleDbRequestsJdbc(); - } - public List selectAllUsersInfo() { return handleDbRequests.selectAllUsersAllTenants(); } diff --git a/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java b/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java index b9a2a0f5d3..91c85b8666 100644 --- a/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java +++ b/src/main/java/io/aiven/klaw/config/SecurityConfigNoSSO.java @@ -3,7 +3,6 @@ import io.aiven.klaw.auth.KwRequestFilter; import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.service.MailUtils; import java.util.*; import javax.naming.directory.Attributes; import lombok.extern.slf4j.Slf4j; @@ -36,8 +35,6 @@ public class SecurityConfigNoSSO extends WebSecurityConfigurerAdapter { @Autowired private ManageDatabase manageTopics; - @Autowired private MailUtils utils; - @Value("${klaw.login.authentication.type}") private String authenticationType; @@ -136,8 +133,8 @@ protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(kwRequestFilterup, UsernamePasswordAuthenticationFilter.class); } - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { if (authenticationType != null && authenticationType.equals("db")) { dbAuthentication(auth); } else if (authenticationType != null && authenticationType.equals("ldap")) { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a2e834a9c3..aba9872c8a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -70,8 +70,6 @@ spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.jdbc.lob.non_contextual_creation=true spring.jpa.properties.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl -spring.main.allow-circular-references=true - # Email notification properties klaw.mail.notifications.enable=true spring.mail.properties.mail.transport.protocol=smtp diff --git a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index ea7f4ba1e2..575e357fcc 100644 --- a/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -19,7 +19,7 @@ import io.aiven.klaw.dao.Topic; import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.AclInfo; import io.aiven.klaw.model.AclPatternType; import io.aiven.klaw.model.AclRequestsModel; @@ -60,7 +60,7 @@ public class AclControllerServiceTest { @Mock private ClusterApiService clusterApiService; - @Mock private HandleDbRequests handleDbRequests; + @Mock private HandleDbRequestsJdbc handleDbRequests; @Mock private ManageDatabase manageDatabase; diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index 0b387648c4..c0c1276468 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -16,7 +16,7 @@ import io.aiven.klaw.dao.SchemaRequest; import io.aiven.klaw.dao.TopicRequest; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.AclIPPrincipleType; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; @@ -50,9 +50,9 @@ public class ClusterApiServiceTest { private UtilMethods utilMethods; - @Mock HandleDbRequests handleDbRequests; + @Mock HandleDbRequestsJdbc handleDbRequests; - @Mock MailUtils mailService; + @Mock MailUtils çƒç; @Mock ManageDatabase manageDatabase; diff --git a/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java index bc704eeb5a..85458d939b 100644 --- a/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java @@ -13,7 +13,7 @@ import io.aiven.klaw.dao.Topic; import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.SchemaRequestModel; @@ -45,7 +45,7 @@ public class SchemaRegistryControllerServiceTest { @Mock private UserDetails userDetails; - @Mock private HandleDbRequests handleDbRequests; + @Mock private HandleDbRequestsJdbc handleDbRequests; @Mock private MailUtils mailService; diff --git a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index 29ed2726d4..028dc91d53 100644 --- a/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -16,7 +16,7 @@ import io.aiven.klaw.dao.TopicRequest; import io.aiven.klaw.dao.UserInfo; import io.aiven.klaw.error.KlawException; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.ApiResultStatus; import io.aiven.klaw.model.KwTenantConfigModel; @@ -65,7 +65,7 @@ public class TopicControllerServiceTest { @Mock private ManageDatabase manageDatabase; - @Mock private HandleDbRequests handleDbRequests; + @Mock private HandleDbRequestsJdbc handleDbRequests; @Mock CommonUtilsService commonUtilsService; diff --git a/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java b/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java index 56bcb23d60..e4a9d70bf7 100644 --- a/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java @@ -12,7 +12,7 @@ import io.aiven.klaw.dao.KwClusters; import io.aiven.klaw.dao.Team; import io.aiven.klaw.dao.UserInfo; -import io.aiven.klaw.helpers.HandleDbRequests; +import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.EnvModel; import io.aiven.klaw.model.UserInfoModel; import java.sql.Timestamp; @@ -39,7 +39,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class UiConfigControllerServiceTest { - @Mock private HandleDbRequests handleDbRequests; + @Mock private HandleDbRequestsJdbc handleDbRequests; @Mock private ClusterApiService clusterApiService; From d970ee45f7c70d97a9fc1102c4bd2051587544b5 Mon Sep 17 00:00:00 2001 From: muralibasani Date: Mon, 10 Oct 2022 13:55:41 +0200 Subject: [PATCH 15/15] Remove commented code blocks --- src/main/java/io/aiven/klaw/config/ManageDatabase.java | 9 +-------- .../io/aiven/klaw/service/ClusterApiServiceTest.java | 2 -- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/src/main/java/io/aiven/klaw/config/ManageDatabase.java b/src/main/java/io/aiven/klaw/config/ManageDatabase.java index b2a812955d..919cc09fbb 100644 --- a/src/main/java/io/aiven/klaw/config/ManageDatabase.java +++ b/src/main/java/io/aiven/klaw/config/ManageDatabase.java @@ -149,8 +149,7 @@ public void loadDb() throws KlawException { updateStaticDataToMemory(); checkSSOAuthentication(); } catch (Exception e) { - e.printStackTrace(); - log.error("Error in starting the application. {}", e.getMessage()); + log.error("Error in starting the application. ", e); throw new KlawException(e.getMessage()); } } @@ -159,12 +158,6 @@ public HandleDbRequestsJdbc getHandleDbRequests() { return handleDbRequests; } - // @Bean() - // @Conditional(JdbcDataSourceCondition.class) - // HandleDbRequestsJdbc handleJdbc() { - // return new HandleDbRequestsJdbc(); - // } - private void loadStaticDataToDb() { // add tenant Optional kwTenants = handleDbRequests.getMyTenants(KwConstants.DEFAULT_TENANT_ID); diff --git a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java index c0c1276468..0fee64c4f5 100644 --- a/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java +++ b/src/test/java/io/aiven/klaw/service/ClusterApiServiceTest.java @@ -52,8 +52,6 @@ public class ClusterApiServiceTest { @Mock HandleDbRequestsJdbc handleDbRequests; - @Mock MailUtils çƒç; - @Mock ManageDatabase manageDatabase; @Mock RestTemplate restTemplate;