From 84ac4b84452516d926145d7be6d10787c5536e37 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Fri, 9 Aug 2024 11:47:50 +0530 Subject: [PATCH 1/2] Resolve integration test failure --- src/test/resources/IUDX-ACL-APD-APIs.postman_collection.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/resources/IUDX-ACL-APD-APIs.postman_collection.json b/src/test/resources/IUDX-ACL-APD-APIs.postman_collection.json index e111b27f..b7b50cf9 100644 --- a/src/test/resources/IUDX-ACL-APD-APIs.postman_collection.json +++ b/src/test/resources/IUDX-ACL-APD-APIs.postman_collection.json @@ -1137,7 +1137,7 @@ ], "body": { "mode": "raw", - "raw": "{\n \"request\": [\n {\n \"userEmail\": \"abd311111112c@xyz.com\",\n \"itemId\": \"a347c5b6-5281-4749-9eab-89784d8f8f9a\",\n \"itemType\": \"RESOURCE\",\n \"expiryTime\": \"2024-08-04T20:00:19\",\n \"constraints\": {\n \"access\": [\n \"sub\"\n ]\n }\n }\n ]\n}", + "raw": "{\n \"request\": [\n {\n \"userEmail\": \"abd311111112c@xyz.com\",\n \"itemId\": \"a347c5b6-5281-4749-9eab-89784d8f8f9a\",\n \"itemType\": \"RESOURCE\",\n \"expiryTime\": \"3024-08-04T20:00:19\",\n \"constraints\": {\n \"access\": [\n \"sub\"\n ]\n }\n }\n ]\n}", "options": { "raw": { "language": "json" From f442df10713dd73caf65e339b0e6d5fca1b72573 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Fri, 9 Aug 2024 12:38:14 +0530 Subject: [PATCH 2/2] Resolve checkstyle issues --- .../acl/server/policy/CatalogueClient.java | 286 ++++---- .../apd/acl/server/policy/CreatePolicy.java | 651 +++++++++--------- 2 files changed, 467 insertions(+), 470 deletions(-) diff --git a/src/main/java/iudx/apd/acl/server/policy/CatalogueClient.java b/src/main/java/iudx/apd/acl/server/policy/CatalogueClient.java index 3aec6049..50e0e7ee 100644 --- a/src/main/java/iudx/apd/acl/server/policy/CatalogueClient.java +++ b/src/main/java/iudx/apd/acl/server/policy/CatalogueClient.java @@ -1,5 +1,8 @@ package iudx.apd.acl.server.policy; +import static iudx.apd.acl.server.apiserver.util.Constants.*; +import static iudx.apd.acl.server.common.HttpStatusCode.*; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; @@ -11,167 +14,162 @@ import iudx.apd.acl.server.apiserver.util.Util; import iudx.apd.acl.server.common.HttpStatusCode; import iudx.apd.acl.server.common.ResponseUrn; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; - -import static iudx.apd.acl.server.apiserver.util.Constants.*; -import static iudx.apd.acl.server.common.HttpStatusCode.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class CatalogueClient implements CatalogueClientInterface { - private static final Logger LOGGER = LogManager.getLogger(CatalogueClient.class); - private final String catHost; - private final Integer catPort; - private final String catRelationShipPath; - private final String apdURL; - WebClient client; + private static final Logger LOGGER = LogManager.getLogger(CatalogueClient.class); + private final String catHost; + private final Integer catPort; + private final String catRelationShipPath; + private final String apdUrl; + WebClient client; - public CatalogueClient(JsonObject options) { - WebClientOptions clientOptions = - new WebClientOptions().setSsl(true).setVerifyHost(false).setTrustAll(true); - if (this.client == null) { - this.client = WebClient.create(Vertx.vertx(), clientOptions); - } - this.apdURL = options.getString(APD_URL); - this.catHost = options.getString("catServerHost"); - this.catPort = options.getInteger("catServerPort"); - this.catRelationShipPath = options.getString("dxCatalogueBasePath") + RELATIONSHIP_PATH; + public CatalogueClient(JsonObject options) { + WebClientOptions clientOptions = + new WebClientOptions().setSsl(true).setVerifyHost(false).setTrustAll(true); + if (this.client == null) { + this.client = WebClient.create(Vertx.vertx(), clientOptions); } + this.apdUrl = options.getString(APD_URL); + this.catHost = options.getString("catServerHost"); + this.catPort = options.getInteger("catServerPort"); + this.catRelationShipPath = options.getString("dxCatalogueBasePath") + RELATIONSHIP_PATH; + } - @Override - public Future> fetchItems(Set ids) { - Promise> promise = Promise.promise(); - List resourceObjList = new ArrayList<>(); - for (UUID id : ids) { - client - .get(catPort, catHost, catRelationShipPath) - .addQueryParam(ID, String.valueOf(id)) - .addQueryParam("rel", "all") - .send() - .onFailure( - ar -> { - LOGGER.error("fetchItem error : " + ar.getMessage()); - promise.fail(INTERNAL_SERVER_ERROR.getDescription()); - }) - .onSuccess( - catSuccessResponse -> { - JsonObject resultBody = catSuccessResponse.bodyAsJsonObject(); - LOGGER.info(resultBody.encodePrettily()); - if (resultBody.getString(TYPE).equals(CAT_SUCCESS_URN)) { - List resultJsonList = - resultBody.getJsonArray(RESULTS).stream() - .map(obj -> (JsonObject) obj) - .collect(Collectors.toList()); - UUID provider = null; - UUID resourceGroup = null; - String resServerUrl = null; - boolean isItemGroupLevelResource = false; - boolean isProviderId = false; - boolean isResourceServerId = false; - boolean isInvalidId = false; - String apdUrlOfResource = ""; + @Override + public Future> fetchItems(Set ids) { + Promise> promise = Promise.promise(); + List resourceObjList = new ArrayList<>(); + for (UUID id : ids) { + client + .get(catPort, catHost, catRelationShipPath) + .addQueryParam(ID, String.valueOf(id)) + .addQueryParam("rel", "all") + .send() + .onFailure( + ar -> { + LOGGER.error("fetchItem error : " + ar.getMessage()); + promise.fail(INTERNAL_SERVER_ERROR.getDescription()); + }) + .onSuccess( + catSuccessResponse -> { + JsonObject resultBody = catSuccessResponse.bodyAsJsonObject(); + LOGGER.info(resultBody.encodePrettily()); + if (resultBody.getString(TYPE).equals(CAT_SUCCESS_URN)) { + List resultJsonList = + resultBody.getJsonArray(RESULTS).stream() + .map(obj -> (JsonObject) obj) + .collect(Collectors.toList()); + UUID provider = null; + UUID resourceGroup = null; + String resServerUrl = null; + boolean isItemGroupLevelResource = false; + boolean isProviderId = false; + boolean isResourceServerId = false; + boolean isInvalidId = false; + String apdUrlOfResource = ""; - for (JsonObject resultJson : resultJsonList) { - String type = resultJson.getString(TYPE); - String idFromResponse = resultJson.getString(ID); - /* check if the id being sent is a provider id*/ - if (type.contains(PROVIDER_TAG)) { - isProviderId = idFromResponse.equals(id.toString()); - } - /* check if the id being sent is a resource server id*/ - if (type.contains(RESOURCE_SERVER_TAG)) { - isResourceServerId = idFromResponse.equals(id.toString()); - } + for (JsonObject resultJson : resultJsonList) { + String type = resultJson.getString(TYPE); + String idFromResponse = resultJson.getString(ID); + /* check if the id being sent is a provider id*/ + if (type.contains(PROVIDER_TAG)) { + isProviderId = idFromResponse.equals(id.toString()); + } + /* check if the id being sent is a resource server id*/ + if (type.contains(RESOURCE_SERVER_TAG)) { + isResourceServerId = idFromResponse.equals(id.toString()); + } - isInvalidId = isProviderId || isResourceServerId; - if (!isInvalidId - && idFromResponse != null - && idFromResponse.equals(id.toString())) { - List tags = Util.toList(resultJson.getJsonArray(TYPE)); - isItemGroupLevelResource = tags.contains(RESOURCE_GROUP_TAG); - } + isInvalidId = isProviderId || isResourceServerId; + if (!isInvalidId + && idFromResponse != null + && idFromResponse.equals(id.toString())) { + List tags = Util.toList(resultJson.getJsonArray(TYPE)); + isItemGroupLevelResource = tags.contains(RESOURCE_GROUP_TAG); + } - JsonArray typeArray = resultJson.getJsonArray(TYPE); - if (typeArray.contains(RESOURCE_GROUP_TAG)) { - resourceGroup = UUID.fromString(idFromResponse); - } else if (typeArray.contains(PROVIDER_TAG)) { - provider = UUID.fromString(resultJson.getString(OWNER_ID)); - } else if (typeArray.contains(RESOURCE_TAG)) { - resServerUrl = resultJson.getString(RS_URL); - } else if (typeArray.contains(RESOURCE_ITEM_TAG)) { - apdUrlOfResource = resultJson.getString(APD_URL); - } - } - boolean isInfoFromCatInvalid = - id == null || provider == null || resServerUrl == null; - if (isInfoFromCatInvalid && !isInvalidId) { - LOGGER.error("Something from catalogue is null. The resourceId is {}", id); - LOGGER.error("The ownerId is {}", provider); - LOGGER.error("The resource server URL is {}", resServerUrl); - String failureMessage = - generateFailureMessage( - INTERNAL_SERVER_ERROR, - ResponseUrn.INTERNAL_SERVER_ERROR, - "Something went wrong while fetching resource info from Catalogue"); + JsonArray typeArray = resultJson.getJsonArray(TYPE); + if (typeArray.contains(RESOURCE_GROUP_TAG)) { + resourceGroup = UUID.fromString(idFromResponse); + } else if (typeArray.contains(PROVIDER_TAG)) { + provider = UUID.fromString(resultJson.getString(OWNER_ID)); + } else if (typeArray.contains(RESOURCE_TAG)) { + resServerUrl = resultJson.getString(RS_URL); + } else if (typeArray.contains(RESOURCE_ITEM_TAG)) { + apdUrlOfResource = resultJson.getString(APD_URL); + } + } + boolean isInfoFromCatInvalid = + id == null || provider == null || resServerUrl == null; + if (isInfoFromCatInvalid && !isInvalidId) { + LOGGER.error("Something from catalogue is null. The resourceId is {}", id); + LOGGER.error("The ownerId is {}", provider); + LOGGER.error("The resource server URL is {}", resServerUrl); + String failureMessage = + generateFailureMessage( + INTERNAL_SERVER_ERROR, + ResponseUrn.INTERNAL_SERVER_ERROR, + "Something went wrong while fetching resource info from Catalogue"); - promise.fail(failureMessage); - } else if (isProviderId || isResourceServerId) { - LOGGER.error("isProviderId: {}", isProviderId); - LOGGER.error("isResourceServerId: {}", isResourceServerId); - String failureMessage = - generateFailureMessage( - BAD_REQUEST, - ResponseUrn.BAD_REQUEST_URN, - "Given id is invalid - it is a provider or resource server id"); + promise.fail(failureMessage); + } else if (isProviderId || isResourceServerId) { + LOGGER.error("isProviderId: {}", isProviderId); + LOGGER.error("isResourceServerId: {}", isResourceServerId); + String failureMessage = + generateFailureMessage( + BAD_REQUEST, + ResponseUrn.BAD_REQUEST_URN, + "Given id is invalid - it is a provider or resource server id"); - promise.fail(failureMessage); - } else if (isItemGroupLevelResource) { + promise.fail(failureMessage); + } else if (isItemGroupLevelResource) { - String failureMessage = - generateFailureMessage( - BAD_REQUEST, - ResponseUrn.BAD_REQUEST_URN, - "Given id is invalid - it is group level resource"); - promise.fail(failureMessage); - } - /* if the resource has an APD URL that is not equal to the current APD URL*/ - else if (!isItemGroupLevelResource && !apdURL.equals(apdUrlOfResource)) { - String failureMessage = - generateFailureMessage( - FORBIDDEN, - ResponseUrn.FORBIDDEN_URN, - "Resource is forbidden to access, as the APD URL for the resource : " - + apdUrlOfResource - + " is different than the current APD : " - + apdURL); - promise.fail(failureMessage); - } else { - ResourceObj resourceObj = - new ResourceObj( - id, provider, resourceGroup, resServerUrl, isItemGroupLevelResource); - resourceObjList.add(resourceObj); - promise.complete(resourceObjList); - } - } else { - promise.fail(resultBody.getString(DETAIL)); - } - }); - } - return promise.future(); + String failureMessage = + generateFailureMessage( + BAD_REQUEST, + ResponseUrn.BAD_REQUEST_URN, + "Given id is invalid - it is group level resource"); + promise.fail(failureMessage); + } else if (!isItemGroupLevelResource && !apdUrl.equals(apdUrlOfResource)) { + /* if the resource has an APD URL that is not equal to the current APD URL*/ + String failureMessage = + generateFailureMessage( + FORBIDDEN, + ResponseUrn.FORBIDDEN_URN, + "Resource is forbidden to access, as the APD URL for the resource : " + + apdUrlOfResource + + " is different than the current APD : " + + apdUrl); + promise.fail(failureMessage); + } else { + ResourceObj resourceObj = + new ResourceObj( + id, provider, resourceGroup, resServerUrl, isItemGroupLevelResource); + resourceObjList.add(resourceObj); + promise.complete(resourceObjList); + } + } else { + promise.fail(resultBody.getString(DETAIL)); + } + }); } + return promise.future(); + } - public String generateFailureMessage( - HttpStatusCode httpStatusCode, ResponseUrn responseUrn, String detail) { - return new JsonObject() - .put(TYPE, httpStatusCode.getValue()) - .put(TITLE, responseUrn.getUrn()) - .put(DETAIL, detail) - .encode(); - } + public String generateFailureMessage( + HttpStatusCode httpStatusCode, ResponseUrn responseUrn, String detail) { + return new JsonObject() + .put(TYPE, httpStatusCode.getValue()) + .put(TITLE, responseUrn.getUrn()) + .put(DETAIL, detail) + .encode(); + } } diff --git a/src/main/java/iudx/apd/acl/server/policy/CreatePolicy.java b/src/main/java/iudx/apd/acl/server/policy/CreatePolicy.java index b4968ce0..5914bd89 100644 --- a/src/main/java/iudx/apd/acl/server/policy/CreatePolicy.java +++ b/src/main/java/iudx/apd/acl/server/policy/CreatePolicy.java @@ -1,5 +1,9 @@ package iudx.apd.acl.server.policy; +import static iudx.apd.acl.server.apiserver.util.Constants.*; +import static iudx.apd.acl.server.common.HttpStatusCode.*; +import static iudx.apd.acl.server.policy.util.Constants.*; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonArray; @@ -13,358 +17,353 @@ import iudx.apd.acl.server.common.ResponseUrn; import iudx.apd.acl.server.policy.util.ItemType; import iudx.apd.acl.server.policy.util.Status; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.*; import java.util.stream.Collectors; - -import static iudx.apd.acl.server.apiserver.util.Constants.*; -import static iudx.apd.acl.server.common.HttpStatusCode.*; -import static iudx.apd.acl.server.policy.util.Constants.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class CreatePolicy { - private static final Logger LOGGER = LogManager.getLogger(CreatePolicy.class); - private final PostgresService postgresService; - private final CatalogueClient catalogueClient; + private static final Logger LOGGER = LogManager.getLogger(CreatePolicy.class); + private final PostgresService postgresService; + private final CatalogueClient catalogueClient; - public CreatePolicy(PostgresService postgresService, CatalogueClient catalogueClient) { - this.postgresService = postgresService; - this.catalogueClient = catalogueClient; - } + public CreatePolicy(PostgresService postgresService, CatalogueClient catalogueClient) { + this.postgresService = postgresService; + this.catalogueClient = catalogueClient; + } - public Future initiateCreatePolicy(JsonObject request, User user) { - Promise promise = Promise.promise(); - JsonArray policyList = request.getJsonArray("request"); - UUID userId = UUID.fromString(user.getUserId()); - try { - List createPolicyRequestList = - CreatePolicyRequest.jsonArrayToList(policyList, request.getLong("defaultExpiryDays")); - Set itemIdList = - createPolicyRequestList.stream() - .map(CreatePolicyRequest::getItemId) - .collect(Collectors.toSet()); - Set itemType = - createPolicyRequestList.stream() - .map(CreatePolicyRequest::getItemType) - .collect(Collectors.toSet()); + public Future initiateCreatePolicy(JsonObject request, User user) { + Promise promise = Promise.promise(); + JsonArray policyList = request.getJsonArray("request"); + UUID userId = UUID.fromString(user.getUserId()); + try { + List createPolicyRequestList = + CreatePolicyRequest.jsonArrayToList(policyList, request.getLong("defaultExpiryDays")); + Set itemIdList = + createPolicyRequestList.stream() + .map(CreatePolicyRequest::getItemId) + .collect(Collectors.toSet()); + Set itemType = + createPolicyRequestList.stream() + .map(CreatePolicyRequest::getItemType) + .collect(Collectors.toSet()); - if (itemType.contains(ItemType.RESOURCE_GROUP)) { - LOGGER.debug("Contains resource group"); - return Future.failedFuture( - generateErrorResponse(BAD_REQUEST, "Policy creation for resource group is restricted")); - } + if (itemType.contains(ItemType.RESOURCE_GROUP)) { + LOGGER.debug("Contains resource group"); + return Future.failedFuture( + generateErrorResponse(BAD_REQUEST, "Policy creation for resource group is restricted")); + } - Future> checkIfItemPresent = checkForItemsInDb(itemIdList, itemType, user); - Future isPolicyAlreadyExist = - checkIfItemPresent.compose( - providerIdSet -> { - if (providerIdSet.size() == 1 && providerIdSet.contains(userId)) { - return checkExistingPoliciesForId(createPolicyRequestList, userId); - } else { - LOGGER.error("Item does not belong to the policy creator."); - return Future.failedFuture( - generateErrorResponse( - FORBIDDEN, - "Access Denied: You do not have ownership rights for this resource.")); - } - }); + Future> checkIfItemPresent = checkForItemsInDb(itemIdList, itemType, user); + Future isPolicyAlreadyExist = + checkIfItemPresent.compose( + providerIdSet -> { + if (providerIdSet.size() == 1 && providerIdSet.contains(userId)) { + return checkExistingPoliciesForId(createPolicyRequestList, userId); + } else { + LOGGER.error("Item does not belong to the policy creator."); + return Future.failedFuture( + generateErrorResponse( + FORBIDDEN, + "Access Denied: You do not have ownership rights for this resource.")); + } + }); - Future insertPolicy = - isPolicyAlreadyExist.compose( - policyDoesNotExist -> { - return createPolicy(createPolicyRequestList, userId) - .compose( - createPolicySuccessHandler -> { - JsonArray responseArray = createResponseArray(createPolicySuccessHandler); - LOGGER.debug("Policy is created with info {}", responseArray); - JsonObject responseJson = - new JsonObject() - .put("type", ResponseUrn.SUCCESS_URN.getUrn()) - .put("title", ResponseUrn.SUCCESS_URN.getMessage()) - .put(DETAIL, "Policy created successfully"); - return Future.succeededFuture(responseJson); - }); - }); + Future insertPolicy = + isPolicyAlreadyExist.compose( + policyDoesNotExist -> { + return createPolicy(createPolicyRequestList, userId) + .compose( + createPolicySuccessHandler -> { + JsonArray responseArray = createResponseArray(createPolicySuccessHandler); + LOGGER.debug("Policy is created with info {}", responseArray); + JsonObject responseJson = + new JsonObject() + .put("type", ResponseUrn.SUCCESS_URN.getUrn()) + .put("title", ResponseUrn.SUCCESS_URN.getMessage()) + .put(DETAIL, "Policy created successfully"); + return Future.succeededFuture(responseJson); + }); + }); - insertPolicy - .onSuccess(promise::complete) - .onFailure( - f -> { - LOGGER.info("Policy could not be created {}", f.getLocalizedMessage()); - promise.fail(f); - }); - } catch (IllegalArgumentException e) { - promise.fail(generateErrorResponse(BAD_REQUEST, e.getMessage())); - } - return promise.future(); + insertPolicy + .onSuccess(promise::complete) + .onFailure( + f -> { + LOGGER.info("Policy could not be created {}", f.getLocalizedMessage()); + promise.fail(f); + }); + } catch (IllegalArgumentException e) { + promise.fail(generateErrorResponse(BAD_REQUEST, e.getMessage())); } + return promise.future(); + } - private Future> checkForItemsInDb( - Set itemIdList, Set itemTypeRequest, User user) { - Promise> promise = Promise.promise(); + private Future> checkForItemsInDb( + Set itemIdList, Set itemTypeRequest, User user) { + Promise> promise = Promise.promise(); - postgresService - .getPool() - .withConnection( - sqlConnection -> - sqlConnection - .preparedQuery(ENTITY_TABLE_CHECK) - .execute(Tuple.of(itemIdList.toArray(UUID[]::new))) - .onFailure( - existingIdFailureHandler -> { - LOGGER.error( - "checkForItemsInDb db fail {}", - existingIdFailureHandler.getLocalizedMessage()); - promise.fail( - generateErrorResponse( - INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); - }) - .onSuccess( - existingIdSuccessHandler -> { - Set providerIdSet = new HashSet<>(); - Set existingItemIds = new HashSet<>(); - Set itemTypeDb = new HashSet<>(); - Set rsServerUrlSetDb = new HashSet<>(); - if (existingIdSuccessHandler.size() > 0) { - for (Row row : existingIdSuccessHandler) { - providerIdSet.add(row.getUUID("provider_id")); - existingItemIds.add(row.getUUID("_id")); - itemTypeDb.add(ItemType.valueOf(row.getString("item_type"))); - rsServerUrlSetDb.add(row.getString("resource_server_url")); - } - itemIdList.removeAll(existingItemIds); - } - if (!itemIdList.isEmpty()) { - Future> resourceObjList = - catalogueClient.fetchItems(itemIdList); - Future> providerIdsFromCat = - resourceObjList - .compose( - success -> { - Set itemTypeCat = - success.stream() - .map(ResourceObj::getItemType) - .collect(Collectors.toSet()); - Set rsServerUrlCat = - success.stream() - .map(ResourceObj::getResourceServerUrl) - .collect(Collectors.toSet()); - if (!itemTypeRequest.containsAll(itemTypeCat)) { - return Future.failedFuture("Invalid item type."); - } else if (!rsServerUrlCat.contains( - user.getResourceServerUrl())) { - return Future.failedFuture(generateErrorResponse( - FORBIDDEN, - "Access Denied: You do not have ownership rights for this resource.")); - } else { - return insertItemsIntoDb(success); - } - }) - .onFailure( - failureHandler -> { - String failureMessage = failureHandler.getMessage(); - if (failureMessage.contains(TYPE) - && failureMessage.contains(TITLE)) { - promise.fail(failureHandler.getMessage()); - } else { - promise.fail( - generateErrorResponse(BAD_REQUEST, failureMessage)); - } - }); - providerIdsFromCat - .onSuccess( - insertItemsSuccessHandler -> { - providerIdSet.addAll(insertItemsSuccessHandler); - promise.complete(providerIdSet); - }) - .onFailure( - insertItemsFailureHandler -> { - LOGGER.error( - "insertItemInDbFail " - + insertItemsFailureHandler.getLocalizedMessage()); - - promise.tryFail( - insertItemsFailureHandler - .getLocalizedMessage() - .equalsIgnoreCase( - "Access Denied: You do not have " - + "ownership rights for this resource.") - ? generateErrorResponse( - FORBIDDEN, - insertItemsFailureHandler.getLocalizedMessage()) - : generateErrorResponse( - BAD_REQUEST, - insertItemsFailureHandler.getLocalizedMessage())); - }); - } else { - if (!itemTypeDb.containsAll(itemTypeRequest)) { - promise.fail( - generateErrorResponse(BAD_REQUEST, "Invalid item type.")); - } else if (!rsServerUrlSetDb.contains(user.getResourceServerUrl())) { - promise.fail( - generateErrorResponse( - FORBIDDEN, - "Access Denied: You do not have ownership rights for this resource.")); - } else { - promise.complete(providerIdSet); - } - } - })); - return promise.future(); - } + postgresService + .getPool() + .withConnection( + sqlConnection -> + sqlConnection + .preparedQuery(ENTITY_TABLE_CHECK) + .execute(Tuple.of(itemIdList.toArray(UUID[]::new))) + .onFailure( + existingIdFailureHandler -> { + LOGGER.error( + "checkForItemsInDb db fail {}", + existingIdFailureHandler.getLocalizedMessage()); + promise.fail( + generateErrorResponse( + INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); + }) + .onSuccess( + existingIdSuccessHandler -> { + Set providerIdSet = new HashSet<>(); + Set existingItemIds = new HashSet<>(); + Set itemTypeDb = new HashSet<>(); + Set rsServerUrlSetDb = new HashSet<>(); + if (existingIdSuccessHandler.size() > 0) { + for (Row row : existingIdSuccessHandler) { + providerIdSet.add(row.getUUID("provider_id")); + existingItemIds.add(row.getUUID("_id")); + itemTypeDb.add(ItemType.valueOf(row.getString("item_type"))); + rsServerUrlSetDb.add(row.getString("resource_server_url")); + } + itemIdList.removeAll(existingItemIds); + } + if (!itemIdList.isEmpty()) { + Future> resourceObjList = + catalogueClient.fetchItems(itemIdList); + Future> providerIdsFromCat = + resourceObjList + .compose( + success -> { + Set itemTypeCat = + success.stream() + .map(ResourceObj::getItemType) + .collect(Collectors.toSet()); + Set rsServerUrlCat = + success.stream() + .map(ResourceObj::getResourceServerUrl) + .collect(Collectors.toSet()); + if (!itemTypeRequest.containsAll(itemTypeCat)) { + return Future.failedFuture("Invalid item type."); + } else if (!rsServerUrlCat.contains( + user.getResourceServerUrl())) { + return Future.failedFuture(generateErrorResponse( + FORBIDDEN, + "Access Denied: You do not have ownership rights for this resource.")); + } else { + return insertItemsIntoDb(success); + } + }) + .onFailure( + failureHandler -> { + String failureMessage = failureHandler.getMessage(); + if (failureMessage.contains(TYPE) + && failureMessage.contains(TITLE)) { + promise.fail(failureHandler.getMessage()); + } else { + promise.fail( + generateErrorResponse(BAD_REQUEST, failureMessage)); + } + }); + providerIdsFromCat + .onSuccess( + insertItemsSuccessHandler -> { + providerIdSet.addAll(insertItemsSuccessHandler); + promise.complete(providerIdSet); + }) + .onFailure( + insertItemsFailureHandler -> { + LOGGER.error( + "insertItemInDbFail " + + insertItemsFailureHandler.getLocalizedMessage()); - private Future> insertItemsIntoDb(List resourceObjList) { - Promise> promise = Promise.promise(); - List batch = new ArrayList<>(); - Set providerIdSet = - resourceObjList.stream().map(ResourceObj::getProviderId).collect(Collectors.toSet()); + promise.tryFail( + insertItemsFailureHandler + .getLocalizedMessage() + .equalsIgnoreCase( + "Access Denied: You do not have " + + "ownership rights for this resource.") + ? generateErrorResponse( + FORBIDDEN, + insertItemsFailureHandler.getLocalizedMessage()) + : generateErrorResponse( + BAD_REQUEST, + insertItemsFailureHandler.getLocalizedMessage())); + }); + } else { + if (!itemTypeDb.containsAll(itemTypeRequest)) { + promise.fail( + generateErrorResponse(BAD_REQUEST, "Invalid item type.")); + } else if (!rsServerUrlSetDb.contains(user.getResourceServerUrl())) { + promise.fail( + generateErrorResponse( + FORBIDDEN, + "Access Denied: You do not have ownership rights for this resource.")); + } else { + promise.complete(providerIdSet); + } + } + })); + return promise.future(); + } - for (ResourceObj resourceObj : resourceObjList) { - UUID id = resourceObj.getItemId(); - UUID provider = resourceObj.getProviderId(); - UUID resourceGroupId = resourceObj.getResourceGroupId(); - ItemType itemType = resourceObj.getItemType(); - String resourceServerUrl = resourceObj.getResourceServerUrl(); - batch.add(Tuple.of(id, provider, resourceGroupId, itemType, resourceServerUrl)); - } + private Future> insertItemsIntoDb(List resourceObjList) { + Promise> promise = Promise.promise(); + List batch = new ArrayList<>(); + Set providerIdSet = + resourceObjList.stream().map(ResourceObj::getProviderId).collect(Collectors.toSet()); - postgresService - .getPool() - .withConnection( - sqlConnection -> - sqlConnection - .preparedQuery(INSERT_ENTITY_TABLE) - .executeBatch(batch) - .onFailure( - dbHandler -> { - LOGGER.error( - "insertItemsIntoDb db fail " + dbHandler.getLocalizedMessage()); - }) - .onSuccess( - dbSuccessHandler -> { - promise.complete(providerIdSet); - })); - return promise.future(); + for (ResourceObj resourceObj : resourceObjList) { + UUID id = resourceObj.getItemId(); + UUID provider = resourceObj.getProviderId(); + UUID resourceGroupId = resourceObj.getResourceGroupId(); + ItemType itemType = resourceObj.getItemType(); + String resourceServerUrl = resourceObj.getResourceServerUrl(); + batch.add(Tuple.of(id, provider, resourceGroupId, itemType, resourceServerUrl)); } - private Future checkExistingPoliciesForId( - List createPolicyRequestList, UUID providerId) { - List selectTuples = - createPolicyRequestList.stream() - .map( - createPolicyRequest -> - Tuple.of( - createPolicyRequest.getItemId(), - providerId, - Status.ACTIVE, - createPolicyRequest.getUserEmail())) - .collect(Collectors.toList()); - Promise promise = Promise.promise(); - postgresService - .getPool() - .withTransaction( - conn -> - conn.preparedQuery(CHECK_EXISTING_POLICY) - .executeBatch(selectTuples) - .onFailure( - failureHandler -> { - LOGGER.error( - "isPolicyForIdExist fail :: " + failureHandler.getLocalizedMessage()); - promise.fail( - generateErrorResponse( - INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); - }) - .onSuccess( - policyExists -> { - if (policyExists.size() > 0) { - List responseArray = new ArrayList<>(); - for (RowSet rowSet = policyExists; - rowSet != null; - rowSet = rowSet.next()) { - rowSet.forEach(row -> responseArray.add(row.getUUID("_id"))); - } - LOGGER.error("Policy already Exist."); - promise.fail( - generateErrorResponse( - CONFLICT, - "Policy already exist for some of the request objects " - + responseArray)); - } else { - promise.complete(false); - } - })); + postgresService + .getPool() + .withConnection( + sqlConnection -> + sqlConnection + .preparedQuery(INSERT_ENTITY_TABLE) + .executeBatch(batch) + .onFailure( + dbHandler -> { + LOGGER.error( + "insertItemsIntoDb db fail " + dbHandler.getLocalizedMessage()); + }) + .onSuccess( + dbSuccessHandler -> { + promise.complete(providerIdSet); + })); + return promise.future(); + } - return promise.future(); - } + private Future checkExistingPoliciesForId( + List createPolicyRequestList, UUID providerId) { + List selectTuples = + createPolicyRequestList.stream() + .map( + createPolicyRequest -> + Tuple.of( + createPolicyRequest.getItemId(), + providerId, + Status.ACTIVE, + createPolicyRequest.getUserEmail())) + .collect(Collectors.toList()); + Promise promise = Promise.promise(); + postgresService + .getPool() + .withTransaction( + conn -> + conn.preparedQuery(CHECK_EXISTING_POLICY) + .executeBatch(selectTuples) + .onFailure( + failureHandler -> { + LOGGER.error( + "isPolicyForIdExist fail :: " + failureHandler.getLocalizedMessage()); + promise.fail( + generateErrorResponse( + INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); + }) + .onSuccess( + policyExists -> { + if (policyExists.size() > 0) { + List responseArray = new ArrayList<>(); + for (RowSet rowSet = policyExists; + rowSet != null; + rowSet = rowSet.next()) { + rowSet.forEach(row -> responseArray.add(row.getUUID("_id"))); + } + LOGGER.error("Policy already Exist."); + promise.fail( + generateErrorResponse( + CONFLICT, + "Policy already exist for some of the request objects " + + responseArray)); + } else { + promise.complete(false); + } + })); - Future> createPolicy(List createPolicyRequestList, UUID userId) { - Promise> promise = Promise.promise(); - List createPolicyTuple = - createPolicyRequestList.stream() - .map( - createPolicyRequest -> - Tuple.of( - createPolicyRequest.getUserEmail(), - createPolicyRequest.getItemId(), - userId, - createPolicyRequest.getExpiryTime(), - createPolicyRequest.getConstraints())) - .collect(Collectors.toList()); + return promise.future(); + } - postgresService - .getPool() - .withTransaction( - conn -> { - // Execute the batch query to create policies - return conn.preparedQuery(CREATE_POLICY_QUERY) - .executeBatch(createPolicyTuple) - .onFailure( - failureHandler -> { - LOGGER.error( - "createPolicy fail :: " + failureHandler.getLocalizedMessage()); - // Fail the promise with an error response - promise.fail( - generateErrorResponse( - INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); - }) - .onSuccess(promise::complete); - }); + Future> createPolicy(List createPolicyRequestList, UUID userId) { + Promise> promise = Promise.promise(); + List createPolicyTuple = + createPolicyRequestList.stream() + .map( + createPolicyRequest -> + Tuple.of( + createPolicyRequest.getUserEmail(), + createPolicyRequest.getItemId(), + userId, + createPolicyRequest.getExpiryTime(), + createPolicyRequest.getConstraints())) + .collect(Collectors.toList()); - return promise.future(); - } + postgresService + .getPool() + .withTransaction( + conn -> { + // Execute the batch query to create policies + return conn.preparedQuery(CREATE_POLICY_QUERY) + .executeBatch(createPolicyTuple) + .onFailure( + failureHandler -> { + LOGGER.error( + "createPolicy fail :: " + failureHandler.getLocalizedMessage()); + // Fail the promise with an error response + promise.fail( + generateErrorResponse( + INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); + }) + .onSuccess(promise::complete); + }); - private String generateErrorResponse(HttpStatusCode httpStatusCode, String errorMessage) { - return new JsonObject() - .put(TYPE, httpStatusCode.getValue()) - .put(TITLE, httpStatusCode.getUrn()) - .put(DETAIL, errorMessage) - .encode(); - } + return promise.future(); + } - private JsonArray createResponseArray(RowSet rows) { - JsonArray response = new JsonArray(); - final JsonObject[] ownerJsonObject = {null}; + private String generateErrorResponse(HttpStatusCode httpStatusCode, String errorMessage) { + return new JsonObject() + .put(TYPE, httpStatusCode.getValue()) + .put(TITLE, httpStatusCode.getUrn()) + .put(DETAIL, errorMessage) + .encode(); + } - for (RowSet rowSet = rows; rowSet != null; rowSet = rowSet.next()) { - rowSet.forEach( - row -> { - JsonObject jsonObject = - new JsonObject() - .put("policyId", row.getUUID("_id").toString()) - .put("userEmailId", row.getString("user_emailid")) - .put("itemId", row.getUUID("item_id").toString()) - .put("expiryAt", row.getLocalDateTime("expiry_at").toString()); + private JsonArray createResponseArray(RowSet rows) { + JsonArray response = new JsonArray(); + final JsonObject[] ownerJsonObject = {null}; - if (ownerJsonObject[0] == null) { - ownerJsonObject[0] = - new JsonObject().put("ownerId", row.getValue("owner_id").toString()); - } - response.add(jsonObject); - }); - } + for (RowSet rowSet = rows; rowSet != null; rowSet = rowSet.next()) { + rowSet.forEach( + row -> { + JsonObject jsonObject = + new JsonObject() + .put("policyId", row.getUUID("_id").toString()) + .put("userEmailId", row.getString("user_emailid")) + .put("itemId", row.getUUID("item_id").toString()) + .put("expiryAt", row.getLocalDateTime("expiry_at").toString()); - response.add(ownerJsonObject[0]); - return response; + if (ownerJsonObject[0] == null) { + ownerJsonObject[0] = + new JsonObject().put("ownerId", row.getValue("owner_id").toString()); + } + response.add(jsonObject); + }); } + + response.add(ownerJsonObject[0]); + return response; + } }