From 565a7614ade76bcc56ca012b6b0e2d18f1d0d9df Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 3 Oct 2023 13:39:18 +0530 Subject: [PATCH] Change JSON object return methods:Scopes --- .../rest/api/PublisherRESTAPIServices.java | 4 +- .../api/PublisherRESTAPIServicesImpl.java | 34 ++--- .../extension/rest/api/dto/APIInfo/Scope.java | 34 ++--- .../publisher/APIPublisherServiceImpl.java | 117 +++++++++--------- 4 files changed, 96 insertions(+), 93 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index 4e7d79403a..868c358f23 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -35,7 +35,7 @@ import java.util.List; public interface PublisherRESTAPIServices { - JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) @@ -107,7 +107,7 @@ public interface PublisherRESTAPIServices { String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException; - io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java index 90724d3cf1..65d2af0258 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java @@ -55,7 +55,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { + Constants.COLON + port; @Override - public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + public Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES; @@ -69,8 +69,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); if (HttpStatus.SC_OK == response.code()) { - JSONObject jsonObject = new JSONObject(response.body().string()); - return jsonObject; + JSONArray scopeList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(scopeList.toString(), Scope[].class); } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. @@ -144,16 +144,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; JSONArray bindings = new JSONArray(); - for (String str : scope.getRoles()) { + for (String str : scope.getBindings()) { bindings.put(str); } JSONObject payload = new JSONObject(); - payload.put("name", scope.getKey()); - payload.put("displayName", scope.getName()); - payload.put("description", scope.getDescription()); - payload.put("bindings", bindings); - payload.put("usageCount", scope.getUsageCount()); + payload.put("name", (scope.getName() != null ? scope.getName() : "")); + payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : "")); + payload.put("description", (scope.getDescription() != null ? scope.getDescription() : "")); + payload.put("bindings", (bindings != null ? bindings : "")); + payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() @@ -196,16 +196,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); JSONArray bindings = new JSONArray(); - for (String str : scope.getRoles()) { + for (String str : scope.getBindings()) { bindings.put(str); } JSONObject payload = new JSONObject(); - payload.put("name", scope.getKey()); - payload.put("displayName", scope.getName()); - payload.put("description", scope.getDescription()); - payload.put("bindings", bindings); - payload.put("usageCount", scope.getUsageCount()); + payload.put("name", (scope.getName() != null ? scope.getName() : "")); + payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : "")); + payload.put("description", (scope.getDescription() != null ? scope.getDescription() : "")); + payload.put("bindings", (bindings != null ? bindings : "")); + payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() @@ -453,7 +453,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { " \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + " \"endpointImplementationType\": \"ENDPOINT\",\n" + " \"scopes\": " + api.getScopes().toString() + ",\n" + - " \"operations\": " + (api.getOperations() != null? api.getOperations().toString() : null) + ",\n" + + " \"operations\": " + (api.getOperations() != null ? api.getOperations().toString() : null) + ",\n" + " \"threatProtectionPolicies\": null,\n" + " \"categories\": [],\n" + " \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + @@ -632,7 +632,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) + String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException { String deleteApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java index 1e414675cd..53a40e2707 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Scope.java @@ -18,25 +18,29 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; import java.io.Serializable; -import java.util.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Objects; +import java.util.Set; +import java.util.HashSet; public class Scope implements Serializable{ private static final long serialVersionUID = 1L; - String key; + String id; String name; - List roles; + String displayName; String description; - String id; + List bindings; int usageCount; - public String getKey() { - return key; + public String getDisplayName() { + return displayName; } - public void setKey(String key) { - this.key = key; + public void setDisplayName(String displayName) { + this.displayName = displayName; } public String getName() { @@ -47,12 +51,12 @@ public class Scope implements Serializable{ this.name = name; } - public List getRoles() { - return roles; + public List getBindings() { + return bindings; } - public void setRoles(List roles) { - this.roles = removeDuplicatesFromRoleString(roles); + public void setBindings(List bindings) { + this.bindings = removeDuplicatesFromRoleString(bindings); } public String getDescription() { @@ -87,15 +91,15 @@ public class Scope implements Serializable{ Scope scope = (Scope) o; if (id != null ? !id.equals(scope.id) : scope.id != null) return false; - if (!key.equals(scope.key)) return false; if (!name.equals(scope.name)) return false; - if (roles != null ? !roles.equals(scope.roles) : scope.roles != null) return false; + if (!displayName.equals(scope.displayName)) return false; + if (bindings != null ? !bindings.equals(scope.bindings) : scope.bindings != null) return false; return description != null ? description.equals(scope.description) : scope.description == null; } @Override public int hashCode() { - return Objects.hash(key, name, roles, description, id); + return Objects.hash(name, displayName, bindings, description, id); } private static List removeDuplicatesFromRoleString(List roles) { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 305b542777..a16e249002 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -100,7 +100,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT"; public static final String API_GLOBAL_VISIBILITY = "PUBLIC"; public static final String API_PRIVATE_VISIBILITY = "PRIVATE"; - private static final String ADMIN_ROLE_KEY = ",admin"; + private static final String ADMIN_ROLE_KEY = "admin"; private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); @@ -184,10 +184,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { Scope scope = new Scope(); - scope.setName(apiScope.getName()); + scope.setDisplayName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); - scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); + scope.setName(apiScope.getKey()); + List bindings = apiScope.getRoles(); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } @@ -257,10 +259,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { } else { // if new scope add as shared scope Scope scope = new Scope(); - scope.setName(apiScope.getName()); + scope.setName(apiScope.getKey()); scope.setDescription(apiScope.getDescription()); - scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); + scope.setDisplayName(apiScope.getName()); + List bindings = apiScope.getRoles(); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } @@ -278,10 +282,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (ApiScope apiScope : scopesToMoveAsSharedScopes) { Scope scope = new Scope(); - scope.setName(apiScope.getName()); + scope.setName(apiScope.getKey()); scope.setDescription(apiScope.getDescription()); - scope.setKey(apiScope.getKey()); - scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); + scope.setDisplayName(apiScope.getName()); + List bindings = apiScope.getRoles(); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } @@ -458,10 +464,15 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (DefaultPermission defaultPermission: defaultPermissions.getDefaultPermissions()) { //todo check whether scope is available or not ScopeMapping scopeMapping = defaultPermission.getScopeMapping(); - scope.setName(scopeMapping.getName()); + + String[] roles = scopeMapping.getDefaultRoles().split(","); + List bindings = Arrays.asList(roles); + bindings.add(ADMIN_ROLE_KEY); + + scope.setName(scopeMapping.getKey()); scope.setDescription(scopeMapping.getName()); - scope.setKey(scopeMapping.getKey()); - scope.setRoles(scopeMapping.getDefaultRoles() + ADMIN_ROLE_KEY); + scope.setDisplayName(scopeMapping.getName()); + scope.setBindings(bindings); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } catch (BadRequestException | UnexpectedResponseException | APIServicesException e) { @@ -497,7 +508,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); - JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); try { String fileName = @@ -543,11 +553,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { } Scope scope = new Scope(); - scope.setName( + scope.setDisplayName( scopeMapping[0] != null ? StringUtils.trim(scopeMapping[0]) : StringUtils.EMPTY); scope.setDescription( scopeMapping[1] != null ? StringUtils.trim(scopeMapping[1]) : StringUtils.EMPTY); - scope.setKey( + scope.setName( scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY); // scope.setPermissions( // scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY); @@ -562,30 +572,24 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } } - scope.setRoles(rolesList); - - //Set scope id which related to the scope key - JSONArray scopeList = (JSONArray) scopeObject.get("list"); - for (int i = 0; i < scopeList.length(); i++) { - JSONObject scopeObj = scopeList.getJSONObject(i); - if (scopeObj.getString("name").equals(StringUtils.trim(scopeMapping[2]))) { - scope.setId(scopeObj.getString("id")); - scope.setUsageCount(scopeObj.getInt("usageCount")); - -// Including already existing roles - JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings"); - for (int j = 0; j < existingRolesArray.length(); j++) { - rolesList.add(existingRolesArray.getString(j)); - } + //Set scope details which related to the scope key + Scope[] scopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + for (int i = 0; i < scopes.length; i++) { + Scope relatedScope = scopes[i]; + if (relatedScope.getName().equals(scopeMapping[2].toString())) { + scope.setId(relatedScope.getId()); + scope.setUsageCount(relatedScope.getUsageCount()); + //Including already existing roles + rolesList.addAll(relatedScope.getBindings()); } } - scope.setRoles(rolesList); + scope.setBindings(rolesList); - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { + if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); } else { // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list - log.warn(scope.getKey() + " not available as shared scope"); + log.warn(scope.getName() + " not available as shared scope"); } } for (String role : rolePermissions.keySet()) { @@ -598,12 +602,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } catch (IOException | DirectoryIteratorException ex) { log.error("failed to read scopes from file.", ex); - } catch (APIServicesException | BadRequestException e) { - String errorMsg = "Error while calling APIs"; - log.error(errorMsg, e); - throw new APIManagerPublisherException(e); } - } } catch (APIServicesException e) { String errorMsg = "Error while processing Publisher REST API response"; @@ -639,13 +638,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { try { PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); - JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Map permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); if (permissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, permissions, permScopeMap, false); + updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, permissions, permScopeMap, false); } if (removedPermissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, removedPermissions, permScopeMap, true); + updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, removedPermissions, permScopeMap, true); } try { @@ -677,7 +677,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} * @param apiApplicationKey {@link APIApplicationKey} * @param accessTokenInfo {@link AccessTokenInfo} - * @param scopeObject scope object returning from APIM + * @param scopeList scope list returning from APIM * @param permissions List of permissions * @param permScopeMap Permission Scope map * @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false. @@ -685,7 +685,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { */ private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - JSONObject scopeObject, String[] permissions, Map permScopeMap, boolean removingPermissions ) + Scope[] scopeList, String[] permissions, Map permScopeMap, boolean removingPermissions ) throws APIManagerPublisherException { for (String permission : permissions) { String scopeValue = permScopeMap.get(permission); @@ -696,22 +696,21 @@ public class APIPublisherServiceImpl implements APIPublisherService { throw new APIManagerPublisherException(msg); } - JSONArray scopeList = (JSONArray) scopeObject.get("list"); - for (int i = 0; i < scopeList.length(); i++) { - JSONObject scopeObj = scopeList.getJSONObject(i); - if (scopeObj.getString("name").equals(scopeValue)) { + for (int i = 0; i < scopeList.length; i++) { + Scope scopeObj = scopeList[i]; + if (scopeObj.getName().equals(scopeValue)) { Scope scope = new Scope(); - scope.setName(scopeObj.getString("name")); - scope.setKey(scopeObj.getString("name")); - scope.setDescription(scopeObj.getString("description")); - scope.setId(scopeObj.getString("id")); + scope.setName(scopeObj.getName()); + scope.setDisplayName(scopeObj.getDisplayName()); + scope.setDescription(scopeObj.getDescription()); + scope.setId(scopeObj.getId()); // Including already existing roles - JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings"); - List existingRoleList = new ArrayList(); + List existingRoleList = new ArrayList<>(); + existingRoleList.addAll(scopeObj.getBindings()); - for (int j = 0; j < existingRolesArray.length(); j++) { - existingRoleList.add((String) existingRolesArray.get(j)); + if (!existingRoleList.contains(roleName)) { + existingRoleList.add(roleName); } if (removingPermissions) { @@ -721,14 +720,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { existingRoleList.add(roleName); } } - scope.setRoles(String.join(",", existingRoleList)); + scope.setBindings(existingRoleList); try { - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { + if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); } else { // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list - log.warn(scope.getKey() + " not available as shared scope"); + log.warn(scope.getName() + " not available as shared scope"); } } catch (APIServicesException | BadRequestException | UnexpectedResponseException e) { log.error("Error occurred while updating role scope mapping via APIM REST endpoint.", e);