From 03b6cc29715f64ec15838511b92a918d97b716c8 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 11:10:26 +0530 Subject: [PATCH 01/15] Refactor: resolve checkstyle issue --- .../apiserver/ApiServerVerticle.java | 63 ++- .../marketplace/apiserver/ConsumerApis.java | 109 +++-- .../marketplace/apiserver/ProviderApis.java | 56 +-- .../exceptions/DxRuntimeException.java | 1 - .../apiserver/handlers/AuthHandler.java | 10 +- .../apiserver/handlers/ExceptionHandler.java | 11 +- .../apiserver/handlers/ValidationHandler.java | 4 +- .../linkedAccount/CreateLinkedAccount.java | 7 +- .../linkedAccount/FetchLinkedAccount.java | 13 +- .../linkedAccount/LinkedAccountService.java | 73 +-- .../LinkedAccountServiceImpl.java | 36 +- .../linkedAccount/LinkedAccountVerticle.java | 5 +- .../linkedAccount/UpdateLinkedAccount.java | 190 ++++---- .../apiserver/response/ResponseUtil.java | 26 +- .../apiserver/response/RestResponse.java | 122 ++--- .../apiserver/util/RequestType.java | 8 +- .../data/marketplace/apiserver/util/Role.java | 7 +- .../validation/ValidationHandlerFactory.java | 23 +- .../types/JsonSchemaTypeValidator.java | 20 +- .../types/VariantNameTypeValidator.java | 2 +- .../marketplace/auditing/AuditingService.java | 3 +- .../auditing/AuditingServiceImpl.java | 26 +- .../auditing/AuditingVerticle.java | 141 +++--- .../databroker/DataBrokerService.java | 3 +- .../databroker/DataBrokerServiceImpl.java | 74 ++-- .../authenticator/AuthenticationService.java | 24 +- .../AuthenticationServiceImpl.java | 10 +- .../authenticator/AuthenticationVerticle.java | 4 +- .../AuthorizationContextFactory.java | 18 +- .../authorization/AuthorizationRequest.java | 1 - .../authorization/ConsumerAuthStatergy.java | 5 +- .../authenticator/authorization/IudxRole.java | 8 +- .../authorization/ProviderAuthStatergy.java | 19 +- .../authenticator/model/JwtData.java | 44 +- .../iudx/data/marketplace/common/Api.java | 13 +- .../marketplace/common/CatalogueService.java | 19 +- .../marketplace/common/HttpStatusCode.java | 14 +- .../data/marketplace/common/RespBuilder.java | 5 +- .../data/marketplace/common/ResponseUrn.java | 14 +- .../marketplace/consumer/ConsumerService.java | 24 +- .../consumer/ConsumerServiceImpl.java | 3 +- .../consumer/ConsumerVerticle.java | 5 +- .../consumer/util/PaymentStatus.java | 10 +- .../data/marketplace/deploy/Deployer.java | 227 ++++++---- .../marketplace/policies/CreatePolicy.java | 1 - .../marketplace/policies/DeletePolicy.java | 25 +- .../policies/FetchPolicyUsingPvId.java | 1 + .../data/marketplace/policies/GetPolicy.java | 3 +- .../marketplace/policies/PolicyService.java | 1 + .../policies/PolicyServiceImpl.java | 182 ++++---- .../marketplace/policies/PolicyVerticle.java | 3 +- .../marketplace/policies/VerifyPolicy.java | 116 +++-- .../marketplace/policies/util/Status.java | 5 +- .../marketplace/postgres/PostgresService.java | 22 +- .../postgres/PostgresServiceImpl.java | 65 ++- .../marketplace/product/ProductService.java | 14 +- .../product/ProductServiceImpl.java | 21 +- .../marketplace/product/ProductVerticle.java | 16 +- .../product/util/QueryBuilder.java | 415 +++++++++--------- .../variant/ProductVariantService.java | 41 +- .../variant/ProductVariantServiceImpl.java | 8 +- .../variant/ProductVariantVerticle.java | 8 +- .../marketplace/razorpay/RazorPayService.java | 55 ++- .../razorpay/RazorPayServiceImpl.java | 2 +- .../marketplace/webhook/WebhookService.java | 25 +- .../webhook/WebhookServiceImpl.java | 6 +- .../marketplace/webhook/WebhookVerticle.java | 6 +- 67 files changed, 1321 insertions(+), 1220 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index fca5b1f1..51ec84aa 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -167,7 +167,6 @@ public void start() throws Exception { server = vertx.createHttpServer(serverOptions); server.requestHandler(router).listen(port); - router .route(PROVIDER_PATH + "/*") .subRouter( @@ -180,7 +179,8 @@ public void start() throws Exception { .init()); ExceptionHandler exceptionHandler = new ExceptionHandler(); - ValidationHandler checkPolicyValidationHandler = new ValidationHandler(vertx, RequestType.CHECK_POLICY); + ValidationHandler checkPolicyValidationHandler = + new ValidationHandler(vertx, RequestType.CHECK_POLICY); ValidationHandler verifyValidationHandler = new ValidationHandler(vertx, RequestType.VERIFY); ValidationHandler postLinkedAccountHandler = new ValidationHandler(vertx, RequestType.POST_ACCOUNT); @@ -193,7 +193,6 @@ public void start() throws Exception { .handler(this::getPoliciesHandler) .failureHandler(exceptionHandler); - router .post(api.getProductUserMapsPath()) .handler(this::mapUserToProduct) @@ -235,12 +234,12 @@ public void start() throws Exception { .handler(this::handleFetchLinkedAccount) .failureHandler(exceptionHandler); - router - .get(api.getCheckPolicyPath()) - .handler(checkPolicyValidationHandler) - .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) - .handler(this::checkPolicyHandler) - .failureHandler(exceptionHandler); + router + .get(api.getCheckPolicyPath()) + .handler(checkPolicyValidationHandler) + .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) + .handler(this::checkPolicyHandler) + .failureHandler(exceptionHandler); /*Webhook routes */ @@ -308,25 +307,24 @@ private void setServerOptions(HttpServerOptions serverOptions) { port = config().getInteger("httpPort") == null ? 8080 : config().getInteger("httpPort"); } - private void checkPolicyHandler(RoutingContext routingContext) { - HttpServerResponse response = routingContext.response(); - - User user = routingContext.get("user"); - String productVariantId = routingContext.request().getParam("productVariantId"); - policyService - .checkPolicy(productVariantId, user) - .onComplete( - handler -> { - if (handler.succeeded()) { - int statusCode = handler.result().getInteger(STATUS_CODE); - String result = handler.result().getJsonObject(RESULTS).encode(); - handleSuccessResponse(response, statusCode, result); - } else { - handleFailureResponse(routingContext, handler.cause().getMessage()); - } - }); - } + HttpServerResponse response = routingContext.response(); + + User user = routingContext.get("user"); + String productVariantId = routingContext.request().getParam("productVariantId"); + policyService + .checkPolicy(productVariantId, user) + .onComplete( + handler -> { + if (handler.succeeded()) { + int statusCode = handler.result().getInteger(STATUS_CODE); + String result = handler.result().getJsonObject(RESULTS).encode(); + handleSuccessResponse(response, statusCode, result); + } else { + handleFailureResponse(routingContext, handler.cause().getMessage()); + } + }); + } private void handleWebhookSignatureValidation(RoutingContext routingContext) { @@ -423,11 +421,10 @@ private void handleVerifyPayment(RoutingContext routingContext) { }) .onFailure( verifyFailed -> { - handleResponse(response, BAD_REQUEST.getValue(), verifyFailed.getMessage()); + handleResponse(response, BAD_REQUEST.getValue(), verifyFailed.getMessage()); }); } - private void printDeployedEndpoints(Router router) { for (Route route : router.getRoutes()) { if (route.getPath() != null) { @@ -436,7 +433,6 @@ private void printDeployedEndpoints(Router router) { } } - private void getPoliciesHandler(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); @@ -545,9 +541,10 @@ private void handleVerify(RoutingContext routingContext) { private void handleSuccessResponse(HttpServerResponse response, int statusCode, String result) { response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); } - private void handleResponse(HttpServerResponse response, int statusCode, String result) { - response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); - } + + private void handleResponse(HttpServerResponse response, int statusCode, String result) { + response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); + } /** * Handles Failed HTTP Response diff --git a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java index 13561ad6..eb3c41cb 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java @@ -42,7 +42,13 @@ public class ConsumerApis { private AuthClient authClient; private AuthenticationService authenticationService; - ConsumerApis(Vertx vertx, Router router, Api apis, PostgresService postgresService, AuthClient authClient, AuthenticationService authenticationService) { + ConsumerApis( + Vertx vertx, + Router router, + Api apis, + PostgresService postgresService, + AuthClient authClient, + AuthenticationService authenticationService) { this.vertx = vertx; this.router = router; this.api = apis; @@ -53,12 +59,13 @@ public class ConsumerApis { Router init() { - ValidationHandler resourceValidationHandler = new ValidationHandler(vertx, RequestType.RESOURCE); + ValidationHandler resourceValidationHandler = + new ValidationHandler(vertx, RequestType.RESOURCE); ValidationHandler providerValidationHandler = new ValidationHandler(vertx, RequestType.PROVIDER); ValidationHandler orderValidationHandler = new ValidationHandler(vertx, RequestType.ORDER); ValidationHandler purchaseValidationHandler = - new ValidationHandler(vertx, RequestType.PURCHASE); + new ValidationHandler(vertx, RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); ValidationHandler productVariantHandler = new ValidationHandler(vertx, RequestType.PRODUCT); @@ -92,8 +99,8 @@ Router init() { .handler(this::listPurchases) .failureHandler(exceptionHandler); - router - .get(api.getConsumerProductVariantPath()) + router + .get(api.getConsumerProductVariantPath()) .handler(productVariantHandler) .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::listProductVariants) @@ -115,18 +122,22 @@ private void createOrder(RoutingContext routingContext) { LOGGER.debug(variantId); - JsonObject requestBody = new JsonObject() - .put(AUTH_INFO, routingContext.data().get(AUTH_INFO)) - .put(PRODUCT_VARIANT_ID, variantId); + JsonObject requestBody = + new JsonObject() + .put(AUTH_INFO, routingContext.data().get(AUTH_INFO)) + .put(PRODUCT_VARIANT_ID, variantId); User user = routingContext.get("user"); - consumerService.createOrder(requestBody, user, handler -> { - if(handler.succeeded()) { - handleSuccessResponse(routingContext, 201, handler.result()); - } else { - handleFailureResponse(routingContext, handler.cause()); - } - }); + consumerService.createOrder( + requestBody, + user, + handler -> { + if (handler.succeeded()) { + handleSuccessResponse(routingContext, 201, handler.result()); + } else { + handleFailureResponse(routingContext, handler.cause()); + } + }); } private void listProviders(RoutingContext routingContext) { @@ -141,10 +152,10 @@ private void listProviders(RoutingContext routingContext) { User consumer = routingContext.get("user"); consumerService.listProviders( - consumer, + consumer, requestBody, handler -> { - if (handler.succeeded()) { + if (handler.succeeded()) { if (handler.result().getJsonArray(RESULTS).isEmpty()) { handleSuccessResponse(routingContext, 204, handler.result()); } else { @@ -168,7 +179,7 @@ private void listResources(RoutingContext routingContext) { requestBody.put(AUTH_INFO, authInfo); consumerService.listResources( - consumer, + consumer, requestBody, handler -> { if (handler.succeeded()) { @@ -188,8 +199,7 @@ private void listProductVariants(RoutingContext routingContext) { User consumer = routingContext.get("user"); MultiMap requestParams = routingContext.request().params(); String productId = requestParams.get("productId"); - JsonObject requestJson = - new JsonObject().put("productId", productId); + JsonObject requestJson = new JsonObject().put("productId", productId); consumerService.listProductVariants( consumer, @@ -216,7 +226,7 @@ private void listProducts(RoutingContext routingContext) { User consumer = routingContext.get("user"); consumerService.listProducts( - consumer, + consumer, requestBody, handler -> { if (handler.succeeded()) { @@ -238,18 +248,22 @@ private void listPurchases(RoutingContext routingContext) { String productId = requestParams.get("productId"); String paymentStatus = requestParams.get("paymentStatus"); JsonObject requestJson = - new JsonObject().put("resourceId", resourceId).put("productId", productId).put("paymentStatus", paymentStatus); + new JsonObject() + .put("resourceId", resourceId) + .put("productId", productId) + .put("paymentStatus", paymentStatus); - consumerService.listPurchase(consumer,requestJson, handler -> { - if(handler.succeeded()) - { - handleSuccessResponse(routingContext, HttpStatusCode.SUCCESS.getValue(), handler.result()); - } - else - { - handleFailureResponse(routingContext, handler.cause().getMessage()); - } - }); + consumerService.listPurchase( + consumer, + requestJson, + handler -> { + if (handler.succeeded()) { + handleSuccessResponse( + routingContext, HttpStatusCode.SUCCESS.getValue(), handler.result()); + } else { + handleFailureResponse(routingContext, handler.cause().getMessage()); + } + }); } private void handleFailureResponse(RoutingContext routingContext, Throwable cause) { @@ -309,16 +323,16 @@ private void handleFailureResponse(RoutingContext routingContext, String failure urn = ResponseUrn.fromCode(String.valueOf(type)); } if (jsonObject.getString(DETAIL) != null) { - String detail = jsonObject.getString(DETAIL); + String detail = jsonObject.getString(DETAIL); response - .putHeader(CONTENT_TYPE, APPLICATION_JSON) - .setStatusCode(type) - .end(generateResponse(status, urn, detail).toString()); + .putHeader(CONTENT_TYPE, APPLICATION_JSON) + .setStatusCode(type) + .end(generateResponse(status, urn, detail).toString()); } else { response - .putHeader(CONTENT_TYPE, APPLICATION_JSON) - .setStatusCode(type) - .end(generateResponse(status, urn).toString()); + .putHeader(CONTENT_TYPE, APPLICATION_JSON) + .setStatusCode(type) + .end(generateResponse(status, urn).toString()); } } catch (DecodeException exception) { @@ -328,19 +342,18 @@ private void handleFailureResponse(RoutingContext routingContext, String failure } private void handleResponse( - HttpServerResponse response, HttpStatusCode statusCode, ResponseUrn urn) { + HttpServerResponse response, HttpStatusCode statusCode, ResponseUrn urn) { handleResponse(response, statusCode, urn, statusCode.getDescription()); } private void handleResponse( - HttpServerResponse response, - HttpStatusCode statusCode, - ResponseUrn urn, - String failureMessage) { + HttpServerResponse response, + HttpStatusCode statusCode, + ResponseUrn urn, + String failureMessage) { response - .putHeader(CONTENT_TYPE, APPLICATION_JSON) - .setStatusCode(statusCode.getValue()) - .end(generateResponse(statusCode, urn, failureMessage).toString()); + .putHeader(CONTENT_TYPE, APPLICATION_JSON) + .setStatusCode(statusCode.getValue()) + .end(generateResponse(statusCode, urn, failureMessage).toString()); } - } diff --git a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java index bc8e75ce..fd363c8f 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java @@ -68,9 +68,9 @@ Router init() { ValidationHandler variantValidationHandler = new ValidationHandler(vertx, RequestType.PRODUCT_VARIANT); ValidationHandler deleteVariantValidationHandler = - new ValidationHandler(vertx, RequestType.DELETE_PRODUCT_VARIANT); + new ValidationHandler(vertx, RequestType.DELETE_PRODUCT_VARIANT); ValidationHandler listVariantValidationHandler = - new ValidationHandler(vertx, RequestType.LIST_PRODUCT_VARIANT); + new ValidationHandler(vertx, RequestType.LIST_PRODUCT_VARIANT); ValidationHandler resourceValidationHandler = new ValidationHandler(vertx, RequestType.RESOURCE); ValidationHandler purchaseValidationHandler = @@ -162,11 +162,10 @@ private void handleCreateProduct(RoutingContext routingContext) { } else if (errorMessage.contains(ResponseUrn.INTERNAL_SERVER_ERR_URN.getMessage())) { routingContext.fail( new DxRuntimeException(500, ResponseUrn.INTERNAL_SERVER_ERR_URN, errorMessage)); - } else if( errorMessage.contains(ResponseUrn.FORBIDDEN_URN.getUrn())) - { - handleFailureResponse(routingContext, errorMessage, HttpStatusCode.FORBIDDEN.getValue()); - } - else { + } else if (errorMessage.contains(ResponseUrn.FORBIDDEN_URN.getUrn())) { + handleFailureResponse( + routingContext, errorMessage, HttpStatusCode.FORBIDDEN.getValue()); + } else { handleFailureResponse(routingContext, handler.cause()); } } @@ -233,18 +232,21 @@ private void listPurchases(RoutingContext routingContext) { String productId = requestParams.get("productId"); String paymentStatus = requestParams.get("paymentStatus"); JsonObject requestJson = - new JsonObject().put("resourceId", resourceId).put("productId", productId).put("paymentStatus", paymentStatus); - variantService - .listPurchase(provider, requestJson, handler -> { - if(handler.succeeded()) - { - handleSuccessResponse(routingContext, HttpStatusCode.SUCCESS.getValue(), handler.result()); - } - else - { - handleFailure(routingContext, handler.cause().getMessage()); - } - }); + new JsonObject() + .put("resourceId", resourceId) + .put("productId", productId) + .put("paymentStatus", paymentStatus); + variantService.listPurchase( + provider, + requestJson, + handler -> { + if (handler.succeeded()) { + handleSuccessResponse( + routingContext, HttpStatusCode.SUCCESS.getValue(), handler.result()); + } else { + handleFailure(routingContext, handler.cause().getMessage()); + } + }); } private void handleCreateProductVariant(RoutingContext routingContext) { @@ -268,7 +270,7 @@ private void handleCreateProductVariant(RoutingContext routingContext) { ResponseUrn.RESOURCE_ALREADY_EXISTS_URN, ResponseUrn.RESOURCE_ALREADY_EXISTS_URN.getMessage())); - } else if (errMessage.contains(ResponseUrn.FORBIDDEN_URN.getUrn())){ + } else if (errMessage.contains(ResponseUrn.FORBIDDEN_URN.getUrn())) { handleFailureResponse( routingContext, errMessage, HttpStatusCode.FORBIDDEN.getValue()); } else { @@ -335,8 +337,7 @@ private void handleDeleteProductVariant(RoutingContext routingContext) { if (handler.succeeded()) { handleSuccessResponse(routingContext, 200, handler.result()); } else { - handleFailure( - routingContext, handler.cause().getMessage()); + handleFailure(routingContext, handler.cause().getMessage()); } }); } @@ -349,12 +350,13 @@ private void handleFailureResponse(RoutingContext routingContext, Throwable caus .end(cause.getMessage()); } - private void handleFailureResponse(RoutingContext routingContext, String failureMessage, int statusCode) { + private void handleFailureResponse( + RoutingContext routingContext, String failureMessage, int statusCode) { routingContext - .response() - .putHeader(CONTENT_TYPE, APPLICATION_JSON) - .setStatusCode(statusCode) - .end(failureMessage); + .response() + .putHeader(CONTENT_TYPE, APPLICATION_JSON) + .setStatusCode(statusCode) + .end(failureMessage); } private void handleFailure(RoutingContext routingContext, String failureMessage) { diff --git a/src/main/java/iudx/data/marketplace/apiserver/exceptions/DxRuntimeException.java b/src/main/java/iudx/data/marketplace/apiserver/exceptions/DxRuntimeException.java index 20b57633..f418db47 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/exceptions/DxRuntimeException.java +++ b/src/main/java/iudx/data/marketplace/apiserver/exceptions/DxRuntimeException.java @@ -1,4 +1,3 @@ - package iudx.data.marketplace.apiserver.exceptions; import iudx.data.marketplace.common.ResponseUrn; diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java index 002307b9..86e73b13 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java @@ -129,7 +129,7 @@ Future checkAuth(JsonObject request, JsonObject authInfo) { return promise.future(); } - Future getUserInfo(JsonObject tokenIntrospectResult) { + Future getUserInfo(JsonObject tokenIntrospectResult) { LOGGER.info("Getting user info.."); Promise promise = Promise.promise(); UserContainer userContainer = new UserContainer(); @@ -242,13 +242,13 @@ private String getNormalisedPath(String url) { return api.getConsumerListProducts(); } else if (url.contains(api.getConsumerOrderApi())) { return api.getConsumerOrderApi(); - } else if(url.matches(api.getLinkedAccountService())){ + } else if (url.matches(api.getLinkedAccountService())) { return api.getLinkedAccountService(); - } else if(url.matches(api.getConsumerListResourcePath())) { + } else if (url.matches(api.getConsumerListResourcePath())) { return api.getConsumerListResourcePath(); - } else if(url.matches(api.getConsumerProductVariantPath())) { + } else if (url.matches(api.getConsumerProductVariantPath())) { return api.getConsumerProductVariantPath(); - } else if(url.matches(api.getVerifyPaymentApi())) { + } else if (url.matches(api.getVerifyPaymentApi())) { return api.getVerifyPaymentApi(); } else if (url.matches(api.getCheckPolicyPath())) { return api.getCheckPolicyPath(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java index b820bcc7..5e27700e 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java @@ -60,10 +60,10 @@ public void handle(RoutingContext routingContext) { LOGGER.error(failure.fillInStackTrace()); String INTERNAL_ERROR_RESP = - new RespBuilder() - .withType(ResponseUrn.INTERNAL_SERVER_ERR_URN.getUrn()) - .withTitle(ResponseUrn.INTERNAL_SERVER_ERR_URN.getMessage()) - .getResponse(); + new RespBuilder() + .withType(ResponseUrn.INTERNAL_SERVER_ERR_URN.getUrn()) + .withTitle(ResponseUrn.INTERNAL_SERVER_ERR_URN.getMessage()) + .getResponse(); routingContext .response() @@ -72,7 +72,6 @@ public void handle(RoutingContext routingContext) { .end(INTERNAL_ERROR_RESP); routingContext.next(); - } routingContext.next(); } @@ -112,8 +111,6 @@ public void handleDecodeException(RoutingContext routingContext) { routingContext.next(); return; } - - } /** diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java index 04c1a63e..5fc1128f 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java @@ -1,6 +1,5 @@ package iudx.data.marketplace.apiserver.handlers; - import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; @@ -37,8 +36,7 @@ public void handle(RoutingContext context) { Map pathParams = context.pathParams(); parameters.addAll(pathParams); - List validations = - validationFactory.build(requestType, parameters, body); + List validations = validationFactory.build(requestType, parameters, body); for (Validator validator : Optional.ofNullable(validations).orElse(Collections.emptyList())) { LOGGER.debug("validator : " + validator.getClass().getName()); validator.isValid(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index 9b6b999f..72a7132e 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -335,15 +335,16 @@ public String getStatus() { public void setStatus(String status) { this.status = status; } - public void setAccountProductId(String rzpAccountProductId){ - this.accountProductId = rzpAccountProductId; - } public String getAccountProductId() { return this.accountProductId; } + public void setAccountProductId(String rzpAccountProductId){ + this.accountProductId = rzpAccountProductId; + } + public Future addAuditLogs(String referenceId, User provider) { JsonObject auditInfo = new JsonObject() diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java index c2848b86..ad03adfa 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java @@ -27,9 +27,7 @@ public class FetchLinkedAccount { String createdAt; public FetchLinkedAccount( - PostgresService postgresService, - Api api, - RazorPayService razorPayService) { + PostgresService postgresService, Api api, RazorPayService razorPayService) { this.postgresService = postgresService; this.api = api; this.razorPayService = razorPayService; @@ -187,6 +185,7 @@ public String getRazorpayAccountProductId() { public void setRazorpayAccountProductId(String razorpayAccountProductId) { this.razorpayAccountProductId = razorpayAccountProductId; } + public String getUpdatedAt() { return updatedAt; } @@ -194,14 +193,12 @@ public String getUpdatedAt() { public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } - public String getCreatedAt() - { + + public String getCreatedAt() { return createdAt; } - public void setCreatedAt(String createdAt) - { + public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } - } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java index a47a7701..14525255 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java @@ -1,6 +1,5 @@ package iudx.data.marketplace.apiserver.provider.linkedAccount; - import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.ProxyGen; import io.vertx.codegen.annotations.VertxGen; @@ -13,39 +12,41 @@ @ProxyGen public interface LinkedAccountService { - - /* factory method */ - @GenIgnore - static LinkedAccountService createProxy(Vertx vertx, String address) - { - return new LinkedAccountServiceVertxEBProxy(vertx, address); - } - - /* service operation */ - - /** - * Used to create a new linked account through for Razorpay - * @param request Provider's business related information to create a linked account - * @param user Provider details as User object - * @return Future of JsonObject when it is successful, Future containing failure message during failure - */ - Future createLinkedAccount(JsonObject request, User user); - - /** - * Used to fetch a linked account created through DMP for Razorpay - * @param user Provider details as User object - * @return Future of JsonObject containing linked account details sent by Razorpay - * when it is successful, Future containing failure message during failure - */ - Future fetchLinkedAccount(User user); - - /** - * Used to update a linked account created through DMP for Razorpay - * @param request Provider's business related information to create a linked account - * all the details expect business_type, email can be updated - * @param user Provider details as User object - * @return Future of JsonObject when it is successful, Future containing failure message during failure - */ - Future updateLinkedAccount(JsonObject request, User user); - + /* factory method */ + @GenIgnore + static LinkedAccountService createProxy(Vertx vertx, String address) { + return new LinkedAccountServiceVertxEBProxy(vertx, address); + } + + /* service operation */ + + /** + * Used to create a new linked account through for Razorpay + * + * @param request Provider's business related information to create a linked account + * @param user Provider details as User object + * @return Future of JsonObject when it is successful, Future containing failure message during + * failure + */ + Future createLinkedAccount(JsonObject request, User user); + + /** + * Used to fetch a linked account created through DMP for Razorpay + * + * @param user Provider details as User object + * @return Future of JsonObject containing linked account details sent by Razorpay when it is + * successful, Future containing failure message during failure + */ + Future fetchLinkedAccount(User user); + + /** + * Used to update a linked account created through DMP for Razorpay + * + * @param request Provider's business related information to create a linked account all the + * details expect business_type, email can be updated + * @param user Provider details as User object + * @return Future of JsonObject when it is successful, Future containing failure message during + * failure + */ + Future updateLinkedAccount(JsonObject request, User user); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java index 44cbff54..33a00c9d 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java @@ -45,15 +45,15 @@ public Future fetchLinkedAccount(User user) { Promise promise = Promise.promise(); this.fetchLinkedAccount - .initiateFetchingLinkedAccount(user) - .onComplete( - handler -> { - if (handler.succeeded()) { - promise.complete(handler.result()); - } else { - promise.fail(handler.cause().getMessage()); - } - }); + .initiateFetchingLinkedAccount(user) + .onComplete( + handler -> { + if (handler.succeeded()) { + promise.complete(handler.result()); + } else { + promise.fail(handler.cause().getMessage()); + } + }); return promise.future(); } @@ -62,15 +62,15 @@ public Future updateLinkedAccount(JsonObject request, User user) { Promise promise = Promise.promise(); this.updateLinkedAccount - .initiateUpdatingLinkedAccount(request, user) - .onComplete( - handler -> { - if (handler.succeeded()) { - promise.complete(handler.result()); - } else { - promise.fail(handler.cause().getMessage()); - } - }); + .initiateUpdatingLinkedAccount(request, user) + .onComplete( + handler -> { + if (handler.succeeded()) { + promise.complete(handler.result()); + } else { + promise.fail(handler.cause().getMessage()); + } + }); return promise.future(); } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java index 761ca681..4c968c90 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java @@ -39,10 +39,11 @@ public void start(Promise startPromise) throws Exception { razorPayService = RazorPayService.createProxy(vertx, RAZORPAY_SERVICE_ADDRESS); createLinkedAccount = - new CreateLinkedAccount(postgresService, api, auditingService,razorPayService); + new CreateLinkedAccount(postgresService, api, auditingService, razorPayService); fetchLinkedAccount = new FetchLinkedAccount(postgresService, api, razorPayService); - updateLinkedAccount = new UpdateLinkedAccount(postgresService, api, auditingService, razorPayService); + updateLinkedAccount = + new UpdateLinkedAccount(postgresService, api, auditingService, razorPayService); linkedAccountService = new LinkedAccountServiceImpl(createLinkedAccount, fetchLinkedAccount, updateLinkedAccount); diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java index 8e225075..ce3676fc 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java @@ -34,12 +34,16 @@ public class UpdateLinkedAccount { String providerId; public UpdateLinkedAccount( - PostgresService postgresService, Api api, AuditingService auditingService, RazorPayService razorPayService) { + PostgresService postgresService, + Api api, + AuditingService auditingService, + RazorPayService razorPayService) { this.postgresService = postgresService; this.api = api; this.auditingService = auditingService; this.razorPayService = razorPayService; } + public Future initiateUpdatingLinkedAccount(JsonObject request, User provider) { String accountRequest = getAccountRequest(request); @@ -48,37 +52,41 @@ public Future initiateUpdatingLinkedAccount(JsonObject request, User String emailId = provider.getEmailId(); setEmailId(emailId); - Future accountInfoFuture = getAccountId(GET_MERCHANT_INFO_QUERY, providerId, emailId); - Future updateAccountInfoInRzpFuture = accountInfoFuture.compose(accountInfoJson -> { - String accountId = accountInfoJson.getString("accountId"); - /* set account id */ - setRzpAccountId(accountId); - return razorPayService.updateLinkedAccount(accountRequest,accountId); - }); - Future userResponseFuture = updateAccountInfoInRzpFuture.compose(isEditInRazorpaySuccessful -> { - if(isEditInRazorpaySuccessful) - { - return updateMerchantInfo(UPDATE_MERCHANT_INFO_QUERY, providerId, emailId); - } - return Future.failedFuture(updateAccountInfoInRzpFuture.cause().getMessage()); - }); + Future accountInfoFuture = + getAccountId(GET_MERCHANT_INFO_QUERY, providerId, emailId); + Future updateAccountInfoInRzpFuture = + accountInfoFuture.compose( + accountInfoJson -> { + String accountId = accountInfoJson.getString("accountId"); + /* set account id */ + setRzpAccountId(accountId); + return razorPayService.updateLinkedAccount(accountRequest, accountId); + }); + Future userResponseFuture = + updateAccountInfoInRzpFuture.compose( + isEditInRazorpaySuccessful -> { + if (isEditInRazorpaySuccessful) { + return updateMerchantInfo(UPDATE_MERCHANT_INFO_QUERY, providerId, emailId); + } + return Future.failedFuture(updateAccountInfoInRzpFuture.cause().getMessage()); + }); /* send the information for auditing */ /* accountId, referenceId, Non-sensitive PII */ - userResponseFuture.compose(insertInDbSuccessful -> { - Future auditFuture = addAuditLogs(provider); - return auditFuture; - }); + userResponseFuture.compose( + insertInDbSuccessful -> { + Future auditFuture = addAuditLogs(provider); + return auditFuture; + }); return userResponseFuture; } - public String getAccountRequest(JsonObject requestBody) - { + public String getAccountRequest(JsonObject requestBody) { String category = requestBody.getJsonObject("profile").getString("category"); String subcategory = requestBody.getJsonObject("profile").getString("subcategory"); JsonObject registered = - requestBody.getJsonObject("profile").getJsonObject("addresses").getJsonObject("registered"); + requestBody.getJsonObject("profile").getJsonObject("addresses").getJsonObject("registered"); String street1 = registered.getString("street1"); String street2 = registered.getString("street2"); String city = registered.getString("city"); @@ -88,20 +96,20 @@ public String getAccountRequest(JsonObject requestBody) String contactName = requestBody.getString("contactName"); JsonObject registeredJson = - new JsonObject() - .put("street1", street1) - .put("street2", street2) - .put("city", city) - .put("state", state) - .put("postal_code", postalCode) - .put("country", country); + new JsonObject() + .put("street1", street1) + .put("street2", street2) + .put("city", city) + .put("state", state) + .put("postal_code", postalCode) + .put("country", country); JsonObject addressJson = new JsonObject().put("registered", registeredJson); JsonObject profileJson = - new JsonObject() - .put("category", category) - .put("subcategory", subcategory) - .put("addresses", addressJson); + new JsonObject() + .put("category", category) + .put("subcategory", subcategory) + .put("addresses", addressJson); JsonObject legalInfoJson = new JsonObject(); /* checks if optional field legal info is null */ @@ -123,11 +131,11 @@ public String getAccountRequest(JsonObject requestBody) setPhoneNumber(phoneNumber); JsonObject details = - new JsonObject() - .put("phone", phoneNumber) - .put("legal_business_name", legalBusinessName) - .put("profile", profileJson) - .put("legal_info", legalInfoJson); + new JsonObject() + .put("phone", phoneNumber) + .put("legal_business_name", legalBusinessName) + .put("profile", profileJson) + .put("legal_info", legalInfoJson); setCustomerFacingBusinessName(legalBusinessName); /* customer facing business name is not a necessary field in the request body @@ -143,44 +151,44 @@ public String getAccountRequest(JsonObject requestBody) return details.encode(); } - public Future getAccountId(String query, String providerId, String emailId) - { + public Future getAccountId(String query, String providerId, String emailId) { Promise promise = Promise.promise(); String finalQuery = query.replace("$1", providerId).replace("$2", emailId); - postgresService.executeQuery(finalQuery, handler -> { - if(handler.succeeded()) - { - boolean isResultEmpty = handler.result().getJsonArray(RESULTS).isEmpty(); - if(!isResultEmpty) - { - JsonObject result = handler.result().getJsonArray(RESULTS).getJsonObject(0); - String accountId = result.getString("account_id"); - - /* set referenceId */ - setReferenceId(result.getString("reference_id")); - - promise.complete(new JsonObject().put("accountId", accountId).put("referenceId", referenceId)); - } - else - { - LOGGER.fatal("Linked account is not created or there was a problem while inserting the record in postgres"); - promise.fail( + postgresService.executeQuery( + finalQuery, + handler -> { + if (handler.succeeded()) { + boolean isResultEmpty = handler.result().getJsonArray(RESULTS).isEmpty(); + if (!isResultEmpty) { + JsonObject result = handler.result().getJsonArray(RESULTS).getJsonObject(0); + String accountId = result.getString("account_id"); + + /* set referenceId */ + setReferenceId(result.getString("reference_id")); + + promise.complete( + new JsonObject().put("accountId", accountId).put("referenceId", referenceId)); + } else { + LOGGER.fatal( + "Linked account is not created or there was a problem while inserting the record in postgres"); + promise.fail( new RespBuilder() - .withType(HttpStatusCode.NOT_FOUND.getValue()) - .withTitle(ResponseUrn.RESOURCE_NOT_FOUND_URN.getUrn()) - .withDetail("Linked account cannot be updated as, it is not found") - .getResponse()); - } - } - else { - LOGGER.error("Failed to fetch account id from postgres : {}", handler.cause().getMessage()); - promise.fail(new RespBuilder() - .withType(HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) - .withTitle(ResponseUrn.INTERNAL_SERVER_ERR_URN.getUrn()) - .withDetail("Linked account could not be updated : Internal Server error") - .getResponse()); - } - }); + .withType(HttpStatusCode.NOT_FOUND.getValue()) + .withTitle(ResponseUrn.RESOURCE_NOT_FOUND_URN.getUrn()) + .withDetail("Linked account cannot be updated as, it is not found") + .getResponse()); + } + } else { + LOGGER.error( + "Failed to fetch account id from postgres : {}", handler.cause().getMessage()); + promise.fail( + new RespBuilder() + .withType(HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) + .withTitle(ResponseUrn.INTERNAL_SERVER_ERR_URN.getUrn()) + .withDetail("Linked account could not be updated : Internal Server error") + .getResponse()); + } + }); return promise.future(); } @@ -276,47 +284,41 @@ public void setCustomerFacingBusinessName(String customerFacingBusinessName) { this.customerFacingBusinessName = customerFacingBusinessName; } - public String getEmailId() - { + public String getEmailId() { return this.emailId; } - public void setEmailId(String emailId) - { + public void setEmailId(String emailId) { this.emailId = emailId; } - public String getRzpAccountId() - { + public String getRzpAccountId() { return this.rzpAccountId; } - public void setRzpAccountId(String rzpAccountId) - { + public void setRzpAccountId(String rzpAccountId) { this.rzpAccountId = rzpAccountId; } - public String getProviderId() - { + public String getProviderId() { return this.providerId; } - public void setProviderId(String providerId) - { + public void setProviderId(String providerId) { this.providerId = providerId; } public Future addAuditLogs(User provider) { JsonObject auditInfo = - new JsonObject() - .put("referenceId", getReferenceId()) - .put("email", getEmailId()) - .put("phoneNumber", getPhoneNumber()) - .put("legalBusinessName", getLegalBusinessName()) - .put("customerFacingBusinessName", getCustomerFacingBusinessName()) - .put("accountId", getRzpAccountId()) - .put("providerId", getProviderId()); + new JsonObject() + .put("referenceId", getReferenceId()) + .put("email", getEmailId()) + .put("phoneNumber", getPhoneNumber()) + .put("legalBusinessName", getLegalBusinessName()) + .put("customerFacingBusinessName", getCustomerFacingBusinessName()) + .put("accountId", getRzpAccountId()) + .put("providerId", getProviderId()); return auditingService.handleAuditLogs( - provider, auditInfo, api.getLinkedAccountService(), HttpMethod.PUT.toString()); + provider, auditInfo, api.getLinkedAccountService(), HttpMethod.PUT.toString()); } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/response/ResponseUtil.java b/src/main/java/iudx/data/marketplace/apiserver/response/ResponseUtil.java index d8480c0e..16eb2cd3 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/response/ResponseUtil.java +++ b/src/main/java/iudx/data/marketplace/apiserver/response/ResponseUtil.java @@ -5,19 +5,19 @@ import iudx.data.marketplace.common.ResponseUrn; public class ResponseUtil { - public static JsonObject generateResponse(HttpStatusCode statusCode, ResponseUrn urn) { - return generateResponse(statusCode, urn, statusCode.getDescription()); - } + public static JsonObject generateResponse(HttpStatusCode statusCode, ResponseUrn urn) { + return generateResponse(statusCode, urn, statusCode.getDescription()); + } - public static JsonObject generateResponse( - HttpStatusCode statusCode, ResponseUrn urn, String message) { - String type = urn.getUrn(); + public static JsonObject generateResponse( + HttpStatusCode statusCode, ResponseUrn urn, String message) { + String type = urn.getUrn(); - return new RestResponse.Builder() - .withMessage(message) - .withType(type) - .withTitle(statusCode.getDescription()) - .build() - .toJson(); - } + return new RestResponse.Builder() + .withMessage(message) + .withType(type) + .withTitle(statusCode.getDescription()) + .build() + .toJson(); + } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/response/RestResponse.java b/src/main/java/iudx/data/marketplace/apiserver/response/RestResponse.java index 9b5c623c..ba35b36b 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/response/RestResponse.java +++ b/src/main/java/iudx/data/marketplace/apiserver/response/RestResponse.java @@ -3,78 +3,78 @@ import io.vertx.core.json.JsonObject; public class RestResponse { - private final String type; - private final String title; - private final String detail; - private int status; + private final String type; + private final String title; + private final String detail; + private int status; - private RestResponse(String type, String title, String detail) { - super(); - this.type = type; - this.title = title; - this.detail = detail; - } + private RestResponse(String type, String title, String detail) { + super(); + this.type = type; + this.title = title; + this.detail = detail; + } - private RestResponse(String type, String title, String detail, int status) { - super(); - this.type = type; - this.title = title; - this.detail = detail; - this.status = status; - } + private RestResponse(String type, String title, String detail, int status) { + super(); + this.type = type; + this.title = title; + this.detail = detail; + this.status = status; + } - public JsonObject toJson() { - if (status != 0) { - return new JsonObject() - .put("statusCode", status) - .put("type", this.type) - .put("title", this.title) - .put("detail", this.detail); - } - return new JsonObject() - .put("type", this.type) - .put("title", this.title) - .put("detail", this.detail); + public JsonObject toJson() { + if (status != 0) { + return new JsonObject() + .put("statusCode", status) + .put("type", this.type) + .put("title", this.title) + .put("detail", this.detail); } + return new JsonObject() + .put("type", this.type) + .put("title", this.title) + .put("detail", this.detail); + } - public static class Builder { - private String type; - private String title; - private String detail; - private int status; + public static class Builder { + private String type; + private String title; + private String detail; + private int status; - public Builder() {} + public Builder() {} - public Builder withType(String type) { - this.type = type; - return this; - } + public Builder withType(String type) { + this.type = type; + return this; + } - public Builder withTitle(String title) { - this.title = title; - return this; - } + public Builder withTitle(String title) { + this.title = title; + return this; + } - public Builder withMessage(String message) { - this.detail = message; - return this; - } + public Builder withMessage(String message) { + this.detail = message; + return this; + } - public Builder withStatusCode(int statusCode) { - this.status = statusCode; - return this; - } + public Builder withStatusCode(int statusCode) { + this.status = statusCode; + return this; + } - public RestResponse build() { - return new RestResponse(this.type, this.title, this.detail, this.status); - } + public RestResponse build() { + return new RestResponse(this.type, this.title, this.detail, this.status); + } - public RestResponse build(int statusCode, String type, String title, String detail) { - this.type = type; - this.title = title; - this.detail = detail; - this.status = statusCode; - return new RestResponse(this.type, this.title, this.detail, this.status); - } + public RestResponse build(int statusCode, String type, String title, String detail) { + this.type = type; + this.title = title; + this.detail = detail; + this.status = statusCode; + return new RestResponse(this.type, this.title, this.detail, this.status); } + } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java index a4ab09de..25f3813b 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java @@ -25,11 +25,11 @@ public enum RequestType { private String filename; - public String getFilename() { - return this.filename; - } - private RequestType(String filename) { this.filename = filename; } + + public String getFilename() { + return this.filename; + } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/Role.java b/src/main/java/iudx/data/marketplace/apiserver/util/Role.java index 845ee998..d2fc7436 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/Role.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/Role.java @@ -16,9 +16,6 @@ public enum Role { Role(String value) { role = value; } - public String getRole() { - return role; - } public static Role fromString(String roleValue) { return Stream.of(values()) @@ -26,4 +23,8 @@ public static Role fromString(String roleValue) { .findAny() .orElseThrow(() -> new DxRuntimeException(404, ROLE_NOT_FOUND)); } + + public String getRole() { + return role; + } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java index 0ab343de..ad86fb94 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java @@ -16,7 +16,7 @@ public class ValidationHandlerFactory { private static final Logger LOGGER = LogManager.getLogger(ValidationHandlerFactory.class); public List build( - final RequestType requestType, final MultiMap parameters, final JsonObject body) { + final RequestType requestType, final MultiMap parameters, final JsonObject body) { LOGGER.debug("getValidation4Context() started for : " + requestType); LOGGER.debug("type : " + requestType); List validator = null; @@ -79,6 +79,7 @@ private List getCheckPolicyValidator(MultiMap parameters) { validators.add(new UuidTypeValidator(parameters.get(PRODUCT_VARIANT_ID), true)); return validators; } + private List getPaymentWebhookValidator(JsonObject body) { List validators = new ArrayList<>(); validators.add(new JsonSchemaTypeValidator(body, RequestType.ORDER_PAID_WEBHOOK)); @@ -91,10 +92,11 @@ private List getConsumerProductVariantValidator(MultiMap parameters) validators.add(new ProductIdTypeValidator(parameters.get("productId"), true)); return validators; } + private List getPurchaseValidator(MultiMap parameters) { List validators = new ArrayList<>(); - validators.add(new UuidTypeValidator(parameters.get("resourceId"),false)); + validators.add(new UuidTypeValidator(parameters.get("resourceId"), false)); validators.add(new ProductIdTypeValidator(parameters.get("productId"), false)); validators.add(new OrderIdTypeValidator(parameters.get("orderId"), false)); return validators; @@ -112,12 +114,12 @@ private List getPostLinkedAccountValidator(JsonObject body, RequestTy return validators; } - private List getPutLinkedAccountValidator(JsonObject body, RequestType requestType) - { + private List getPutLinkedAccountValidator(JsonObject body, RequestType requestType) { List validators = new ArrayList<>(); validators.add(new JsonSchemaTypeValidator(body, requestType)); return validators; } + private List getOrderValidator(MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get(PRODUCT_VARIANT_ID), true)); @@ -152,7 +154,7 @@ private List getProviderIDValidators(final MultiMap parameters) { } private List getProductValidators( - final MultiMap parameters, final JsonObject body, final RequestType requestType) { + final MultiMap parameters, final JsonObject body, final RequestType requestType) { List validators = new ArrayList<>(); if (body == null || body.isEmpty()) { @@ -165,7 +167,7 @@ private List getProductValidators( } private List getProductVariantValidators( - final MultiMap parameters, final JsonObject body, final RequestType requestType) { + final MultiMap parameters, final JsonObject body, final RequestType requestType) { List validators = new ArrayList<>(); if (body == null || body.isEmpty()) { @@ -177,17 +179,16 @@ private List getProductVariantValidators( return validators; } - private List getDeleteProductVariantValidators(final MultiMap parameters, final RequestType requestType) - { + private List getDeleteProductVariantValidators( + final MultiMap parameters, final RequestType requestType) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get(PRODUCT_VARIANT_ID), true)); return validators; } - private List listProductVariantValidators(final MultiMap parameters) - { + private List listProductVariantValidators(final MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new ProductIdTypeValidator(parameters.get(PRODUCT_ID), true)); return validators; } -} \ No newline at end of file +} diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java index b02c5dd0..23f4cfb7 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -23,11 +23,10 @@ public class JsonSchemaTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(JsonSchemaTypeValidator.class); - - private final JsonObject body; - private final RequestType requestType; private static String pkg = Validator.class.getPackageName(); private static final String PACKAGE_NAME = "/" + pkg.replace(".","/"); + private final JsonObject body; + private final RequestType requestType; public JsonSchemaTypeValidator(JsonObject body, RequestType requestType) { this.body = body; @@ -35,6 +34,14 @@ public JsonSchemaTypeValidator(JsonObject body, RequestType requestType) { isValid(); } + public static JsonNode loadResource(final String name) throws IOException { + return JsonLoader.fromResource(name); + } + + public static JsonNode loadString(final String obj) throws IOException { + return JsonLoader.fromString(obj); + } + @Override public boolean isValid() { boolean isValid; @@ -83,13 +90,6 @@ private boolean validateJson(JsonObject body, RequestType requestType) throws IO return isValid; } - public static JsonNode loadResource(final String name) throws IOException { - return JsonLoader.fromResource(name); - } - - public static JsonNode loadString(final String obj) throws IOException { - return JsonLoader.fromString(obj); - } @Override public int failureCode() { return HttpStatusCode.BAD_REQUEST.getValue(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java index c3d52a45..6b0952d9 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java @@ -9,7 +9,7 @@ import static iudx.data.marketplace.apiserver.util.Constants.VALIDATION_VARIANT_NAME_REGEX; import static iudx.data.marketplace.common.ResponseUrn.INVALID_NAME_URN; -public class VariantNameTypeValidator implements Validator{ +public class VariantNameTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(VariantNameTypeValidator.class); diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingService.java b/src/main/java/iudx/data/marketplace/auditing/AuditingService.java index 52a2b86b..0269e537 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingService.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingService.java @@ -25,6 +25,7 @@ static AuditingService createProxy(Vertx vertx, String address) { * @param httpMethod Http Method of the endpoint * @return Future of type void */ - Future handleAuditLogs (User user, JsonObject information, String api, String httpMethod); + Future handleAuditLogs(User user, JsonObject information, String api, String httpMethod); + Future insertAuditLogIntoRmq(JsonObject request); } diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java b/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java index 6255af03..4eff469d 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java @@ -28,7 +28,8 @@ public AuditingServiceImpl(DataBrokerService dataBrokerService, JsonObject confi } @Override - public Future handleAuditLogs(User user, JsonObject information, String api, String httpMethod) { + public Future handleAuditLogs( + User user, JsonObject information, String api, String httpMethod) { LOGGER.debug("handleAuditLogs started"); String userId = user.getUserId(); ZonedDateTime zst = ZonedDateTime.now(ZoneId.of("Asia/Kolkata")); @@ -45,18 +46,17 @@ public Future handleAuditLogs(User user, JsonObject information, String ap Promise promise = Promise.promise(); LOGGER.debug("AuditLog: " + auditLog); - this - .insertAuditLogIntoRmq(auditLog) - .onComplete( - handler -> { - if (handler.succeeded()) { - LOGGER.info("Audit data published into RMQ."); - promise.complete(); - } else { - LOGGER.error("failed: " + handler.cause().getMessage()); - promise.complete(); - } - }); + this.insertAuditLogIntoRmq(auditLog) + .onComplete( + handler -> { + if (handler.succeeded()) { + LOGGER.info("Audit data published into RMQ."); + promise.complete(); + } else { + LOGGER.error("failed: " + handler.cause().getMessage()); + promise.complete(); + } + }); return promise.future(); } diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java b/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java index e7cc3851..1a5b798c 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java @@ -15,84 +15,83 @@ public class AuditingVerticle extends AbstractVerticle { - private RabbitMQOptions config; - private RabbitMQClient client; - private String dataBrokerIp; - private int dataBrokerPort; - private int dataBrokerManagementPort; - private String dataBrokerVhost; - private String dataBrokerUserName; - private String dataBrokerPassword; - private int connectionTimeout; - private int requestedHeartbeat; - private int handshakeTimeout; - private int requestedChannelMax; - private int networkRecoveryInterval; - private ServiceBinder binder; - private MessageConsumer consumer; - private WebClientOptions webConfig; - private DataBrokerService dataBrokerService; - private AuditingService metering; + private RabbitMQOptions config; + private RabbitMQClient client; + private String dataBrokerIp; + private int dataBrokerPort; + private int dataBrokerManagementPort; + private String dataBrokerVhost; + private String dataBrokerUserName; + private String dataBrokerPassword; + private int connectionTimeout; + private int requestedHeartbeat; + private int handshakeTimeout; + private int requestedChannelMax; + private int networkRecoveryInterval; + private ServiceBinder binder; + private MessageConsumer consumer; + private WebClientOptions webConfig; + private DataBrokerService dataBrokerService; + private AuditingService metering; - @Override - public void start() throws Exception { + @Override + public void start() throws Exception { - /* Read the configuration and set the rabbitMQ server properties. */ - dataBrokerIp = config().getString("dataBrokerIP"); - dataBrokerPort = config().getInteger("dataBrokerPort"); - dataBrokerManagementPort = config().getInteger("dataBrokerManagementPort"); - dataBrokerVhost = config().getString("dataBrokerVhost"); - dataBrokerUserName = config().getString("dataBrokerUserName"); - dataBrokerPassword = config().getString("dataBrokerPassword"); - connectionTimeout = config().getInteger("connectionTimeout"); - requestedHeartbeat = config().getInteger("requestedHeartbeat"); - handshakeTimeout = config().getInteger("handshakeTimeout"); - requestedChannelMax = config().getInteger("requestedChannelMax"); - networkRecoveryInterval = config().getInteger("networkRecoveryInterval"); + /* Read the configuration and set the rabbitMQ server properties. */ + dataBrokerIp = config().getString("dataBrokerIP"); + dataBrokerPort = config().getInteger("dataBrokerPort"); + dataBrokerManagementPort = config().getInteger("dataBrokerManagementPort"); + dataBrokerVhost = config().getString("dataBrokerVhost"); + dataBrokerUserName = config().getString("dataBrokerUserName"); + dataBrokerPassword = config().getString("dataBrokerPassword"); + connectionTimeout = config().getInteger("connectionTimeout"); + requestedHeartbeat = config().getInteger("requestedHeartbeat"); + handshakeTimeout = config().getInteger("handshakeTimeout"); + requestedChannelMax = config().getInteger("requestedChannelMax"); + networkRecoveryInterval = config().getInteger("networkRecoveryInterval"); - /* Configure the RabbitMQ Data Broker client with input from config files. */ + /* Configure the RabbitMQ Data Broker client with input from config files. */ - config = - new RabbitMQOptions() - .setUser(dataBrokerUserName) - .setPassword(dataBrokerPassword) - .setHost(dataBrokerIp) - .setPort(dataBrokerPort) - .setVirtualHost(dataBrokerVhost) - .setConnectionTimeout(connectionTimeout) - .setRequestedHeartbeat(requestedHeartbeat) - .setHandshakeTimeout(handshakeTimeout) - .setRequestedChannelMax(requestedChannelMax) - .setNetworkRecoveryInterval(networkRecoveryInterval) - .setAutomaticRecoveryEnabled(true); + config = + new RabbitMQOptions() + .setUser(dataBrokerUserName) + .setPassword(dataBrokerPassword) + .setHost(dataBrokerIp) + .setPort(dataBrokerPort) + .setVirtualHost(dataBrokerVhost) + .setConnectionTimeout(connectionTimeout) + .setRequestedHeartbeat(requestedHeartbeat) + .setHandshakeTimeout(handshakeTimeout) + .setRequestedChannelMax(requestedChannelMax) + .setNetworkRecoveryInterval(networkRecoveryInterval) + .setAutomaticRecoveryEnabled(true); - webConfig = - new WebClientOptions() - .setKeepAlive(true) - .setConnectTimeout(86400000) - .setDefaultHost(dataBrokerIp) - .setDefaultPort(dataBrokerManagementPort) - .setKeepAliveTimeout(86400000); - /* Create a Vertx Web Client with the configuration and vertx cluster instance. */ + webConfig = + new WebClientOptions() + .setKeepAlive(true) + .setConnectTimeout(86400000) + .setDefaultHost(dataBrokerIp) + .setDefaultPort(dataBrokerManagementPort) + .setKeepAliveTimeout(86400000); + /* Create a Vertx Web Client with the configuration and vertx cluster instance. */ - WebClient.create(vertx, webConfig); + WebClient.create(vertx, webConfig); - /* - * Create a RabbitMQ Client with the configuration and vertx cluster instance. - */ + /* + * Create a RabbitMQ Client with the configuration and vertx cluster instance. + */ - client = RabbitMQClient.create(vertx, config); - dataBrokerService = new DataBrokerServiceImpl(client); - metering = new AuditingServiceImpl(dataBrokerService, config()); - binder = new ServiceBinder(vertx); - /* Publish the Data Broker service with the Event Bus against an address. */ - consumer = - binder.setAddress(AUDITING_SERVICE_ADDRESS).register(AuditingService.class, metering); - } - - @Override - public void stop() { - binder.unregister(consumer); - } + client = RabbitMQClient.create(vertx, config); + dataBrokerService = new DataBrokerServiceImpl(client); + metering = new AuditingServiceImpl(dataBrokerService, config()); + binder = new ServiceBinder(vertx); + /* Publish the Data Broker service with the Event Bus against an address. */ + consumer = + binder.setAddress(AUDITING_SERVICE_ADDRESS).register(AuditingService.class, metering); + } + @Override + public void stop() { + binder.unregister(consumer); + } } diff --git a/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerService.java b/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerService.java index 64adf8e4..a8f7ac0a 100644 --- a/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerService.java +++ b/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerService.java @@ -1,10 +1,9 @@ package iudx.data.marketplace.auditing.databroker; - import io.vertx.core.Future; import io.vertx.core.json.JsonObject; public interface DataBrokerService { - Future publishMessage(String toExchange, String routingKey, JsonObject body); + Future publishMessage(String toExchange, String routingKey, JsonObject body); } diff --git a/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerServiceImpl.java b/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerServiceImpl.java index 1f2d8db0..f725b391 100644 --- a/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/auditing/databroker/DataBrokerServiceImpl.java @@ -8,43 +8,45 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -public class DataBrokerServiceImpl implements DataBrokerService{ - private static final Logger LOGGER = LogManager.getLogger(DataBrokerServiceImpl.class); - private RabbitMQClient rabbitWebclient; - public DataBrokerServiceImpl(RabbitMQClient rabbitWebclient) { - this.rabbitWebclient = rabbitWebclient; - } - /** - * @param toExchange Exchange name - * @param routingKey routingKey - * @param messageBody JsonObject - * @return void future - */ - @Override - public Future publishMessage(String toExchange, String routingKey, JsonObject messageBody) { - Promise promise = Promise.promise(); +public class DataBrokerServiceImpl implements DataBrokerService { + private static final Logger LOGGER = LogManager.getLogger(DataBrokerServiceImpl.class); + private RabbitMQClient rabbitWebclient; + + public DataBrokerServiceImpl(RabbitMQClient rabbitWebclient) { + this.rabbitWebclient = rabbitWebclient; + } - Future rabbitMqClientStartFuture; - Buffer buffer = Buffer.buffer(messageBody.toString()); - if (!rabbitWebclient.isConnected()) { - rabbitMqClientStartFuture = rabbitWebclient.start(); - } else { - rabbitMqClientStartFuture = Future.succeededFuture(); - } - rabbitMqClientStartFuture - .compose( - rabbitStartupFuture -> rabbitWebclient.basicPublish(toExchange, routingKey, buffer)) - .onSuccess( - successHandler -> { - LOGGER.debug("Data Published into RMQ"); - promise.complete(); - }) - .onFailure( - failureHandler -> { - LOGGER.error(failureHandler.getMessage()); - promise.fail(failureHandler.getMessage()); - }); + /** + * @param toExchange Exchange name + * @param routingKey routingKey + * @param messageBody JsonObject + * @return void future + */ + @Override + public Future publishMessage(String toExchange, String routingKey, JsonObject messageBody) { + Promise promise = Promise.promise(); - return promise.future(); + Future rabbitMqClientStartFuture; + Buffer buffer = Buffer.buffer(messageBody.toString()); + if (!rabbitWebclient.isConnected()) { + rabbitMqClientStartFuture = rabbitWebclient.start(); + } else { + rabbitMqClientStartFuture = Future.succeededFuture(); } + rabbitMqClientStartFuture + .compose( + rabbitStartupFuture -> rabbitWebclient.basicPublish(toExchange, routingKey, buffer)) + .onSuccess( + successHandler -> { + LOGGER.debug("Data Published into RMQ"); + promise.complete(); + }) + .onFailure( + failureHandler -> { + LOGGER.error(failureHandler.getMessage()); + promise.fail(failureHandler.getMessage()); + }); + + return promise.future(); + } } diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java index 93eb05ad..6916d732 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java @@ -26,6 +26,18 @@ @ProxyGen public interface AuthenticationService { + /** + * The createProxy helps the code generation blocks to generate proxy code. + * + * @param vertx which is the vertx instance + * @param address which is the proxy address + * @return AuthenticationServiceVertxEBProxy which is a service proxy + */ + @GenIgnore + static AuthenticationService createProxy(Vertx vertx, String address) { + return new AuthenticationServiceVertxEBProxy(vertx, address); + } + /** * The tokenIntrospect method implements the authentication and authorization module using IUDX * APIs. @@ -39,18 +51,6 @@ public interface AuthenticationService { AuthenticationService tokenIntrospect( JsonObject request, JsonObject authenticationInfo, Handler> handler); - /** - * The createProxy helps the code generation blocks to generate proxy code. - * - * @param vertx which is the vertx instance - * @param address which is the proxy address - * @return AuthenticationServiceVertxEBProxy which is a service proxy - */ - @GenIgnore - static AuthenticationService createProxy(Vertx vertx, String address) { - return new AuthenticationServiceVertxEBProxy(vertx, address); - } - /** * Token introspection for verify endpoint that uses a bearer token generated by DX Auth Server * @param authInfo contains Api Endpoint, Header token and Api Method diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java index ebede825..6bb1615d 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java @@ -140,11 +140,6 @@ public AuthenticationService tokenIntrospect4Verify( return this; } - // class to contain intermediate data for token introspection - final class ResultContainer { - JwtData jwtData; - } - Future decodeJwt(String jwtToken) { Promise promise = Promise.promise(); TokenCredentials credentials = new TokenCredentials(jwtToken); @@ -166,6 +161,11 @@ Future decodeJwt(String jwtToken) { return promise.future(); } + // class to contain intermediate data for token introspection + final class ResultContainer { + JwtData jwtData; + } + } diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java index a61c3dfc..b7904743 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java @@ -30,6 +30,7 @@ public class AuthenticationVerticle extends AbstractVerticle { private MessageConsumer consumer; private WebClient webClient; private Api api; + static WebClient createWebClient(Vertx vertx, JsonObject config) { return createWebClient(vertx, config, false); } @@ -115,4 +116,5 @@ private Future getJwtPublicKey(Vertx vertx, JsonObject config) { } }); return promise.future(); - }} + } +} diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java index bbd3425e..c2076689 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java @@ -3,21 +3,21 @@ import iudx.data.marketplace.common.Api; public class AuthorizationContextFactory { - public static AuthorizationStatergy create(IudxRole role, Api api){ + public static AuthorizationStatergy create(IudxRole role, Api api) { if (role == null) { throw new IllegalArgumentException(role + " role is not defined in IUDX"); } switch (role) { - case PROVIDER: { - return ProviderAuthStatergy.getInstance(api); - } - case CONSUMER: { - return ConsumerAuthStatergy.getInstance(api); - } + case PROVIDER: + { + return ProviderAuthStatergy.getInstance(api); + } + case CONSUMER: + { + return ConsumerAuthStatergy.getInstance(api); + } default: throw new IllegalArgumentException(role + " role is not defined in IUDX"); } - } - } diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java index 8145d578..7516abfa 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java @@ -6,7 +6,6 @@ public class AuthorizationRequest { - private final Method method; private final String api; diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java index 88232365..2b0eb5bd 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java @@ -11,7 +11,6 @@ import java.util.List; import java.util.Map; - import static iudx.data.marketplace.authenticator.authorization.Method.GET; import static iudx.data.marketplace.authenticator.authorization.Method.POST; @@ -20,9 +19,11 @@ public class ConsumerAuthStatergy implements AuthorizationStatergy { private static volatile ConsumerAuthStatergy instance; Map> consumerAuthorizationRules = new HashMap<>(); + private ConsumerAuthStatergy(Api apis) { buildPermissions(apis); } + public static ConsumerAuthStatergy getInstance(Api apis) { if (instance == null) { synchronized (ConsumerAuthStatergy.class) { @@ -33,6 +34,7 @@ public static ConsumerAuthStatergy getInstance(Api apis) { } return instance; } + private void buildPermissions(Api apis) { // api access list List apiAccessList = new ArrayList<>(); @@ -50,6 +52,7 @@ private void buildPermissions(Api apis) { apiAccessList.add(new AuthorizationRequest(GET, apis.getPoliciesUrl())); consumerAuthorizationRules.put("api", apiAccessList); } + @Override public boolean isAuthorized(AuthorizationRequest authorizationRequest, JwtData jwtData) { String endpoint = authorizationRequest.getApi(); diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java index 734f973e..c86b30ec 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java @@ -13,10 +13,6 @@ public enum IudxRole { this.role = role; } - public String getRole() { - return this.role; - } - public static IudxRole fromRole(final JwtData jwtData) { String role = jwtData.getRole().equalsIgnoreCase(DELEGATE.getRole()) ? jwtData.getDrl() : jwtData.getRole(); return Stream.of(values()) @@ -25,5 +21,9 @@ public static IudxRole fromRole(final JwtData jwtData) { .orElse(null); } + public String getRole() { + return this.role; + } + } diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java index ffa7a9b1..dc66ccea 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java @@ -11,7 +11,6 @@ import java.util.List; import java.util.Map; - import static iudx.data.marketplace.authenticator.authorization.Method.*; public class ProviderAuthStatergy implements AuthorizationStatergy { @@ -19,25 +18,21 @@ public class ProviderAuthStatergy implements AuthorizationStatergy { private static volatile ProviderAuthStatergy instance; Map> providerAuthorizationRequest = new HashMap<>(); - private ProviderAuthStatergy(Api api) - { + private ProviderAuthStatergy(Api api) { buildPermissions(api); } - public static ProviderAuthStatergy getInstance(Api api) - { - if(instance == null) - { - synchronized (ProviderAuthStatergy.class) - { - if(instance == null) - { + public static ProviderAuthStatergy getInstance(Api api) { + if (instance == null) { + synchronized (ProviderAuthStatergy.class) { + if (instance == null) { instance = new ProviderAuthStatergy(api); } } } return instance; } + private void buildPermissions(Api api) { List apiAccessList = new ArrayList<>(); apiAccessList.add(new AuthorizationRequest(POST, api.getProviderProductPath())); @@ -49,7 +44,7 @@ private void buildPermissions(Api api) { apiAccessList.add(new AuthorizationRequest(GET, api.getProviderProductVariantPath())); apiAccessList.add(new AuthorizationRequest(DELETE, api.getProviderProductVariantPath())); -// Linked Account APIs + // Linked Account APIs apiAccessList.add(new AuthorizationRequest(POST, api.getLinkedAccountService())); apiAccessList.add(new AuthorizationRequest(PUT, api.getLinkedAccountService())); apiAccessList.add(new AuthorizationRequest(GET, api.getLinkedAccountService())); diff --git a/src/main/java/iudx/data/marketplace/authenticator/model/JwtData.java b/src/main/java/iudx/data/marketplace/authenticator/model/JwtData.java index dc7b6730..8ea1ecd9 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/model/JwtData.java +++ b/src/main/java/iudx/data/marketplace/authenticator/model/JwtData.java @@ -124,27 +124,27 @@ public void setIat(Integer iat) { @Override public String toString() { return "JwtData [access_token=" - + accessToken - + ", sub=" - + sub - + ", iss=" - + iss - + ", aud=" - + aud - + ", exp=" - + exp - + ", iat=" - + iat - + ", iid=" - + iid - + ", role=" - + role - + ", cons=" - + cons - + ", drl=" - + drl - + ", did=" - + did - + "]"; + + accessToken + + ", sub=" + + sub + + ", iss=" + + iss + + ", aud=" + + aud + + ", exp=" + + exp + + ", iat=" + + iat + + ", iid=" + + iid + + ", role=" + + role + + ", cons=" + + cons + + ", drl=" + + drl + + ", did=" + + did + + "]"; } } diff --git a/src/main/java/iudx/data/marketplace/common/Api.java b/src/main/java/iudx/data/marketplace/common/Api.java index bfced995..506701a4 100644 --- a/src/main/java/iudx/data/marketplace/common/Api.java +++ b/src/main/java/iudx/data/marketplace/common/Api.java @@ -57,7 +57,7 @@ private void buildPaths() { verifyPaymentApi = new StringBuilder(VERIFY_PAYMENTS_PATH); consumerProductVariantPath = new StringBuilder(CONSUMER_PATH + PRODUCT_VARIANT_PATH); consumerListResourcePath = new StringBuilder(CONSUMER_PATH + LIST_RESOURCES_PATH); - checkPolicyPath = new StringBuilder( dxApiBasePath).append(CHECK_POLICY_PATH + POLICIES_API); + checkPolicyPath = new StringBuilder(dxApiBasePath).append(CHECK_POLICY_PATH + POLICIES_API); } public String getPoliciesUrl() { @@ -107,6 +107,7 @@ public String getConsumerListProducts() { public String getLinkedAccountService() { return linkedAccountService.toString(); } + public String getConsumerOrderApi() { return consumerOrdersApi.toString(); } @@ -114,16 +115,16 @@ public String getConsumerOrderApi() { public String getVerifyPaymentApi() { return verifyPaymentApi.toString(); } - public String getConsumerProductVariantPath() - { + + public String getConsumerProductVariantPath() { return consumerProductVariantPath.toString(); } - public String getConsumerListResourcePath() - { + public String getConsumerListResourcePath() { return consumerListResourcePath.toString(); } - public String getCheckPolicyPath(){ + + public String getCheckPolicyPath() { return checkPolicyPath.toString(); } } diff --git a/src/main/java/iudx/data/marketplace/common/CatalogueService.java b/src/main/java/iudx/data/marketplace/common/CatalogueService.java index 9e48dbd2..1b15d383 100644 --- a/src/main/java/iudx/data/marketplace/common/CatalogueService.java +++ b/src/main/java/iudx/data/marketplace/common/CatalogueService.java @@ -116,7 +116,8 @@ public Future getResourceCount(String resourceID) { new JsonObject().put(RESOURCE_ID, resourceID).put("totalHits", totalHits); promise.complete(res); } else { - LOGGER.debug("Cat web client call to {} failed for id: {} ", catRelPath, resourceID); + LOGGER.debug( + "Cat web client call to {} failed for id: {} ", catRelPath, resourceID); promise.fail( "Cat web client call to " + catItemPath + " failed for id: " + resourceID); } @@ -131,11 +132,12 @@ public Future searchApi(JsonObject params) { JsonArray keysArray = new JsonArray(); JsonArray valuesArray = new JsonArray(); - params.forEach(entry -> { - keysArray.add(entry.getKey()); - JsonArray valueArray = new JsonArray().add(entry.getValue()); - valuesArray.add(valueArray.getList()); - }); + params.forEach( + entry -> { + keysArray.add(entry.getKey()); + JsonArray valueArray = new JsonArray().add(entry.getValue()); + valuesArray.add(valueArray.getList()); + }); LOGGER.debug(keysArray.getList().toString()); LOGGER.debug(valuesArray.getList().toString()); @@ -144,8 +146,9 @@ public Future searchApi(JsonObject params) { .get(catPort, catHost, "/iudx/cat/v1/search") .addQueryParam("property", keysArray.getList().toString()) .addQueryParam("value", valuesArray.getList().toString()) - .send(searchApiHandler -> { - if(searchApiHandler.succeeded()) { + .send( + searchApiHandler -> { + if (searchApiHandler.succeeded()) { LOGGER.debug(searchApiHandler.result().bodyAsJsonObject()); } else { LOGGER.error(searchApiHandler.cause()); diff --git a/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java b/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java index fcd7f215..a9398925 100644 --- a/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java +++ b/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java @@ -71,6 +71,13 @@ public enum HttpStatusCode { this.urn = urn; } + public static HttpStatusCode getByValue(int value) { + for (HttpStatusCode status : values()) { + if (status.value == value) return status; + } + throw new IllegalArgumentException("Invalid status code: " + value); + } + public int getValue() { return value; } @@ -87,11 +94,4 @@ public String getUrn() { public String toString() { return value + " " + description; } - - public static HttpStatusCode getByValue(int value) { - for (HttpStatusCode status : values()) { - if (status.value == value) return status; - } - throw new IllegalArgumentException("Invalid status code: " + value); - } } diff --git a/src/main/java/iudx/data/marketplace/common/RespBuilder.java b/src/main/java/iudx/data/marketplace/common/RespBuilder.java index c727d0f3..9d9983bb 100644 --- a/src/main/java/iudx/data/marketplace/common/RespBuilder.java +++ b/src/main/java/iudx/data/marketplace/common/RespBuilder.java @@ -13,8 +13,8 @@ public RespBuilder withType(String type) { response.put(JSON_TYPE, type); return this; } - public RespBuilder withType(int statusCode) - { + + public RespBuilder withType(int statusCode) { response.put(JSON_TYPE, statusCode); return this; } @@ -38,6 +38,7 @@ public RespBuilder withResult(JsonObject result) { response.put(RESULTS, result); return this; } + public JsonObject getJsonResponse() { return response; } diff --git a/src/main/java/iudx/data/marketplace/common/ResponseUrn.java b/src/main/java/iudx/data/marketplace/common/ResponseUrn.java index b2871bcf..1aee29d5 100644 --- a/src/main/java/iudx/data/marketplace/common/ResponseUrn.java +++ b/src/main/java/iudx/data/marketplace/common/ResponseUrn.java @@ -68,6 +68,13 @@ public enum ResponseUrn { this.message = message; } + public static ResponseUrn fromCode(final String urn) { + return Stream.of(values()) + .filter(v -> v.urn.equalsIgnoreCase(urn)) + .findAny() + .orElse(YET_NOT_IMPLEMENTED_URN); // if backend service dont respond with urn + } + public String getUrn() { return urn; } @@ -76,13 +83,6 @@ public String getMessage() { return message; } - public static ResponseUrn fromCode(final String urn) { - return Stream.of(values()) - .filter(v -> v.urn.equalsIgnoreCase(urn)) - .findAny() - .orElse(YET_NOT_IMPLEMENTED_URN); // if backend service dont respond with urn - } - public String toString() { return "[" + urn + " : " + message + " ]"; } diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java index 5c4a6f2a..2a81fdbe 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java @@ -13,6 +13,18 @@ @VertxGen @ProxyGen public interface ConsumerService { + /** + * The createProxy helps the code generation blocks to generate proxy code. + * + * @param vertx which is the vertx instance + * @param address which is the proxy address + * @return ProductServiceVertxEBProxy which is a service proxy + */ + @GenIgnore + static ConsumerService createProxy(Vertx vertx, String address) { + return new ConsumerServiceVertxEBProxy(vertx, address); + } + /** * The listResources method fetches some or all resources available on the IUDX marketplace * @param consumer as User object @@ -63,18 +75,6 @@ public interface ConsumerService { @Fluent ConsumerService listProductVariants(User user,JsonObject request, Handler> handler); - /** - * The createProxy helps the code generation blocks to generate proxy code. - * - * @param vertx which is the vertx instance - * @param address which is the proxy address - * @return ProductServiceVertxEBProxy which is a service proxy - */ - @GenIgnore - static ConsumerService createProxy(Vertx vertx, String address) { - return new ConsumerServiceVertxEBProxy(vertx, address); - } - /** * List purchase will fetch invoice related info, provider, consumer and product variant related information * After the purchase is made. Pending, successful, failed payments are displayed diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java index 8d364c61..109e8232 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java @@ -364,8 +364,7 @@ public ConsumerService listProductVariants( return this; } - Future generateOrderEntry( - JsonObject orderInfo, String variantId, String consumerId) { + Future generateOrderEntry(JsonObject orderInfo, String variantId, String consumerId) { Promise promise = Promise.promise(); QueryContainer queryContainer = getQueryContainer(orderInfo, variantId, consumerId); diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java index 23cadbc7..20168115 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java @@ -30,7 +30,10 @@ public void start() throws Exception { consumerService = new ConsumerServiceImpl(config(), postgresService, razorPayService, util); binder = new ServiceBinder(vertx); - consumer = binder.setAddress(CONSUMER_SERVICE_ADDRESS).register(ConsumerService.class, consumerService); + consumer = + binder + .setAddress(CONSUMER_SERVICE_ADDRESS) + .register(ConsumerService.class, consumerService); LOGGER.info("Consumer Service started"); } diff --git a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java index 8bfa42cd..e94f5a1d 100644 --- a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java +++ b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java @@ -16,11 +16,6 @@ public enum PaymentStatus { paymentStatus = value; } - public String getPaymentStatus() - { - return paymentStatus; - } - public static PaymentStatus fromString(String value) { return Stream.of(values()) @@ -29,4 +24,9 @@ public static PaymentStatus fromString(String value) .orElseThrow(() -> new DxRuntimeException(404, PAYMENT_STATUS_NOT_FOUND)); } + public String getPaymentStatus() + { + return paymentStatus; + } + } diff --git a/src/main/java/iudx/data/marketplace/deploy/Deployer.java b/src/main/java/iudx/data/marketplace/deploy/Deployer.java index 9fcb32cc..40f5ca26 100644 --- a/src/main/java/iudx/data/marketplace/deploy/Deployer.java +++ b/src/main/java/iudx/data/marketplace/deploy/Deployer.java @@ -50,8 +50,10 @@ *
  • --config/-c : path to the config file *
  • --isClustered/-C : true for clustering and false for non-clustered mode *
  • --host/-i : the hostname for clustering or localhost for non-clustered mode - *
  • --modules/-m : comma separated list of module names to deploy, by default all is used to deploy every verticle + *
  • --modules/-m : comma separated list of module names to deploy, by default all is used to + * deploy every verticle * + * * Replace the fatjar file with respective path to fat jar for clustered or non-clustered mode * Replace the configs with the respective path to config.json * @@ -67,9 +69,9 @@ public class Deployer { /** * Recursively deploy all modules. * - * @param vertx the vert.x instance + * @param vertx the vert.x instance * @param configs the JSON configuration - * @param i for recursive base case + * @param i for recursive base case */ public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { if (i >= configs.getJsonArray("modules").size()) { @@ -93,20 +95,23 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { deploymentOptions.setMaxWorkerExecuteTimeUnit(TimeUnit.MINUTES); } - vertx.deployVerticle(moduleName, deploymentOptions, ar -> { - if (ar.succeeded()) { - LOGGER.info("Deployed " + moduleName); - recursiveDeploy(vertx, configs, i + 1); - } else { - LOGGER.fatal("Failed to deploy " + moduleName + " cause:", ar.cause()); - } - }); + vertx.deployVerticle( + moduleName, + deploymentOptions, + ar -> { + if (ar.succeeded()) { + LOGGER.info("Deployed " + moduleName); + recursiveDeploy(vertx, configs, i + 1); + } else { + LOGGER.fatal("Failed to deploy " + moduleName + " cause:", ar.cause()); + } + }); } /** * Recursively deploy modules/verticles (if they exist) present in the `modules` list. * - * @param vertx the vert.x instance + * @param vertx the vert.x instance * @param configs the JSON configuration * @param modules the list of modules to deploy */ @@ -119,8 +124,11 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, List String moduleName = modules.get(0); JsonObject config = - configuredModules.stream().map(obj -> (JsonObject) obj).filter(obj -> obj.getString("id").equals(moduleName)) - .findFirst().orElse(new JsonObject()); + configuredModules.stream() + .map(obj -> (JsonObject) obj) + .filter(obj -> obj.getString("id").equals(moduleName)) + .findFirst() + .orElse(new JsonObject()); if (config.isEmpty()) { LOGGER.fatal("Failed to deploy " + moduleName + " cause: Not Found"); @@ -130,7 +138,8 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, List JsonObject commonConfigs = configs.getJsonObject("commonConfig"); config.mergeIn(commonConfigs, true); int numInstances = config.getInteger("verticleInstances"); - DeploymentOptions deploymentOptions = new DeploymentOptions().setInstances(numInstances).setConfig(config); + DeploymentOptions deploymentOptions = + new DeploymentOptions().setInstances(numInstances).setConfig(config); boolean isWorkerVerticle = config.getBoolean("isWorkerVerticle"); if (isWorkerVerticle) { LOGGER.info("worker verticle : " + config.getString("id")); @@ -141,15 +150,18 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, List deploymentOptions.setMaxWorkerExecuteTimeUnit(TimeUnit.MINUTES); } - vertx.deployVerticle(moduleName, deploymentOptions, ar -> { - if (ar.succeeded()) { - LOGGER.info("Deployed " + moduleName); - modules.remove(0); - recursiveDeploy(vertx, configs, modules); - } else { - LOGGER.fatal("Failed to deploy " + moduleName + " cause:", ar.cause()); - } - }); + vertx.deployVerticle( + moduleName, + deploymentOptions, + ar -> { + if (ar.succeeded()) { + LOGGER.info("Deployed " + moduleName); + modules.remove(0); + recursiveDeploy(vertx, configs, modules); + } else { + LOGGER.fatal("Failed to deploy " + moduleName + " cause:", ar.cause()); + } + }); } private static JsonObject getConfigForModule(int moduleIndex, JsonObject configurations) { @@ -160,7 +172,8 @@ private static JsonObject getConfigForModule(int moduleIndex, JsonObject configu public static void deploy(String configPath) { EventBusOptions ebOptions = new EventBusOptions(); - VertxOptions options = new VertxOptions().setEventBusOptions(ebOptions).setMetricsOptions(getMetricsOptions()); + VertxOptions options = + new VertxOptions().setEventBusOptions(ebOptions).setMetricsOptions(getMetricsOptions()); String config; try { @@ -179,7 +192,6 @@ public static void deploy(String configPath) { setJvmMetrics(); recursiveDeploy(vertx, configuration, 0); - } private static void setVertxInstance(Vertx vertx) { @@ -188,28 +200,52 @@ private static void setVertxInstance(Vertx vertx) { public static void main(String[] args) { - CLI cli = CLI.create("DX DMP-APD Server").setSummary("A CLI to deploy the DMP-APD server") - .addOption(new Option().setLongName("help").setShortName("h").setFlag(true).setDescription("display help")) - .addOption( - new Option().setLongName("config").setShortName("c").setRequired(true).setDescription("configuration file")) - .addOption(new Option().setLongName("isClustered").setShortName("C").setRequired(true).setDefaultValue("false") - .setDescription("Is it being deployed in clustered mode")) - - .addOption(new Option().setLongName("host").setShortName("i").setRequired(true).setDefaultValue("localhost") - .setDescription("public host")) - - .addOption( - new TypedOption().setType(String.class).setLongName("modules").setShortName("m").setRequired(false) - .setDefaultValue("all").setParsedAsList(true).setDescription( - "comma separated list of verticle names to deploy. " - + - "If omitted, or if `all` is passed, all verticles are deployed")); + CLI cli = + CLI.create("DX DMP-APD Server") + .setSummary("A CLI to deploy the DMP-APD server") + .addOption( + new Option() + .setLongName("help") + .setShortName("h") + .setFlag(true) + .setDescription("display help")) + .addOption( + new Option() + .setLongName("config") + .setShortName("c") + .setRequired(true) + .setDescription("configuration file")) + .addOption( + new Option() + .setLongName("isClustered") + .setShortName("C") + .setRequired(true) + .setDefaultValue("false") + .setDescription("Is it being deployed in clustered mode")) + .addOption( + new Option() + .setLongName("host") + .setShortName("i") + .setRequired(true) + .setDefaultValue("localhost") + .setDescription("public host")) + .addOption( + new TypedOption() + .setType(String.class) + .setLongName("modules") + .setShortName("m") + .setRequired(false) + .setDefaultValue("all") + .setParsedAsList(true) + .setDescription( + "comma separated list of verticle names to deploy. " + + "If omitted, or if `all` is passed, all verticles are deployed")); StringBuilder usageString = new StringBuilder(); cli.usage(usageString); CommandLine commandLine = cli.parse(Arrays.asList(args), false); - boolean isDeploymentInClusteredMode = Boolean.parseBoolean(commandLine.getOptionValue("isClustered")); - + boolean isDeploymentInClusteredMode = + Boolean.parseBoolean(commandLine.getOptionValue("isClustered")); if (commandLine.isValid() && !commandLine.isFlagEnabled("help")) { String configPath = commandLine.getOptionValue("config"); @@ -218,7 +254,8 @@ public static void main(String[] args) { List modules = passedModules.stream().distinct().collect(Collectors.toList()); if (!isDeploymentInClusteredMode) { deploy(configPath); - } /* `all` is also passed by default if no -m option given.*/ else if (modules.contains("all")) { + } /* `all` is also passed by default if no -m option given.*/ else if (modules.contains( + "all")) { deployInClusteredMode(configPath, host, List.of()); } else { deployInClusteredMode(configPath, host, modules); @@ -230,13 +267,12 @@ public static void main(String[] args) { } } - /** * Deploy clustered vert.x instance. * * @param configPath the path for JSON config file - * @param host String - * @param modules list of modules to deploy. If list is empty, all modules are deployed + * @param host String + * @param modules list of modules to deploy. If list is empty, all modules are deployed */ public static void deployInClusteredMode(String configPath, String host, List modules) { String config; @@ -256,26 +292,31 @@ public static void deployInClusteredMode(String configPath, String host, List { - if (res.succeeded()) { - vertxInstance = res.result(); - LOGGER.debug(vertxInstance.isMetricsEnabled()); - setJvmMetrics(); - if (modules.isEmpty()) { - recursiveDeploy(vertxInstance, configuration, 0); - } else { - recursiveDeploy(vertxInstance, configuration, modules); - } - } else { - LOGGER.fatal("Could not join cluster"); - } - }); + Vertx.clusteredVertx( + options, + res -> { + if (res.succeeded()) { + vertxInstance = res.result(); + LOGGER.debug(vertxInstance.isMetricsEnabled()); + setJvmMetrics(); + if (modules.isEmpty()) { + recursiveDeploy(vertxInstance, configuration, 0); + } else { + recursiveDeploy(vertxInstance, configuration, modules); + } + } else { + LOGGER.fatal("Could not join cluster"); + } + }); } - - public static ClusterManager getClusterManager(String host, List zookeepers, String clusterId) { + public static ClusterManager getClusterManager( + String host, List zookeepers, String clusterId) { Config config = new Config(); config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); config.getNetworkConfig().setPublicAddress(host); @@ -283,18 +324,28 @@ public static ClusterManager getClusterManager(String host, List zookeep config.setProperty("hazelcast.logging.type", "log4j2"); DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(new ZookeeperDiscoveryStrategyFactory()); - discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.ZOOKEEPER_URL.key(), String.join(",", zookeepers)); + discoveryStrategyConfig.addProperty( + ZookeeperDiscoveryProperties.ZOOKEEPER_URL.key(), String.join(",", zookeepers)); discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.GROUP.key(), clusterId); - config.getNetworkConfig().getJoin().getDiscoveryConfig().addDiscoveryStrategyConfig(discoveryStrategyConfig); + config + .getNetworkConfig() + .getJoin() + .getDiscoveryConfig() + .addDiscoveryStrategyConfig(discoveryStrategyConfig); return new HazelcastClusterManager(config); } public static MetricsOptions getMetricsOptions() { - return new MicrometerMetricsOptions().setPrometheusOptions( - new VertxPrometheusOptions().setEnabled(true).setStartEmbeddedServer(true) + return new MicrometerMetricsOptions() + .setPrometheusOptions( + new VertxPrometheusOptions() + .setEnabled(true) + .setStartEmbeddedServer(true) .setEmbeddedServerOptions(new HttpServerOptions().setPort(9000))) - .setLabels(EnumSet.of(Label.EB_ADDRESS, Label.EB_FAILURE, Label.HTTP_CODE, Label.HTTP_METHOD)).setEnabled(true); + .setLabels( + EnumSet.of(Label.EB_ADDRESS, Label.EB_FAILURE, Label.HTTP_CODE, Label.HTTP_METHOD)) + .setEnabled(true); } public static void setJvmMetrics() { @@ -317,14 +368,16 @@ public static void gracefulShutdown() { LOGGER.debug("number of verticles being undeployed are:" + deployIdSet.size()); // shutdown verticles for (String deploymentId : deployIdSet) { - vertxInstance.undeploy(deploymentId, handler -> { - if (handler.succeeded()) { - LOGGER.debug(deploymentId + " verticle successfully Undeployed"); - latchVerticles.countDown(); - } else { - LOGGER.warn(deploymentId + "Undeploy failed!"); - } - }); + vertxInstance.undeploy( + deploymentId, + handler -> { + if (handler.succeeded()) { + LOGGER.debug(deploymentId + " verticle successfully Undeployed"); + latchVerticles.countDown(); + } else { + LOGGER.warn(deploymentId + "Undeploy failed!"); + } + }); } try { @@ -339,14 +392,15 @@ public static void gracefulShutdown() { try { latchCluster.await(5, TimeUnit.SECONDS); // shutdown vertx - vertxInstance.close(handler -> { - if (handler.succeeded()) { - LOGGER.info("vertx closed succesfully"); - latchVertx.countDown(); - } else { - LOGGER.warn("Vertx didn't close properly, reason:" + handler.cause()); - } - }); + vertxInstance.close( + handler -> { + if (handler.succeeded()) { + LOGGER.info("vertx closed succesfully"); + latchVertx.countDown(); + } else { + LOGGER.warn("Vertx didn't close properly, reason:" + handler.cause()); + } + }); } catch (Exception e) { e.printStackTrace(); } @@ -364,5 +418,4 @@ public static void gracefulShutdown() { e.printStackTrace(); } } - } diff --git a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java index fe24aa5d..5cc3ea55 100644 --- a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java @@ -141,7 +141,6 @@ public Future createPolicy(String orderId) { return policyCreationFuture; }); return policyCreationFuture; - }); return future; diff --git a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java index 20ec3b00..2682a477 100644 --- a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java @@ -70,8 +70,7 @@ public Future executeUpdateQuery(String query, UUID policyUuid, User LOG.debug("inside executeUpdateQuery"); Promise promise = Promise.promise(); Tuple tuple = Tuple.of(policyUuid); - JsonObject param = new JsonObject() - .put("$1", policyUuid.toString()); + JsonObject param = new JsonObject().put("$1", policyUuid.toString()); postgresService.executePreparedQuery( query, @@ -94,10 +93,12 @@ public Future executeUpdateQuery(String query, UUID policyUuid, User /* sending information for auditing */ /* audit info = Request body + response + extra information if any*/ - JsonObject auditInfo = new JsonObject() + JsonObject auditInfo = + new JsonObject() .put("policyId", policyUuid.toString()) .put("policyStatus", Status.DELETED.toString()); - auditingService.handleAuditLogs(user, auditInfo, api.getPoliciesUrl(), HttpMethod.DELETE.toString()); + auditingService.handleAuditLogs( + user, auditInfo, api.getPoliciesUrl(), HttpMethod.DELETE.toString()); promise.complete(responseJson); } @@ -105,17 +106,16 @@ public Future executeUpdateQuery(String query, UUID policyUuid, User LOG.debug("update query failed"); LOG.error("Failure while executing the query : {}", queryHandler.cause().getMessage()); promise.fail( - new JsonObject() - .put(TYPE, HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) - .put(TITLE, ResponseUrn.DB_ERROR_URN.getUrn()) - .put(DETAIL, "Policy could not be deleted, update query failed") - .encode()); + new JsonObject() + .put(TYPE, HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) + .put(TITLE, ResponseUrn.DB_ERROR_URN.getUrn()) + .put(DETAIL, "Policy could not be deleted, update query failed") + .encode()); } }); return promise.future(); } - /** * Queries postgres table to check if the policy given in the request is owned by the provider or * provider delegate, Checks if the policy that is about to be deleted is ACTIVE or DELETED Checks @@ -131,10 +131,9 @@ public Future verifyPolicy(User user, String query, UUID policyUuid) { String ownerId = user.getUserId(); LOG.info("What's the ownerId : " + ownerId); - JsonObject param = new JsonObject() - .put("$1", policyUuid.toString()); + JsonObject param = new JsonObject().put("$1", policyUuid.toString()); postgresService.executePreparedQuery( - query, + query, param, queryHandler -> { if (queryHandler.succeeded()) { diff --git a/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java b/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java index ecb51076..63a52382 100644 --- a/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java +++ b/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java @@ -16,6 +16,7 @@ import static iudx.data.marketplace.policies.util.Constants.FETCH_POLICY; import static iudx.data.marketplace.policies.util.Constants.FETCH_PRODUCT_VARIANT; import static iudx.data.marketplace.product.util.Constants.RESULTS; + public class FetchPolicyUsingPvId { private static final Logger LOG = LoggerFactory.getLogger(FetchPolicyUsingPvId.class); private PostgresService postgresService; diff --git a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java index 07138fb9..914c43b6 100644 --- a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java @@ -21,9 +21,8 @@ import static iudx.data.marketplace.policies.util.Constants.GET_POLICY_4_PROVIDER_QUERY; public class GetPolicy { - private static final Logger LOG = LoggerFactory.getLogger(GetPolicy.class); public static final String FAILURE_MESSAGE = "Policy could not be fetched"; - + private static final Logger LOG = LoggerFactory.getLogger(GetPolicy.class); private final PostgresService postgresService; public GetPolicy(PostgresService postgresService) { diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyService.java b/src/main/java/iudx/data/marketplace/policies/PolicyService.java index 39cb54ab..69f54721 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyService.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyService.java @@ -25,5 +25,6 @@ static PolicyService createProxy(Vertx vertx, String address) { Future getPolicies(User user); Future verifyPolicy(JsonObject jsonObject); + Future checkPolicy(String productVariantId, User user); } diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyServiceImpl.java b/src/main/java/iudx/data/marketplace/policies/PolicyServiceImpl.java index 1e2ff00f..71b75eef 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyServiceImpl.java @@ -6,32 +6,32 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class PolicyServiceImpl implements PolicyService{ - private static final Logger LOG = LoggerFactory.getLogger(PolicyServiceImpl.class); - private final DeletePolicy deletePolicy; - private final GetPolicy getPolicy; - private final CreatePolicy createPolicy; - private final VerifyPolicy verifyPolicy; - private final FetchPolicyUsingPvId fetchPolicy; +public class PolicyServiceImpl implements PolicyService { + private static final Logger LOG = LoggerFactory.getLogger(PolicyServiceImpl.class); + private final DeletePolicy deletePolicy; + private final GetPolicy getPolicy; + private final CreatePolicy createPolicy; + private final VerifyPolicy verifyPolicy; + private final FetchPolicyUsingPvId fetchPolicy; - JsonObject config; + JsonObject config; - public PolicyServiceImpl( - DeletePolicy deletePolicy, - CreatePolicy createPolicy, - GetPolicy getPolicy, - VerifyPolicy verifyPolicy, - FetchPolicyUsingPvId fetchPolicyUsingPvId) { - this.deletePolicy = deletePolicy; - this.createPolicy = createPolicy; - this.getPolicy = getPolicy; - this.verifyPolicy = verifyPolicy; - this.fetchPolicy = fetchPolicyUsingPvId; - } + public PolicyServiceImpl( + DeletePolicy deletePolicy, + CreatePolicy createPolicy, + GetPolicy getPolicy, + VerifyPolicy verifyPolicy, + FetchPolicyUsingPvId fetchPolicyUsingPvId) { + this.deletePolicy = deletePolicy; + this.createPolicy = createPolicy; + this.getPolicy = getPolicy; + this.verifyPolicy = verifyPolicy; + this.fetchPolicy = fetchPolicyUsingPvId; + } - @Override - public Future createPolicy(String orderId) { - Promise promise = Promise.promise(); + @Override + public Future createPolicy(String orderId) { + Promise promise = Promise.promise(); createPolicy .createPolicy(orderId) .onComplete( @@ -42,78 +42,78 @@ public Future createPolicy(String orderId) { promise.fail(handler.cause().getMessage()); } }); - return promise.future(); - } + return promise.future(); + } - @Override - public Future deletePolicy(JsonObject policy, User user) { - Promise promise = Promise.promise(); - this.deletePolicy - .initiateDeletePolicy(policy, user) - .onComplete( - handler -> { - if (handler.succeeded()) { - LOG.info("Successfully deleted the policy"); - promise.complete(handler.result()); - } else { - LOG.error("Failed to delete the policy"); - promise.fail(handler.cause().getMessage()); - } - }); - return promise.future(); - } + @Override + public Future deletePolicy(JsonObject policy, User user) { + Promise promise = Promise.promise(); + this.deletePolicy + .initiateDeletePolicy(policy, user) + .onComplete( + handler -> { + if (handler.succeeded()) { + LOG.info("Successfully deleted the policy"); + promise.complete(handler.result()); + } else { + LOG.error("Failed to delete the policy"); + promise.fail(handler.cause().getMessage()); + } + }); + return promise.future(); + } - @Override - public Future getPolicies(User user) { - Promise promise = Promise.promise(); - this.getPolicy - .initiateGetPolicy(user) - .onComplete( - handler -> { - if (handler.succeeded()) { - LOG.info("GET policy successful"); - promise.complete(handler.result()); - } else { - LOG.error("Failed to execute GET policy"); - promise.fail(handler.cause().getMessage()); - } - }); - return promise.future(); - } + @Override + public Future getPolicies(User user) { + Promise promise = Promise.promise(); + this.getPolicy + .initiateGetPolicy(user) + .onComplete( + handler -> { + if (handler.succeeded()) { + LOG.info("GET policy successful"); + promise.complete(handler.result()); + } else { + LOG.error("Failed to execute GET policy"); + promise.fail(handler.cause().getMessage()); + } + }); + return promise.future(); + } - @Override - public Future verifyPolicy(JsonObject jsonObject) { - Promise promise = Promise.promise(); + @Override + public Future verifyPolicy(JsonObject jsonObject) { + Promise promise = Promise.promise(); - this.verifyPolicy - .initiateVerifyPolicy(jsonObject) - .onComplete( - handler -> { - if (handler.succeeded()) { - promise.complete(handler.result()); - } else { - LOG.error("Failed to verify policy"); - promise.fail(handler.cause().getMessage()); - } - }); - return promise.future(); - } + this.verifyPolicy + .initiateVerifyPolicy(jsonObject) + .onComplete( + handler -> { + if (handler.succeeded()) { + promise.complete(handler.result()); + } else { + LOG.error("Failed to verify policy"); + promise.fail(handler.cause().getMessage()); + } + }); + return promise.future(); + } - @Override - public Future checkPolicy(String productVariantId, User user) { - Promise promise = Promise.promise(); + @Override + public Future checkPolicy(String productVariantId, User user) { + Promise promise = Promise.promise(); - this.fetchPolicy - .checkIfPolicyExists(productVariantId, user) - .onComplete( - handler -> { - if (handler.succeeded()) { - promise.complete(handler.result()); - } else { - LOG.error("Failed to verify policy"); - promise.fail(handler.cause().getMessage()); - } - }); - return promise.future(); - } + this.fetchPolicy + .checkIfPolicyExists(productVariantId, user) + .onComplete( + handler -> { + if (handler.succeeded()) { + promise.complete(handler.result()); + } else { + LOG.error("Failed to verify policy"); + promise.fail(handler.cause().getMessage()); + } + }); + return promise.future(); + } } diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java index 655e89a2..233f7b94 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java @@ -46,7 +46,8 @@ public void start() { verifyPolicy = new VerifyPolicy(postgresServiceImpl); fetchPolicyUsingPvId = new FetchPolicyUsingPvId(postgresServiceImpl); policyService = - new PolicyServiceImpl(deletePolicy, createPolicy, getPolicy, verifyPolicy,fetchPolicyUsingPvId); + new PolicyServiceImpl( + deletePolicy, createPolicy, getPolicy, verifyPolicy, fetchPolicyUsingPvId); new ServiceBinder(vertx) .setAddress(POLICY_SERVICE_ADDRESS) diff --git a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java index e3399b1c..f4958739 100644 --- a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java @@ -41,17 +41,16 @@ public Future initiateVerifyPolicy(JsonObject request) { String userEmail = request.getJsonObject("user").getString("email"); UUID itemId = UUID.fromString(request.getJsonObject("item").getString("itemId")); - /*check if the orderId is present in the context object*/ - if(request.containsKey("context") && StringUtils.isNotBlank(request.getJsonObject("context").getString("orderId"))) - { - String orderId = request.getJsonObject("context").getString("orderId"); - setOrderId(orderId); - } + /*check if the orderId is present in the context object*/ + if (request.containsKey("context") + && StringUtils.isNotBlank(request.getJsonObject("context").getString("orderId"))) { + String orderId = request.getJsonObject("context").getString("orderId"); + setOrderId(orderId); + } Future checkForExistingPolicy = checkExistingPoliciesForId(itemId, ownerId, userEmail); - Future getPolicyDetail = checkForExistingPolicy.compose( isPolicyExist -> { @@ -82,57 +81,58 @@ private Future checkExistingPoliciesForId( Tuple selectTuples = Tuple.of(itemId, ownerId, Status.ACTIVE, userEmailId); String query; - JsonObject params = new JsonObject() + JsonObject params = + new JsonObject() .put("itemId", itemId.toString()) .put("ownerId", ownerId.toString()) .put("status", Status.ACTIVE) .put("userEmailId", userEmailId); - if(StringUtils.isNotBlank(getOrderId())) - { - query = CHECK_POLICY_FROM_ORDER_ID; - params.put("orderId", getOrderId()); - } else { - query = CHECK_EXISTING_POLICY; - } - - Promise promise = Promise.promise(); - postgresService - .executePreparedQuery(query, params, handler -> { - if(handler.failed()){ - LOGGER.error( - "isPolicyForIdExist fail, DB execution failed :: {}", - handler.cause().getMessage()); + if (StringUtils.isNotBlank(getOrderId())) { + query = CHECK_POLICY_FROM_ORDER_ID; + params.put("orderId", getOrderId()); + } else { + query = CHECK_EXISTING_POLICY; + } + + Promise promise = Promise.promise(); + postgresService.executePreparedQuery( + query, + params, + handler -> { + if (handler.failed()) { + LOGGER.error( + "isPolicyForIdExist fail, DB execution failed :: {}", handler.cause().getMessage()); + promise.fail( + generateErrorResponse( + INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); + } else { + JsonArray policy = handler.result().getJsonArray(RESULT); + boolean isPolicyNotPresent = policy.isEmpty(); + if (isPolicyNotPresent) { + LOGGER.error("No matching policy"); + promise.complete(new JsonObject()); + } else { + LOGGER.debug("policy exists : {} ", handler.result().encode()); + if (handler.result().getJsonArray(RESULT).size() > 1 + && query.equals(CHECK_POLICY_FROM_ORDER_ID)) { + LOGGER.fatal( + "Fetched more than 1 policy for a single" + + " resource with a single orderId : {}", + orderId); promise.fail( - generateErrorResponse( - INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); - } - else - { - JsonArray policy = handler.result().getJsonArray(RESULT); - boolean isPolicyNotPresent = policy.isEmpty(); - if (isPolicyNotPresent) { - LOGGER.error("No matching policy"); - promise.complete(new JsonObject()); - } else { - LOGGER.debug("policy exists : {} ", handler.result().encode()); - if(handler.result().getJsonArray(RESULT).size() > 1 && query.equals(CHECK_POLICY_FROM_ORDER_ID)) - { - LOGGER.fatal("Fetched more than 1 policy for a single" + - " resource with a single orderId : {}",orderId); - promise.fail( - generateErrorResponse( - INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); - return; - } - JsonObject result = handler.result().getJsonArray(RESULT).getJsonObject(0); - JsonObject constraints = result.getJsonObject("constraints"); - String policyId = result.getString("_id"); - JsonObject response = - new JsonObject().put("constraints", constraints).put("id", policyId); - promise.complete(response); - } + generateErrorResponse( + INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR.getDescription())); + return; + } + JsonObject result = handler.result().getJsonArray(RESULT).getJsonObject(0); + JsonObject constraints = result.getJsonObject("constraints"); + String policyId = result.getString("_id"); + JsonObject response = + new JsonObject().put("constraints", constraints).put("id", policyId); + promise.complete(response); } + } }); return promise.future(); @@ -146,13 +146,11 @@ public String generateErrorResponse(HttpStatusCode httpStatusCode, String errorM .encode(); } - private String getOrderId() { - return this.orderId; - } - private void setOrderId(String orderId) - { - this.orderId = orderId; - } - + private String getOrderId() { + return this.orderId; + } + private void setOrderId(String orderId) { + this.orderId = orderId; + } } diff --git a/src/main/java/iudx/data/marketplace/policies/util/Status.java b/src/main/java/iudx/data/marketplace/policies/util/Status.java index 3a34c53e..7a39cadd 100644 --- a/src/main/java/iudx/data/marketplace/policies/util/Status.java +++ b/src/main/java/iudx/data/marketplace/policies/util/Status.java @@ -1,5 +1,6 @@ package iudx.data.marketplace.policies.util; + public enum Status { - ACTIVE, - DELETED; + ACTIVE, + DELETED; } diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java index 15667a15..222b25d1 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java @@ -28,6 +28,17 @@ @ProxyGen public interface PostgresService { + /** + * The createProxy helps the code generation blocks to generate proxy code. + * @param vertx which is the vertx instance + * @param address which is the proxy address + * @return PostgresServiceVertxRBProxy which is a service proxy + */ + @GenIgnore + static PostgresService createProxy(Vertx vertx, String address) { + return new PostgresServiceVertxEBProxy(vertx, address); + } + /** * The executeQuery implements single query operations with the database. * @@ -70,17 +81,6 @@ PostgresService executePreparedQuery( @Fluent PostgresService executeTransaction(final List queries, Handler> handler); - /** - * The createProxy helps the code generation blocks to generate proxy code. - * @param vertx which is the vertx instance - * @param address which is the proxy address - * @return PostgresServiceVertxRBProxy which is a service proxy - */ - @GenIgnore - static PostgresService createProxy(Vertx vertx, String address) { - return new PostgresServiceVertxEBProxy(vertx, address); - } - @Fluent PostgresService checkPolicy(final String query,final JsonObject param, Handler> handler); } diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java index ef2a7345..d77fe094 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java @@ -36,6 +36,38 @@ public PostgresServiceImpl(final PgPool pgclient) { this.client = pgclient; } + private static Future executeBatch( + SqlConnection conn, ConcurrentLinkedQueue statements) { + try { + var statement = statements.poll(); + if (statement == null) { + return Future.succeededFuture(); + } + Promise promise = Promise.promise(); + + Collector> rowCollector = + Collectors.mapping(row -> row.toJson(), Collectors.toList()); + conn.query(statement) + .collecting(rowCollector) + .execute() + .map(rows -> rows.value()) + .onSuccess( + successHandler -> { + executeBatch(conn, statements).onComplete(h -> { + promise.complete(); + }); + }) + .onFailure( + failureHandler -> { + LOGGER.debug("Failure : {}",failureHandler.getMessage() ); + LOGGER.error("Fail db"); + promise.fail(failureHandler); + }); + return promise.future(); + } catch (Throwable t) { + return Future.failedFuture(t); + } + } @Override public PostgresService executeQuery( @@ -98,39 +130,6 @@ public PostgresService executeCountQuery( return this; } - private static Future executeBatch( - SqlConnection conn, ConcurrentLinkedQueue statements) { - try { - var statement = statements.poll(); - if (statement == null) { - return Future.succeededFuture(); - } - Promise promise = Promise.promise(); - - Collector> rowCollector = - Collectors.mapping(row -> row.toJson(), Collectors.toList()); - conn.query(statement) - .collecting(rowCollector) - .execute() - .map(rows -> rows.value()) - .onSuccess( - successHandler -> { - executeBatch(conn, statements).onComplete(h -> { - promise.complete(); - }); - }) - .onFailure( - failureHandler -> { - LOGGER.debug("Failure : {}",failureHandler.getMessage() ); - LOGGER.error("Fail db"); - promise.fail(failureHandler); - }); - return promise.future(); - } catch (Throwable t) { - return Future.failedFuture(t); - } - } - @Override public PostgresService executeTransaction( final List queries, Handler> handler) { diff --git a/src/main/java/iudx/data/marketplace/product/ProductService.java b/src/main/java/iudx/data/marketplace/product/ProductService.java index 6401480d..bbe044f2 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductService.java +++ b/src/main/java/iudx/data/marketplace/product/ProductService.java @@ -10,7 +10,8 @@ import io.vertx.core.json.JsonObject; import iudx.data.marketplace.policies.User; -@VertxGen @ProxyGen +@VertxGen +@ProxyGen public interface ProductService { /** @@ -25,7 +26,6 @@ static ProductService createProxy(Vertx vertx, String address) { return new ProductServiceVertxEBProxy(vertx, address); } - /** * The createProduct method implements the creation of a product on the IUDX data marketplace. * @@ -34,7 +34,8 @@ static ProductService createProxy(Vertx vertx, String address) { * @return ProductService which is a service */ @Fluent - ProductService createProduct(User user, JsonObject request, Handler> handler); + ProductService createProduct( + User user, JsonObject request, Handler> handler); /** * The deleteProduct method implements the soft delete of a product on the IUDX data marketplace. @@ -44,7 +45,8 @@ static ProductService createProxy(Vertx vertx, String address) { * @return ProductService which is a service */ @Fluent - ProductService deleteProduct(User user, JsonObject request, Handler> handler); + ProductService deleteProduct( + User user, JsonObject request, Handler> handler); /** * The listProduct method fetches some or all the products available on the IUDX data marketplace @@ -54,6 +56,6 @@ static ProductService createProxy(Vertx vertx, String address) { * @return ProductService which is a service */ @Fluent - ProductService listProducts(User user, JsonObject request, Handler> handler); - + ProductService listProducts( + User user, JsonObject request, Handler> handler); } diff --git a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java index 4b1a329d..2a30dd2a 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java @@ -62,18 +62,17 @@ private static boolean isSameProviderForAll(JsonArray resourceDetails) { return sameProviderForAll; } - private boolean isSameApdUrlForAll(JsonArray resourceDetails) { - LOGGER.debug("current APD URL is : {}", this.apdUrl); - String currentApdUrl = this.apdUrl; - boolean sameApdUrl = true; - for (int i = 0; i < resourceDetails.size() && sameApdUrl; i++) { - String apdUrlOfResource = resourceDetails.getJsonObject(i).getString(APD_URL); - LOGGER.debug("APD URL of the current resource is : {}", apdUrlOfResource); - sameApdUrl = - apdUrlOfResource.equals(currentApdUrl); - } - return sameApdUrl; + private boolean isSameApdUrlForAll(JsonArray resourceDetails) { + LOGGER.debug("current APD URL is : {}", this.apdUrl); + String currentApdUrl = this.apdUrl; + boolean sameApdUrl = true; + for (int i = 0; i < resourceDetails.size() && sameApdUrl; i++) { + String apdUrlOfResource = resourceDetails.getJsonObject(i).getString(APD_URL); + LOGGER.debug("APD URL of the current resource is : {}", apdUrlOfResource); + sameApdUrl = apdUrlOfResource.equals(currentApdUrl); } + return sameApdUrl; + } @Override public ProductService createProduct( diff --git a/src/main/java/iudx/data/marketplace/product/ProductVerticle.java b/src/main/java/iudx/data/marketplace/product/ProductVerticle.java index da45c675..17449543 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductVerticle.java +++ b/src/main/java/iudx/data/marketplace/product/ProductVerticle.java @@ -30,13 +30,17 @@ public void start() throws Exception { razorPayService = RazorPayService.createProxy(vertx, RAZORPAY_SERVICE_ADDRESS); isAccountActivationCheckBeingDone = config().getBoolean("isAccountActivationCheckBeingDone"); - if(!isAccountActivationCheckBeingDone) - { - LOGGER.warn("\n\n" +"account activation check is set to false. Enable it in production" + "\n\n" ); + if (!isAccountActivationCheckBeingDone) { + LOGGER.warn( + "\n\n" + "account activation check is set to false. Enable it in production" + "\n\n"); } - productService = new ProductServiceImpl(config(), postgresService, catService, razorPayService, isAccountActivationCheckBeingDone); - - + productService = + new ProductServiceImpl( + config(), + postgresService, + catService, + razorPayService, + isAccountActivationCheckBeingDone); binder = new ServiceBinder(vertx); consumer = diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index 58eba946..200a55ed 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -38,39 +38,39 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso // Product Table entry queries.add( - new StringBuilder( - INSERT_PRODUCT_QUERY - .replace("$0", productTable) - .replace("$1", productID) - .replace("$2", providerID) - .replace("$3", providerName) - .replace("$4", Status.ACTIVE.toString())) - .toString()); + new StringBuilder( + INSERT_PRODUCT_QUERY + .replace("$0", productTable) + .replace("$1", productID) + .replace("$2", providerID) + .replace("$3", providerName) + .replace("$4", Status.ACTIVE.toString())) + .toString()); // Resource Table entry resourceDetails.forEach( - resource -> { - queries.add( - new StringBuilder( - INSERT_RESOURCE_QUERY - .replace("$0", resourceTable) - .replace("$1", ((JsonObject) resource).getString(RESOURCE_ID)) - .replace("$2", ((JsonObject) resource).getString(RESOURCE_NAME)) - .replace("$3", providerID) - .replace("$4", providerName) - .replace("$5", request.getString(RESOURCE_SERVER)) - .replace("$6", ((JsonObject) resource).getString("accessPolicy"))) - .toString()); - - // Product-Resource relationship table entry - queries.add( - new StringBuilder( - INSERT_P_R_REL_QUERY - .replace("$0", productResourceRelationTable) - .replace("$1", productID) - .replace("$2", ((JsonObject) resource).getString(RESOURCE_ID))) - .toString()); - }); + resource -> { + queries.add( + new StringBuilder( + INSERT_RESOURCE_QUERY + .replace("$0", resourceTable) + .replace("$1", ((JsonObject) resource).getString(RESOURCE_ID)) + .replace("$2", ((JsonObject) resource).getString(RESOURCE_NAME)) + .replace("$3", providerID) + .replace("$4", providerName) + .replace("$5", request.getString(RESOURCE_SERVER)) + .replace("$6", ((JsonObject) resource).getString("accessPolicy"))) + .toString()); + + // Product-Resource relationship table entry + queries.add( + new StringBuilder( + INSERT_P_R_REL_QUERY + .replace("$0", productResourceRelationTable) + .replace("$1", productID) + .replace("$2", ((JsonObject) resource).getString(RESOURCE_ID))) + .toString()); + }); LOGGER.debug("Queries : " + queries); return queries; @@ -80,11 +80,11 @@ public String buildListProductsQuery(JsonObject request) { StringBuilder query; query = - new StringBuilder( - LIST_PRODUCT_FOR_RESOURCE - .replace("$0", productTable) - .replace("$9", productResourceRelationTable) - .replace("$8", resourceTable)); + new StringBuilder( + LIST_PRODUCT_FOR_RESOURCE + .replace("$0", productTable) + .replace("$9", productResourceRelationTable) + .replace("$8", resourceTable)); if (request.containsKey("resourceId")) { query.append(" and rt._id=$4"); } @@ -96,13 +96,13 @@ public String buildListProductsQuery(JsonObject request) { public String buildProductDetailsQuery(String productID, String providerId) { StringBuilder query = - new StringBuilder( - SELECT_PRODUCT_DETAILS - .replace("$0", productTable) - .replace("$9", productResourceRelationTable) - .replace("$8", resourceTable) - .replace("$1", productID) - .replace("$2", providerId)); + new StringBuilder( + SELECT_PRODUCT_DETAILS + .replace("$0", productTable) + .replace("$9", productResourceRelationTable) + .replace("$8", resourceTable) + .replace("$1", productID) + .replace("$2", providerId)); return query.toString(); } @@ -111,23 +111,22 @@ public String buildCreateProductVariantQuery(JsonObject request) { JsonArray resources = request.getJsonArray(RESOURCES_ARRAY); - // UUID for each product variant. String pvID = supplier.get(); LOGGER.debug("request is : " + request.encodePrettily()); StringBuilder query = - new StringBuilder( - INSERT_PV_QUERY - .replace("$0", productVariantTable) - .replace("$1", pvID) - .replace("$2", request.getString("provider_id")) - .replace("$3", request.getString(PRODUCT_ID)) - .replace("$4", request.getString(Constants.PRODUCT_VARIANT_NAME)) - .replace("$5", resources.encode()) - .replace("$6", request.getDouble(PRICE).toString()) - .replace("$7", request.getInteger(DURATION).toString()) - .replace("$s", Status.ACTIVE.toString())); + new StringBuilder( + INSERT_PV_QUERY + .replace("$0", productVariantTable) + .replace("$1", pvID) + .replace("$2", request.getString("provider_id")) + .replace("$3", request.getString(PRODUCT_ID)) + .replace("$4", request.getString(Constants.PRODUCT_VARIANT_NAME)) + .replace("$5", resources.encode()) + .replace("$6", request.getDouble(PRICE).toString()) + .replace("$7", request.getInteger(DURATION).toString()) + .replace("$s", Status.ACTIVE.toString())); LOGGER.debug(query); return query.toString(); @@ -135,34 +134,27 @@ public String buildCreateProductVariantQuery(JsonObject request) { public String updateProductVariantStatusQuery(String productID, String variant) { StringBuilder query = - new StringBuilder( - UPDATE_PV_STATUS - .replace("$0", productVariantTable) - .replace("$1", productID) - .replace("$2", variant) - .replace("$3", Status.ACTIVE.toString()) - .replace("$4", Status.INACTIVE.toString())); + new StringBuilder( + UPDATE_PV_STATUS + .replace("$0", productVariantTable) + .replace("$1", productID) + .replace("$2", variant) + .replace("$3", Status.ACTIVE.toString()) + .replace("$4", Status.INACTIVE.toString())); LOGGER.debug("Query to update pv status : {}", query); return query.toString(); } - public String checkProductVariantExistence(String productId, String variantName) - { + public String checkProductVariantExistence(String productId, String variantName) { StringBuilder query = - new StringBuilder(CHECK_IF_PV_EXISTS - .replace("$1", productId) - .replace("$2", variantName)); + new StringBuilder(CHECK_IF_PV_EXISTS.replace("$1", productId).replace("$2", variantName)); LOGGER.debug("Query to check pv existence : {}", query); return query.toString(); } - public String checkIfProductExists(String productId, String providerId) - { - StringBuilder query = new StringBuilder( - CHECK_IF_PRODUCT_EXISTS - .replace("$1", productId) - ); + public String checkIfProductExists(String productId, String providerId) { + StringBuilder query = new StringBuilder(CHECK_IF_PRODUCT_EXISTS.replace("$1", productId)); LOGGER.debug("Query to check if product exists : {}", query); return query.toString(); } @@ -182,23 +174,22 @@ public String updateProductVariantStatusQuery(String productVariantId) { public String selectProductVariant(String productID, String variantName) { StringBuilder query = - new StringBuilder( - SELECT_PV_QUERY - .replace("$0", productVariantTable) - .replace("$1", productID) - .replace("$2", variantName) - .replace("$3", Status.ACTIVE.toString())); + new StringBuilder( + SELECT_PV_QUERY + .replace("$0", productVariantTable) + .replace("$1", productID) + .replace("$2", variantName) + .replace("$3", Status.ACTIVE.toString())); LOGGER.debug("select product variant query : {}", query); return query.toString(); } public String listProductVariants(JsonObject request, String providerId) { - StringBuilder query = new StringBuilder( - FETCH_ACTIVE_PRODUCT_VARIANTS); + StringBuilder query = new StringBuilder(FETCH_ACTIVE_PRODUCT_VARIANTS); query.append(" AND P.\"providerId\"=$3"); - if(request.containsKey(Constants.PRODUCT_VARIANT_NAME)) { + if (request.containsKey(Constants.PRODUCT_VARIANT_NAME)) { query.append(" AND P.\"productVariantName\"=$4"); } query.append(" ORDER BY P.\"updatedAt\" DESC"); @@ -215,121 +206,133 @@ public JsonObject buildMessageForRmq(JsonObject request) { return request; } - public String listPurchaseForProviderDuringPendingStatus(String providerId, String resourceId, String productId, String rsUrl) - { + public String listPurchaseForProviderDuringPendingStatus( + String providerId, String resourceId, String productId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); StringBuilder query = - new StringBuilder(LIST_PENDING_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2", rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_PENDING_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_PENDING_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_PENDING_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_PENDING_PAYMENTS_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_PENDING_PAYMENTS_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } query.append(" \n ORDER BY I.modified_at DESC "); LOGGER.debug("Query :" + query); return query.toString(); } - public String listPurchaseForProviderDuringFailedPayment(String providerId, String resourceId, String productId, String rsUrl) - { + public String listPurchaseForProviderDuringFailedPayment( + String providerId, String resourceId, String productId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); StringBuilder query = - new StringBuilder(LIST_FAILED_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2",rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_FAILED_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_FAILED_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_FAILED_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_FAILED_PAYMENTS_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_FAILED_PAYMENTS_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } query.append(" \n ORDER BY I.modified_at DESC "); LOGGER.debug("Query :" + query); return query.toString(); } - public String listSuccessfulPurchaseForProvider(String providerId, String resourceId, String productId, - String rsUrl) - { + public String listSuccessfulPurchaseForProvider( + String providerId, String resourceId, String productId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); StringBuilder query = - new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2", rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER.replace("$1", providerId).replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", providerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", providerId) + .replace("$3", rsUrl)); } - query.append(" \n ORDER BY I.modified_at DESC "); LOGGER.debug("Query :" + query); return query.toString(); } - public String listPurchaseForConsumerDuringPendingPayment(String consumerId, String resourceId, String productId, String orderId, String rsUrl) - { + + public String listPurchaseForConsumerDuringPendingPayment( + String consumerId, String resourceId, String productId, String orderId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); boolean isOrderIdPresent = StringUtils.isNotBlank(orderId); StringBuilder query = - new StringBuilder(LIST_PENDING_PAYMENTS_4_CONSUMER.replace("$1", consumerId).replace("$2",rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_PENDING_PAYMENTS_4_CONSUMER.replace("$1", consumerId).replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isOrderIdPresent) - { - query = new StringBuilder(LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER - .replace("$1", orderId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isOrderIdPresent) { + query = + new StringBuilder( + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER + .replace("$1", orderId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } query.append(" \n ORDER BY I.modified_at DESC "); @@ -337,81 +340,85 @@ public String listPurchaseForConsumerDuringPendingPayment(String consumerId, Str return query.toString(); } - - public String listPurchaseForConsumerDuringFailurePayment(String consumerId, String resourceId, String productId, String orderId, String rsUrl) - { + public String listPurchaseForConsumerDuringFailurePayment( + String consumerId, String resourceId, String productId, String orderId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); boolean isOrderIdPresent = StringUtils.isNotBlank(orderId); StringBuilder query = - new StringBuilder(LIST_FAILED_PAYMENTS_4_CONSUMER.replace("$1", consumerId).replace("$2", rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_FAILED_PAYMENTS_4_CONSUMER.replace("$1", consumerId).replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isOrderIdPresent) - { - query = new StringBuilder(LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER - .replace("$1", orderId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isOrderIdPresent) { + query = + new StringBuilder( + LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER + .replace("$1", orderId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } query.append(" \n ORDER BY I.modified_at DESC "); LOGGER.debug("Query :" + query); return query.toString(); } - public String listPurchaseForConsumerDuringSuccessfulPayment(String consumerId, String resourceId, String productId, String orderId, String rsUrl) - { + public String listPurchaseForConsumerDuringSuccessfulPayment( + String consumerId, String resourceId, String productId, String orderId, String rsUrl) { boolean isProductIdPresent = StringUtils.isNotBlank(productId); boolean isResourceIdPresent = StringUtils.isNotBlank(resourceId); boolean isOrderIdPresent = StringUtils.isNotBlank(orderId); StringBuilder query = - new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_PAYMENTS_4_CONSUMER.replace("$1", consumerId).replace("$2", rsUrl)); - - if(isProductIdPresent && !isResourceIdPresent) - { - query = new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT - .replace("$1", productId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_PAYMENTS_4_CONSUMER + .replace("$1", consumerId) + .replace("$2", rsUrl)); + + if (isProductIdPresent && !isResourceIdPresent) { + query = + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT + .replace("$1", productId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isResourceIdPresent && !isProductIdPresent) - { - query = new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE - .replace("$1", resourceId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isResourceIdPresent && !isProductIdPresent) { + query = + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE + .replace("$1", resourceId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } - if(isOrderIdPresent) - { - query = new StringBuilder(LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER - .replace("$1", orderId) - .replace("$2", consumerId) - .replace("$3", rsUrl)); + if (isOrderIdPresent) { + query = + new StringBuilder( + LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER + .replace("$1", orderId) + .replace("$2", consumerId) + .replace("$3", rsUrl)); } query.append(" \n ORDER BY I.modified_at DESC "); LOGGER.debug("Query :" + query); return query.toString(); } - - - - - -} \ No newline at end of file +} diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java index b3b696df..80e775b8 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java @@ -10,7 +10,8 @@ import io.vertx.core.json.JsonObject; import iudx.data.marketplace.policies.User; -@VertxGen @ProxyGen +@VertxGen +@ProxyGen public interface ProductVariantService { /** @@ -26,56 +27,66 @@ static ProductVariantService createProxy(Vertx vertx, String address) { } /** - * The createProductVariant method implements the creation of a product variant on the IUDX data marketplace. + * The createProductVariant method implements the creation of a product variant on the IUDX data + * marketplace. * * @param request which is a JsonObject * @param handler which is a Request Handler * @return ProductVariantService which is a service */ @Fluent - ProductVariantService createProductVariant(User user, JsonObject request, Handler> handler); + ProductVariantService createProductVariant( + User user, JsonObject request, Handler> handler); /** - * The updateProductVariant method implements the update of a product variant on the IUDX data marketplace. + * The updateProductVariant method implements the update of a product variant on the IUDX data + * marketplace. * * @param request which is a JsonObject * @param handler which is a Request Handler * @return ProductVariantService which is a service */ @Fluent - ProductVariantService updateProductVariant(User user, JsonObject request, Handler> handler); + ProductVariantService updateProductVariant( + User user, JsonObject request, Handler> handler); /** - * The deleteProductVariant method implements the soft delete of a product variant on the IUDX data marketplace. + * The deleteProductVariant method implements the soft delete of a product variant on the IUDX + * data marketplace. * * @param request which is a JsonObject * @param handler which is a Request Handler * @return ProductVariantService which is a service */ @Fluent - ProductVariantService deleteProductVariant(User user, JsonObject request, Handler> handler); + ProductVariantService deleteProductVariant( + User user, JsonObject request, Handler> handler); /** - * The listProductVariant method implements the fetch of product variant(s) on the IUDX data marketplace. + * The listProductVariant method implements the fetch of product variant(s) on the IUDX data + * marketplace. + * * @param user which is the calling user Object * @param request which is a JsonObject * @param handler which is a Request Handler * @return ProductVariantService which is a service */ @Fluent - ProductVariantService listProductVariants(User user, JsonObject request, Handler> handler); - + ProductVariantService listProductVariants( + User user, JsonObject request, Handler> handler); /** - * List purchase will fetch invoice related info, provider, consumer and product variant related information - * After the purchase is made. Both successful and failed payments are displayed - * List purchase will list all the purchases if no query parameters are given - * It can also list purchases based on the productId, resourceId if it is given in the query parameter + * List purchase will fetch invoice related info, provider, consumer and product variant related + * information After the purchase is made. Both successful and failed payments are displayed List + * purchase will list all the purchases if no query parameters are given It can also list + * purchases based on the productId, resourceId if it is given in the query parameter + * * @param user Provider user * @param request query param if any * @param handler Asynchronous JsonObject handler that contains the list of purchases * @return */ @Fluent - ProductVariantService listPurchase(User user, JsonObject request, Handler> handler); + ProductVariantService listPurchase( + User user, JsonObject request, Handler> handler); } diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java index 10112b0c..49c515f0 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java @@ -58,7 +58,7 @@ public ProductVariantService createProductVariant( .withType(ResponseUrn.BAD_REQUEST_URN.getUrn()) .withTitle(ResponseUrn.BAD_REQUEST_URN.getMessage()) .withDetail( - "Product Variant cannot be created as product is in INACTIVE state or is not found") + "Product Variant cannot be created as product is in INACTIVE state or is not found") .getResponse(); return Future.failedFuture(failureMessage); } @@ -92,9 +92,9 @@ public ProductVariantService createProductVariant( JsonObject res = pdfHandler.result().getJsonArray(RESULTS).getJsonObject(0); JsonArray resResources = res.getJsonArray(RESOURCES_ARRAY); if (resources.size() != resResources.size()) { - /* if the number of resources listed while creating product variant != - * number of resources listed while creating product - * then bad request is thrown and returned without creating product variant */ + /* if the number of resources listed while creating product variant != + * number of resources listed while creating product + * then bad request is thrown and returned without creating product variant */ String detail = "Number of resources is incorrect, required : " + resResources.size(); String failureMessage = diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java index 04e3e96f..d21e2769 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java @@ -15,7 +15,7 @@ public class ProductVariantVerticle extends AbstractVerticle { public static final Logger LOGGER = LogManager.getLogger(ProductVariantVerticle.class); private MessageConsumer consumer; - private ServiceBinder binder; + private ServiceBinder binder; private PostgresService postgresService; private ProductVariantService variantService; private Util util; @@ -27,7 +27,10 @@ public void start() throws Exception { variantService = new ProductVariantServiceImpl(config(), postgresService, util); binder = new ServiceBinder(vertx); - consumer = binder.setAddress(PRODUCT_VARIANT_SERVICE_ADDRESS).register(ProductVariantService.class, variantService); + consumer = + binder + .setAddress(PRODUCT_VARIANT_SERVICE_ADDRESS) + .register(ProductVariantService.class, variantService); LOGGER.info("Product Variant Service started"); } @@ -36,4 +39,3 @@ public void stop() { binder.unregister(consumer); } } - diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java index 48f2e4cf..e48d54b1 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java @@ -7,7 +7,8 @@ import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; -@VertxGen @ProxyGen +@VertxGen +@ProxyGen public interface RazorPayService { /** * The createProxy helps the code generation blocks to generate proxy code. @@ -22,8 +23,8 @@ static RazorPayService createProxy(Vertx vertx, String address) { } /** - * The create order method implements the creation of an order using the razorpayClient - * This method also creates a transfer from the order to the respective merchant account + * The create order method implements the creation of an order using the razorpayClient This + * method also creates a transfer from the order to the respective merchant account * * @param request which is a JsonObject * @retun Future which is a vertx Future @@ -31,8 +32,9 @@ static RazorPayService createProxy(Vertx vertx, String address) { Future createOrder(JsonObject request); /** - * The verifyPayment method verifies the payment signature for every payment that is made using RazorPay - * This method also creates a payment record in the marketplace database + * The verifyPayment method verifies the payment signature for every payment that is made using + * RazorPay This method also creates a payment record in the marketplace database + * * @param request which is a JsonObject * @retun Future which is a vertx Future */ @@ -42,48 +44,54 @@ static RazorPayService createProxy(Vertx vertx, String address) { * Accepts the terms and conditions of behalf of the merchant after a linked account is created *
    * The terms and conditions are accepted for route as a Razorpay product + * * @param info contains accountId generated by Razorpay * @return productId as success response in Future JsonObject, failure of type Future if any - * @see Request product configuration + * @see Request + * product configuration */ Future requestProductConfiguration(JsonObject info); /** + * Checks if the account is activated by the Merchant by completing the required KYC or adding + * their bank account details * - * Checks if the account is activated by the Merchant by completing the required KYC or - * adding their bank account details * @param request - contains productId and accountId generated by Razorpay - * @return status as active as success response in Future JsonObject, failure if the - *
    status is any of ( - *
    requested - *
    needs_clarification - *
    under_review - *
    suspended - *
    ) - * @see Fetch a product configuration + * @return status as active as success response in Future JsonObject, failure if the
    + * status is any of (
    + * requested
    + * needs_clarification
    + * under_review
    + * suspended
    + * ) + * @see Fetch + * a product configuration */ Future fetchProductConfiguration(JsonObject request); - /** * Creates Linked account for the merchant through DMP in Payment Gateway + * * @param request Required details to create linked account * @return Future of type JsonObject as success response, failure if any */ Future createLinkedAccount(String request); - /** * Fetches a linked account from Razorpay + * * @param accountId Razorpay ID generated after creating a linked account * @return Linked account information as Future of type JsonObject when as success response. - * Failure if any + * Failure if any */ Future fetchLinkedAccount(String accountId); /** - * Updates the account information after creating a linked account - *
    All the information except businessType, email could be updated + * Updates the account information after creating a linked account
    + * All the information except businessType, email could be updated + * * @param request Fields to be updated as JSON string * @param accountId Razorpay generated ID after creating a linked account * @return Future of type boolean after updating successfully or failure if any @@ -91,8 +99,9 @@ static RazorPayService createProxy(Vertx vertx, String address) { Future updateLinkedAccount(String request, String accountId); /** - * Captures webhook event from RazorPay related to payment and order, - * it also triggers the flow of policy creation + * Captures webhook event from RazorPay related to payment and order, it also triggers the flow of + * policy creation + * * @return Future of type JsonObject as success response, failure if any */ Future webhookSignatureValidator(JsonObject request, String signatureHeader); diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java index bdf5100c..37cacdea 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java @@ -300,7 +300,7 @@ public Future createLinkedAccount(String request) { return promise.future(); } - Future recordPayment(JsonObject request) { + Future recordPayment(JsonObject request) { Promise promise = Promise.promise(); StringBuilder query = new StringBuilder(RECORD_PAYMENT.replace("$0", paymentTable)); diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java index 173304b9..11fc35fe 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java @@ -10,19 +10,6 @@ @VertxGen @ProxyGen public interface WebhookService { - /** - * @param orderId which is a String generated from Razorpay - * @return Future which is a vertx Future - */ - Future recordOrderPaid(String orderId); - - /** - * @param orderId which is a String generated from Razorpay - * @return Future which is a vertx Future - */ - Future recordPaymentFailure(String orderId); - - /** * The createProxy helps the code generation blocks to generate proxy code. * @@ -34,4 +21,16 @@ public interface WebhookService { static WebhookService createProxy(Vertx vertx, String address) { return new WebhookServiceVertxEBProxy(vertx, address); } + + /** + * @param orderId which is a String generated from Razorpay + * @return Future which is a vertx Future + */ + Future recordOrderPaid(String orderId); + + /** + * @param orderId which is a String generated from Razorpay + * @return Future which is a vertx Future + */ + Future recordPaymentFailure(String orderId); } diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookServiceImpl.java b/src/main/java/iudx/data/marketplace/webhook/WebhookServiceImpl.java index 70f740db..938437c6 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookServiceImpl.java @@ -54,14 +54,16 @@ Future updatePaymentStatusForInvoice(String orderId, PaymentStatus payment new StringBuilder(UPDATE_PAYMENT_STATUS_QUERY.replace("$0", invoiceTable)); JsonObject params = - new JsonObject().put(PAYMENT_STATUS, paymentStatus.getPaymentStatus()).put(ORDER_ID, orderId); + new JsonObject() + .put(PAYMENT_STATUS, paymentStatus.getPaymentStatus()) + .put(ORDER_ID, orderId); postgresService.executePreparedQuery( query.toString(), params, pgHandler -> { if (pgHandler.succeeded()) { - LOGGER.debug("Result after updating : {}", pgHandler.result().encode()); + LOGGER.debug("Result after updating : {}", pgHandler.result().encode()); promise.complete(); } else { promise.fail(pgHandler.cause()); diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java index 00479736..ec4df868 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java @@ -16,7 +16,6 @@ public class WebhookVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(WebhookVerticle.class); - private MessageConsumer consumer; private ServiceBinder binder; private PostgresService postgresService; @@ -33,9 +32,8 @@ public void start() { webhookService = new WebhookServiceImpl(postgresService, policyService, invoiceTable); binder = new ServiceBinder(vertx); - consumer = binder - .setAddress(WEBHOOK_SERVICE_ADDRESS) - .register(WebhookService.class, webhookService); + consumer = + binder.setAddress(WEBHOOK_SERVICE_ADDRESS).register(WebhookService.class, webhookService); LOGGER.info("webhook Service started"); } } From 594f392603f1ded6fe7e9104071a89d3f2563b90 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 11:14:05 +0530 Subject: [PATCH 02/15] Refactor: resolve checkstyle issue --- .../apiserver/ApiServerVerticle.java | 1 - .../marketplace/apiserver/ProviderApis.java | 1 - .../apiserver/handlers/ExceptionHandler.java | 4 +- .../apiserver/handlers/ValidationHandler.java | 5 +- .../linkedAccount/CreateLinkedAccount.java | 87 +++++----- .../linkedAccount/FetchLinkedAccount.java | 6 +- .../linkedAccount/LinkedAccountVerticle.java | 5 - .../linkedAccount/UpdateLinkedAccount.java | 6 +- .../linkedAccount/util/Constants.java | 22 +-- .../marketplace/apiserver/util/Constants.java | 6 +- .../data/marketplace/apiserver/util/Role.java | 39 +++-- .../validation/ValidationHandlerFactory.java | 9 +- .../types/JsonSchemaTypeValidator.java | 31 ++-- .../types/OrderIdTypeValidator.java | 1 - .../types/VariantNameTypeValidator.java | 8 +- .../auditing/AuditingServiceImpl.java | 13 +- .../auditing/AuditingVerticle.java | 4 +- .../marketplace/auditing/util/Constants.java | 25 ++- .../marketplace/authenticator/AuthClient.java | 6 +- .../authenticator/AuthenticationService.java | 7 +- .../AuthenticationServiceImpl.java | 113 ++++++------- .../authenticator/AuthenticationVerticle.java | 9 +- .../authorization/AuthorizationRequest.java | 1 - .../authorization/ConsumerAuthStatergy.java | 12 +- .../authenticator/authorization/IudxRole.java | 16 +- .../authorization/ProviderAuthStatergy.java | 10 +- .../authenticator/util/Constants.java | 2 +- .../marketplace/common/CatalogueService.java | 2 - .../data/marketplace/common/Constants.java | 5 +- .../data/marketplace/common/RespBuilder.java | 6 +- .../data/marketplace/common/ResponseUrn.java | 32 ++-- .../iudx/data/marketplace/common/Util.java | 1 - .../marketplace/consumer/ConsumerService.java | 39 +++-- .../consumer/ConsumerVerticle.java | 4 +- .../marketplace/consumer/util/Constants.java | 118 ++++++------- .../consumer/util/PaymentStatus.java | 18 +- .../marketplace/policies/DeletePolicy.java | 12 -- .../policies/FetchPolicyUsingPvId.java | 13 +- .../data/marketplace/policies/GetPolicy.java | 15 +- .../marketplace/policies/PolicyVerticle.java | 16 +- .../iudx/data/marketplace/policies/User.java | 6 +- .../marketplace/policies/VerifyPolicy.java | 18 +- .../marketplace/policies/util/Constants.java | 159 +++++++++--------- .../marketplace/postgres/PostgresService.java | 21 ++- .../postgres/PostgresServiceImpl.java | 51 +++--- .../postgres/PostgresVerticle.java | 4 +- .../marketplace/product/ProductVerticle.java | 4 +- .../marketplace/product/util/Constants.java | 32 ++-- .../product/util/QueryBuilder.java | 1 - .../variant/ProductVariantVerticle.java | 6 +- .../data/marketplace/razorpay/Constants.java | 3 +- .../razorpay/RazorPayVerticle.java | 10 +- .../razorpay/util/ErrorMessageBuilder.java | 5 +- .../marketplace/webhook/WebhookService.java | 3 +- .../marketplace/webhook/WebhookVerticle.java | 6 +- 55 files changed, 518 insertions(+), 541 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index 51ec84aa..fb08b6f1 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -9,7 +9,6 @@ import io.vertx.core.http.*; import io.vertx.core.json.DecodeException; import io.vertx.core.json.JsonObject; -import io.vertx.core.net.JksOptions; import io.vertx.ext.web.Route; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; diff --git a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java index fd363c8f..e7a717de 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java @@ -30,7 +30,6 @@ import iudx.data.marketplace.product.ProductService; import iudx.data.marketplace.product.variant.ProductVariantService; import java.util.Map; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java index 5e27700e..9f071fec 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java @@ -1,5 +1,7 @@ package iudx.data.marketplace.apiserver.handlers; +import static iudx.data.marketplace.apiserver.util.Constants.*; + import io.vertx.core.Handler; import io.vertx.core.json.DecodeException; import io.vertx.core.json.JsonObject; @@ -12,8 +14,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.apiserver.util.Constants.*; - public class ExceptionHandler implements Handler { private static final Logger LOGGER = LogManager.getLogger(ExceptionHandler.class); diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java index 5fc1128f..e931b214 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java @@ -8,13 +8,12 @@ import iudx.data.marketplace.apiserver.util.RequestType; import iudx.data.marketplace.apiserver.validation.ValidationHandlerFactory; import iudx.data.marketplace.apiserver.validation.types.Validator; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ValidationHandler implements Handler { diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index 72a7132e..06fb8fe8 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -1,6 +1,5 @@ package iudx.data.marketplace.apiserver.provider.linkedAccount; - import com.google.common.hash.Hashing; import io.vertx.core.Future; import io.vertx.core.Promise; @@ -46,7 +45,7 @@ public CreateLinkedAccount( PostgresService postgresService, Api api, AuditingService auditingService, - RazorPayService razorPayService ) { + RazorPayService razorPayService) { this.postgresService = postgresService; this.api = api; this.auditingService = auditingService; @@ -55,16 +54,16 @@ public CreateLinkedAccount( /** * Initiates provider registration flow + * * @param request Information used to create linked account present in payload * @param provider User object * @return Successful or failure response of type Future JsonObject */ - public Future initiateCreatingLinkedAccount(JsonObject request, User provider) { String referenceId = createReferenceId(); String emailId = provider.getEmailId(); JsonObject merchantDetails = getLinkedAccountDetails(request, referenceId, emailId); - String providerId = provider.getUserId(); + String providerId = provider.getUserId(); setProviderId(providerId); var razorpayFlowFuture = createLinkedAccount(merchantDetails); @@ -82,46 +81,48 @@ public Future initiateCreatingLinkedAccount(JsonObject request, User /* send the information for auditing */ /* audit info = Ids generated by Razorpay + Necessary information (Non-sensitive PII) */ - Future auditingFuture = userResponse.compose(insertInDBSuccessful -> - addAuditLogs(referenceId,provider)); + Future auditingFuture = + userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); return userResponse; } /** - * Initiates creating linked account and accepting terms and conditions - * Fetches and sets accountId, accountProductId after creating linked account and after accepting TnC respectively + * Initiates creating linked account and accepting terms and conditions Fetches and sets + * accountId, accountProductId after creating linked account and after accepting TnC respectively * * @param merchantDetails of type JsonObject to required to create linked account through Razorpay - * @return true if the flow is successful, respective failure response if any - * of type Future + * @return true if the flow is successful, respective failure response if any of type Future */ private Future createLinkedAccount(JsonObject merchantDetails) { - Future linkedAccountCreationFuture = razorPayService.createLinkedAccount(merchantDetails.toString()); - Future productConfigurationFuture = linkedAccountCreationFuture.compose(linkedAccountJson -> { - String accountId = linkedAccountJson.getString("accountId"); - setAccountId(accountId); - return razorPayService.requestProductConfiguration(linkedAccountJson); - }); + Future linkedAccountCreationFuture = + razorPayService.createLinkedAccount(merchantDetails.toString()); + Future productConfigurationFuture = + linkedAccountCreationFuture.compose( + linkedAccountJson -> { + String accountId = linkedAccountJson.getString("accountId"); + setAccountId(accountId); + return razorPayService.requestProductConfiguration(linkedAccountJson); + }); Future requestProductConfigurationFuture = - productConfigurationFuture.compose(productConfigJson -> { - String accountProductId = productConfigJson.getString("razorpayAccountProductId"); - setAccountProductId(accountProductId); - return Future.succeededFuture(true); - }); + productConfigurationFuture.compose( + productConfigJson -> { + String accountProductId = productConfigJson.getString("razorpayAccountProductId"); + setAccountProductId(accountProductId); + return Future.succeededFuture(true); + }); return requestProductConfigurationFuture; } - /** - * Creates a request body to create linked account through Razorpay based on the request - * payload
    - * Options fields in the request payload are : - *
    customerFacingBusinessName - *
    legalInfo JSON - *
    GST - *
    PAN + * Creates a request body to create linked account through Razorpay based on the request payload + *
    + * Options fields in the request payload are :
    + * customerFacingBusinessName
    + * legalInfo JSON
    + * GST
    + * PAN * * @param request Request payload of type JsonObject * @param referenceId random Id generated to act as internal reference @@ -193,8 +194,8 @@ public JsonObject getLinkedAccountDetails( setCustomerFacingBusinessName(legalBusinessName); /* customer facing business name is not a necessary field in the request body - * while inserting in the DB, if customer facing business name is null, it is - * replaced with the legal business name */ + * while inserting in the DB, if customer facing business name is null, it is + * replaced with the legal business name */ if (StringUtils.isNotBlank(customerFacingBusinessName)) { setCustomerFacingBusinessName(customerFacingBusinessName); details.put("customer_facing_business_name", customerFacingBusinessName); @@ -206,8 +207,9 @@ public JsonObject getLinkedAccountDetails( } /** - * Inserts a record in DB with required merchant details like referenceId, phoneNumber, - * provider email id, business name, Razorpay generated account id, account status + * Inserts a record in DB with required merchant details like referenceId, phoneNumber, provider + * email id, business name, Razorpay generated account id, account status + * * @param query Insert query of type string * @param referenceId Acts as primary key to store record * @return Success or failure response of type Future Json object @@ -254,9 +256,10 @@ Future insertInfoInDB(String query, String referenceId) { } /** - * Creates a referenceId of length = 20 based on present time as seed. This referenceId could be sent to Razorpay - * while creating linked account and it can also act as an internal reference to store relevant - * merchant information in the DB + * Creates a referenceId of length = 20 based on present time as seed. This referenceId could be + * sent to Razorpay while creating linked account and it can also act as an internal reference to + * store relevant merchant information in the DB + * * @return referenceId as string which to act as primary key to store record in DB */ private String createReferenceId() { @@ -270,13 +273,12 @@ private String createReferenceId() { .substring(0, 20); return referenceId; } - public String getBusinessType() - { + + public String getBusinessType() { return this.businessType; } - public void setBusinessType(String businessType) - { + public void setBusinessType(String businessType) { this.businessType = businessType; } @@ -336,12 +338,11 @@ public void setStatus(String status) { this.status = status; } - public String getAccountProductId() - { + public String getAccountProductId() { return this.accountProductId; } - public void setAccountProductId(String rzpAccountProductId){ + public void setAccountProductId(String rzpAccountProductId) { this.accountProductId = rzpAccountProductId; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java index ad03adfa..dfd21b1f 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.apiserver.provider.linkedAccount; +import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonObject; @@ -14,9 +17,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; -import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; - public class FetchLinkedAccount { private static final Logger LOGGER = LogManager.getLogger(FetchLinkedAccount.class); PostgresService postgresService; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java index 4c968c90..68491c27 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java @@ -2,11 +2,8 @@ import static iudx.data.marketplace.common.Constants.*; -import com.razorpay.RazorpayClient; import io.vertx.core.AbstractVerticle; import io.vertx.core.Promise; -import io.vertx.ext.web.client.WebClient; -import io.vertx.ext.web.client.WebClientOptions; import io.vertx.serviceproxy.ServiceBinder; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; @@ -15,8 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.security.SecureRandom; - public class LinkedAccountVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java index ce3676fc..5428a2f8 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.apiserver.provider.linkedAccount; +import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.http.HttpMethod; @@ -16,9 +19,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; -import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; - public class UpdateLinkedAccount { private static Logger LOGGER = LogManager.getLogger(UpdateLinkedAccount.class); PostgresService postgresService; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java index d204418c..4fd87d38 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java @@ -7,11 +7,11 @@ public class Constants { + " provider_id, status, rzp_account_product_id) " + " VALUES ('$1', '$2', '$3', '$4', '$5','$6', '$7', '$8', '$9');"; -public static final String FETCH_MERCHANT_INFO_QUERY = - "SELECT account_id, rzp_account_product_id, status FROM merchant_table WHERE provider_id = '$1'"; + public static final String FETCH_MERCHANT_INFO_QUERY = + "SELECT account_id, rzp_account_product_id, status FROM merchant_table WHERE provider_id = '$1'"; -public static String UPDATE_LINKED_ACCOUNT_STATUS_QUERY = - "UPDATE merchant_table SET status = 'ACTIVATED' WHERE provider_id = '$1' RETURNING reference_id"; + public static String UPDATE_LINKED_ACCOUNT_STATUS_QUERY = + "UPDATE merchant_table SET status = 'ACTIVATED' WHERE provider_id = '$1' RETURNING reference_id"; public static final String ACCOUNT_TYPE = "route"; public static final String FAILURE_MESSAGE = "User registration incomplete : "; @@ -20,12 +20,12 @@ public class Constants { + "M.modified_at AS \"updatedAt\" , M.created_at AS \"createdAt\" \n" + "FROM merchant_table M\n" + "WHERE M.provider_id = '$1'\n"; - public static final String GET_MERCHANT_INFO_QUERY = "SELECT account_id, reference_id FROM merchant_table WHERE provider_id = '$1'" + - " AND email = '$2'"; - - public static final String UPDATE_MERCHANT_INFO_QUERY = "UPDATE merchant_table SET " + - " phone_number = '$1', legal_business_name = '$2', customer_facing_business_name = '$3' " + - " WHERE provider_id = '$4' AND email = '$5' RETURNING account_id; "; - + public static final String GET_MERCHANT_INFO_QUERY = + "SELECT account_id, reference_id FROM merchant_table WHERE provider_id = '$1'" + + " AND email = '$2'"; + public static final String UPDATE_MERCHANT_INFO_QUERY = + "UPDATE merchant_table SET " + + " phone_number = '$1', legal_business_name = '$2', customer_facing_business_name = '$3' " + + " WHERE provider_id = '$4' AND email = '$5' RETURNING account_id; "; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/Constants.java b/src/main/java/iudx/data/marketplace/apiserver/util/Constants.java index 4a97fe5b..05db868d 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/Constants.java @@ -93,7 +93,8 @@ public class Constants { public static final String STRING_URN = "urn"; public static final String DOMAIN = "datakaveri.org"; public static final int VALIDATION_PRODUCT_ID_MAXLEN = 150; - public static final Pattern VALIDATION_PRODUCT_ID_REGEX = Pattern.compile("^[a-zA-Z0-9-]{3,150}$"); + public static final Pattern VALIDATION_PRODUCT_ID_REGEX = + Pattern.compile("^[a-zA-Z0-9-]{3,150}$"); public static final int VALIDATION_VARIANT_NAME_MAX_LEN = 100; public static final Pattern VALIDATION_VARIANT_NAME_REGEX = Pattern.compile("^[a-zA-Z0-9-]{3,100}$"); @@ -103,8 +104,7 @@ public class Constants { public static final Pattern POLICY_ID_PATTERN = Pattern.compile( "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}"); - public static final Pattern ORDER_ID_PATTERN = - Pattern.compile("order_[a-zA-Z0-9]+"); + public static final Pattern ORDER_ID_PATTERN = Pattern.compile("order_[a-zA-Z0-9]+"); // response keys public static final String TYPE = "type"; public static final String TITLE = "title"; diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/Role.java b/src/main/java/iudx/data/marketplace/apiserver/util/Role.java index d2fc7436..e7ffd201 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/Role.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/Role.java @@ -1,30 +1,29 @@ package iudx.data.marketplace.apiserver.util; -import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; +import static iudx.data.marketplace.common.ResponseUrn.ROLE_NOT_FOUND; +import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; import java.util.stream.Stream; -import static iudx.data.marketplace.common.ResponseUrn.ROLE_NOT_FOUND; - public enum Role { - PROVIDER("provider"), - CONSUMER_DELEGATE("consumerDelegate"), - PROVIDER_DELEGATE("providerDelegate"), - CONSUMER("consumer"); - private final String role; + PROVIDER("provider"), + CONSUMER_DELEGATE("consumerDelegate"), + PROVIDER_DELEGATE("providerDelegate"), + CONSUMER("consumer"); + private final String role; - Role(String value) { - role = value; - } + Role(String value) { + role = value; + } - public static Role fromString(String roleValue) { - return Stream.of(values()) - .filter(element -> element.getRole().equalsIgnoreCase(roleValue)) - .findAny() - .orElseThrow(() -> new DxRuntimeException(404, ROLE_NOT_FOUND)); - } + public static Role fromString(String roleValue) { + return Stream.of(values()) + .filter(element -> element.getRole().equalsIgnoreCase(roleValue)) + .findAny() + .orElseThrow(() -> new DxRuntimeException(404, ROLE_NOT_FOUND)); + } - public String getRole() { - return role; - } + public String getRole() { + return role; + } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java index ad86fb94..f6f49aa0 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java @@ -1,16 +1,15 @@ package iudx.data.marketplace.apiserver.validation; +import static iudx.data.marketplace.apiserver.util.Constants.*; + import io.vertx.core.MultiMap; import io.vertx.core.json.JsonObject; import iudx.data.marketplace.apiserver.util.RequestType; import iudx.data.marketplace.apiserver.validation.types.*; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.ArrayList; import java.util.List; - -import static iudx.data.marketplace.apiserver.util.Constants.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ValidationHandlerFactory { private static final Logger LOGGER = LogManager.getLogger(ValidationHandlerFactory.class); diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java index 23f4cfb7..4a85a33b 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -24,7 +24,7 @@ public class JsonSchemaTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(JsonSchemaTypeValidator.class); private static String pkg = Validator.class.getPackageName(); - private static final String PACKAGE_NAME = "/" + pkg.replace(".","/"); + private static final String PACKAGE_NAME = "/" + pkg.replace(".", "/"); private final JsonObject body; private final RequestType requestType; @@ -40,7 +40,7 @@ public static JsonNode loadResource(final String name) throws IOException { public static JsonNode loadString(final String obj) throws IOException { return JsonLoader.fromString(obj); - } + } @Override public boolean isValid() { @@ -48,16 +48,19 @@ public boolean isValid() { try { isValid = validateJson(body, requestType); } catch (IOException | ProcessingException e) { - throw new DxRuntimeException(failureCode(), SCHEMA_READ_ERROR_URN, failureMessage(body.encode())); + throw new DxRuntimeException( + failureCode(), SCHEMA_READ_ERROR_URN, failureMessage(body.encode())); } - if(!isValid) { - throw new DxRuntimeException(failureCode(), INVALID_PAYLOAD_FORMAT_URN, INVALID_PAYLOAD_FORMAT_URN.getMessage()); + if (!isValid) { + throw new DxRuntimeException( + failureCode(), INVALID_PAYLOAD_FORMAT_URN, INVALID_PAYLOAD_FORMAT_URN.getMessage()); } else { return true; } } - private boolean validateJson(JsonObject body, RequestType requestType) throws IOException, ProcessingException, DxRuntimeException { + private boolean validateJson(JsonObject body, RequestType requestType) + throws IOException, ProcessingException, DxRuntimeException { LOGGER.debug(body); boolean isValid; String schemaPath = PACKAGE_NAME + "/".concat(requestType.getFilename()).concat("_schema.json"); @@ -65,7 +68,7 @@ private boolean validateJson(JsonObject body, RequestType requestType) throws IO LOGGER.debug(schemaPath); final JsonSchema schema; try { - final JsonNode sc = loadResource(schemaPath); + final JsonNode sc = loadResource(schemaPath); } catch (Exception e) { LOGGER.error("Validation Error {}", e.getMessage()); } @@ -77,12 +80,14 @@ private boolean validateJson(JsonObject body, RequestType requestType) throws IO try { JsonNode jsonobj = loadString(body.toString()); ProcessingReport report = schema.validate(jsonobj); - report.forEach( x -> { - if(x.getLogLevel().toString().equalsIgnoreCase("error")) { - LOGGER.error(x.getMessage()); - throw new DxRuntimeException(failureCode(), INVALID_PAYLOAD_FORMAT_URN, x.getMessage()); - } - }); + report.forEach( + x -> { + if (x.getLogLevel().toString().equalsIgnoreCase("error")) { + LOGGER.error(x.getMessage()); + throw new DxRuntimeException( + failureCode(), INVALID_PAYLOAD_FORMAT_URN, x.getMessage()); + } + }); isValid = report.isSuccess(); } catch (IOException | ProcessingException e) { isValid = false; diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java index fa641eed..89fc0bde 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java @@ -5,7 +5,6 @@ import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; import iudx.data.marketplace.common.HttpStatusCode; -import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java index 6b0952d9..ed6ef3cd 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/VariantNameTypeValidator.java @@ -1,14 +1,14 @@ package iudx.data.marketplace.apiserver.validation.types; +import static iudx.data.marketplace.apiserver.util.Constants.VALIDATION_VARIANT_NAME_MAX_LEN; +import static iudx.data.marketplace.apiserver.util.Constants.VALIDATION_VARIANT_NAME_REGEX; +import static iudx.data.marketplace.common.ResponseUrn.INVALID_NAME_URN; + import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; import iudx.data.marketplace.common.HttpStatusCode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.apiserver.util.Constants.VALIDATION_VARIANT_NAME_MAX_LEN; -import static iudx.data.marketplace.apiserver.util.Constants.VALIDATION_VARIANT_NAME_REGEX; -import static iudx.data.marketplace.common.ResponseUrn.INVALID_NAME_URN; - public class VariantNameTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(VariantNameTypeValidator.class); diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java b/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java index 4eff469d..0947ae39 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingServiceImpl.java @@ -1,21 +1,20 @@ package iudx.data.marketplace.auditing; +import static iudx.data.marketplace.auditing.util.Constants.*; +import static iudx.data.marketplace.auditing.util.Constants.ISO_TIME; +import static iudx.data.marketplace.product.util.Constants.TABLES; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonObject; import iudx.data.marketplace.auditing.databroker.DataBrokerService; import iudx.data.marketplace.policies.User; import iudx.data.marketplace.product.util.QueryBuilder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; - -import static iudx.data.marketplace.auditing.util.Constants.*; -import static iudx.data.marketplace.auditing.util.Constants.ISO_TIME; -import static iudx.data.marketplace.product.util.Constants.TABLES; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class AuditingServiceImpl implements AuditingService { private static final Logger LOGGER = LogManager.getLogger(AuditingServiceImpl.class); diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java b/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java index 1a5b798c..09af7476 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingVerticle.java @@ -1,5 +1,7 @@ package iudx.data.marketplace.auditing; +import static iudx.data.marketplace.common.Constants.AUDITING_SERVICE_ADDRESS; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -11,8 +13,6 @@ import iudx.data.marketplace.auditing.databroker.DataBrokerService; import iudx.data.marketplace.auditing.databroker.DataBrokerServiceImpl; -import static iudx.data.marketplace.common.Constants.AUDITING_SERVICE_ADDRESS; - public class AuditingVerticle extends AbstractVerticle { private RabbitMQOptions config; diff --git a/src/main/java/iudx/data/marketplace/auditing/util/Constants.java b/src/main/java/iudx/data/marketplace/auditing/util/Constants.java index 4dcd262c..efef7534 100644 --- a/src/main/java/iudx/data/marketplace/auditing/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/auditing/util/Constants.java @@ -2,17 +2,16 @@ public class Constants { - public static final String PRIMARY_KEY = "primaryKey"; - public static final String ORIGIN = "origin"; - public static final String ORIGIN_SERVER = "dmp-apd-server"; - public static final String EXCHANGE_NAME = "auditing"; - public static final String ROUTING_KEY = "#"; - public static final String EPOCH_TIME = "epochTime"; - public static final String ISO_TIME = "isoTime"; - public static final String API = "api"; - public static final String INFORMATION = "info"; - public static final String RESPONSE_SIZE = "response_size"; - public static final String HTTP_METHOD = "httpMethod"; - public static final String USERID = "userid"; - + public static final String PRIMARY_KEY = "primaryKey"; + public static final String ORIGIN = "origin"; + public static final String ORIGIN_SERVER = "dmp-apd-server"; + public static final String EXCHANGE_NAME = "auditing"; + public static final String ROUTING_KEY = "#"; + public static final String EPOCH_TIME = "epochTime"; + public static final String ISO_TIME = "isoTime"; + public static final String API = "api"; + public static final String INFORMATION = "info"; + public static final String RESPONSE_SIZE = "response_size"; + public static final String HTTP_METHOD = "httpMethod"; + public static final String USERID = "userid"; } diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthClient.java b/src/main/java/iudx/data/marketplace/authenticator/AuthClient.java index 6b03a3b8..8bbdce64 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthClient.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthClient.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.authenticator; +import static iudx.data.marketplace.apiserver.util.Constants.*; +import static iudx.data.marketplace.common.HttpStatusCode.INTERNAL_SERVER_ERROR; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.buffer.Buffer; @@ -10,9 +13,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.apiserver.util.Constants.*; -import static iudx.data.marketplace.common.HttpStatusCode.INTERNAL_SERVER_ERROR; - public class AuthClient { private static final Logger LOGGER = LogManager.getLogger(AuthClient.class); diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java index 6916d732..90473077 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationService.java @@ -53,13 +53,12 @@ AuthenticationService tokenIntrospect( /** * Token introspection for verify endpoint that uses a bearer token generated by DX Auth Server + * * @param authInfo contains Api Endpoint, Header token and Api Method * @param handler AsyncResult JsonObject handler * @return AuthenticationService class object */ - @Fluent AuthenticationService tokenIntrospect4Verify( - JsonObject authInfo, Handler> handler - ); -} \ No newline at end of file + JsonObject authInfo, Handler> handler); +} diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java index 6bb1615d..5dcb3c11 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java @@ -30,7 +30,9 @@ public class AuthenticationServiceImpl implements AuthenticationService { final String apdUrl; final String issuer; final Api apis; - public AuthenticationServiceImpl(Vertx vertx, final JWTAuth jwtAuth, final JsonObject config, final Api apis) { + + public AuthenticationServiceImpl( + Vertx vertx, final JWTAuth jwtAuth, final JsonObject config, final Api apis) { this.jwtAuth = jwtAuth; this.issuer = config.getString("issuer"); this.apdUrl = config.getString(APD_URL); @@ -38,26 +40,28 @@ public AuthenticationServiceImpl(Vertx vertx, final JWTAuth jwtAuth, final JsonO } @Override - public AuthenticationService tokenIntrospect(JsonObject request, JsonObject authenticationInfo, Handler> handler) { + public AuthenticationService tokenIntrospect( + JsonObject request, JsonObject authenticationInfo, Handler> handler) { String token = authenticationInfo.getString(TOKEN); ResultContainer resultContainer = new ResultContainer(); Future jwtDecodeFuture = decodeJwt(token); jwtDecodeFuture - .compose( - decodeHandler -> { - resultContainer.jwtData = decodeHandler; - return validateJwtAccess(resultContainer.jwtData); - }) - .compose(isValidJwtAccess -> validateAccess(resultContainer.jwtData, authenticationInfo)) - .onSuccess(successHandler -> handler.handle(Future.succeededFuture(successHandler))) - .onFailure( - failureHandler -> { - LOGGER.error("error : " + failureHandler.getCause()); - handler.handle(Future.failedFuture(failureHandler.getMessage())); - }); + .compose( + decodeHandler -> { + resultContainer.jwtData = decodeHandler; + return validateJwtAccess(resultContainer.jwtData); + }) + .compose(isValidJwtAccess -> validateAccess(resultContainer.jwtData, authenticationInfo)) + .onSuccess(successHandler -> handler.handle(Future.succeededFuture(successHandler))) + .onFailure( + failureHandler -> { + LOGGER.error("error : " + failureHandler.getCause()); + handler.handle(Future.failedFuture(failureHandler.getMessage())); + }); return this; } + Future validateAccess(JwtData jwtData, JsonObject authInfo) { LOGGER.info("Authorization check started"); Promise promise = Promise.promise(); @@ -104,39 +108,37 @@ public Future validateJwtAccess(JwtData jwtData) { return promise.future(); } - - @Override public AuthenticationService tokenIntrospect4Verify( - JsonObject authInfo, Handler> handler) { + JsonObject authInfo, Handler> handler) { String token = authInfo.getString(TOKEN); Future jwtDecodeFuture = decodeJwt(token); jwtDecodeFuture - .onSuccess( - jwtData -> { - if (jwtData.getSub() == null) { - LOGGER.error("No sub value in JWT"); - handler.handle(Future.failedFuture("No sub value in JWT")); - } else if (!(jwtData.getIss() != null && issuer.equalsIgnoreCase(jwtData.getIss()))) { - LOGGER.error("Incorrect issuer value in JWT"); - handler.handle(Future.failedFuture("Incorrect issuer value in JWT")); - } else if (jwtData.getAud().isEmpty()) { - LOGGER.error("No audience value in JWT"); - handler.handle(Future.failedFuture("No audience value in JWT")); - } else if (!jwtData.getAud().equalsIgnoreCase(apdUrl)) { - LOGGER.error("Incorrect audience value in JWT"); - handler.handle(Future.failedFuture("Incorrect subject value in JWT")); - } else { - LOGGER.info("Auth token verified"); - handler.handle(Future.succeededFuture()); - } - }) - .onFailure( - failureHandler -> { - LOGGER.error("Failed to decode the token : {}", failureHandler.getMessage()); - handler.handle(Future.failedFuture(failureHandler.getMessage())); - }); + .onSuccess( + jwtData -> { + if (jwtData.getSub() == null) { + LOGGER.error("No sub value in JWT"); + handler.handle(Future.failedFuture("No sub value in JWT")); + } else if (!(jwtData.getIss() != null && issuer.equalsIgnoreCase(jwtData.getIss()))) { + LOGGER.error("Incorrect issuer value in JWT"); + handler.handle(Future.failedFuture("Incorrect issuer value in JWT")); + } else if (jwtData.getAud().isEmpty()) { + LOGGER.error("No audience value in JWT"); + handler.handle(Future.failedFuture("No audience value in JWT")); + } else if (!jwtData.getAud().equalsIgnoreCase(apdUrl)) { + LOGGER.error("Incorrect audience value in JWT"); + handler.handle(Future.failedFuture("Incorrect subject value in JWT")); + } else { + LOGGER.info("Auth token verified"); + handler.handle(Future.succeededFuture()); + } + }) + .onFailure( + failureHandler -> { + LOGGER.error("Failed to decode the token : {}", failureHandler.getMessage()); + handler.handle(Future.failedFuture(failureHandler.getMessage())); + }); return this; } @@ -145,19 +147,19 @@ Future decodeJwt(String jwtToken) { TokenCredentials credentials = new TokenCredentials(jwtToken); jwtAuth - .authenticate(credentials) - .onSuccess( - user -> { - JwtData jwtData = new JwtData(user.principal()); - jwtData.setExp(user.get("exp")); - jwtData.setIat(user.get("iat")); - promise.complete(jwtData); - }) - .onFailure( - err -> { - LOGGER.error("failed to decode/validate jwt token : " + err.getMessage()); - promise.fail("failed to decode/validate jwt token : " + err.getMessage()); - }); + .authenticate(credentials) + .onSuccess( + user -> { + JwtData jwtData = new JwtData(user.principal()); + jwtData.setExp(user.get("exp")); + jwtData.setIat(user.get("iat")); + promise.complete(jwtData); + }) + .onFailure( + err -> { + LOGGER.error("failed to decode/validate jwt token : " + err.getMessage()); + promise.fail("failed to decode/validate jwt token : " + err.getMessage()); + }); return promise.future(); } @@ -165,7 +167,4 @@ Future decodeJwt(String jwtToken) { final class ResultContainer { JwtData jwtData; } - - - } diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java index b7904743..81fdeb9c 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.authenticator; +import static iudx.data.marketplace.common.Constants.AUTH_SERVICE_ADDRESS; +import static iudx.data.marketplace.common.Constants.JWT_LEEWAY_TIME; + import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.Promise; @@ -12,15 +15,11 @@ import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.serviceproxy.ServiceBinder; -import iudx.data.marketplace.common.CatalogueService; - import iudx.data.marketplace.common.Api; +import iudx.data.marketplace.common.CatalogueService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.AUTH_SERVICE_ADDRESS; -import static iudx.data.marketplace.common.Constants.JWT_LEEWAY_TIME; - public class AuthenticationVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(AuthenticationVerticle.class); diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java index 7516abfa..004f3477 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java @@ -1,6 +1,5 @@ package iudx.data.marketplace.authenticator.authorization; -import iudx.data.marketplace.common.Api; import java.util.Objects; diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java index 2b0eb5bd..333b0e84 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/ConsumerAuthStatergy.java @@ -1,18 +1,16 @@ package iudx.data.marketplace.authenticator.authorization; -import io.vertx.core.json.JsonArray; +import static iudx.data.marketplace.authenticator.authorization.Method.GET; +import static iudx.data.marketplace.authenticator.authorization.Method.POST; + import iudx.data.marketplace.authenticator.model.JwtData; import iudx.data.marketplace.common.Api; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static iudx.data.marketplace.authenticator.authorization.Method.GET; -import static iudx.data.marketplace.authenticator.authorization.Method.POST; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ConsumerAuthStatergy implements AuthorizationStatergy { private static final Logger LOGGER = LogManager.getLogger(ConsumerAuthStatergy.class); diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java index c86b30ec..3d9ed735 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java @@ -5,7 +5,9 @@ import java.util.stream.Stream; public enum IudxRole { - CONSUMER("consumer"), PROVIDER("provider"), DELEGATE("delegate"); + CONSUMER("consumer"), + PROVIDER("provider"), + DELEGATE("delegate"); private final String role; @@ -14,16 +16,14 @@ public enum IudxRole { } public static IudxRole fromRole(final JwtData jwtData) { - String role = jwtData.getRole().equalsIgnoreCase(DELEGATE.getRole()) ? jwtData.getDrl() : jwtData.getRole(); - return Stream.of(values()) - .filter(v -> v.role.equalsIgnoreCase(role)) - .findAny() - .orElse(null); + String role = + jwtData.getRole().equalsIgnoreCase(DELEGATE.getRole()) + ? jwtData.getDrl() + : jwtData.getRole(); + return Stream.of(values()).filter(v -> v.role.equalsIgnoreCase(role)).findAny().orElse(null); } public String getRole() { return this.role; } - - } diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java index dc66ccea..a3560c7a 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/ProviderAuthStatergy.java @@ -1,17 +1,15 @@ package iudx.data.marketplace.authenticator.authorization; -import io.vertx.core.json.JsonArray; +import static iudx.data.marketplace.authenticator.authorization.Method.*; + import iudx.data.marketplace.authenticator.model.JwtData; import iudx.data.marketplace.common.Api; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static iudx.data.marketplace.authenticator.authorization.Method.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ProviderAuthStatergy implements AuthorizationStatergy { private static final Logger LOGGER = LogManager.getLogger(ProviderAuthStatergy.class); diff --git a/src/main/java/iudx/data/marketplace/authenticator/util/Constants.java b/src/main/java/iudx/data/marketplace/authenticator/util/Constants.java index d380146f..d4fcf8f9 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/authenticator/util/Constants.java @@ -6,5 +6,5 @@ public class Constants { public static final String GET_USER = "select * from user_table where _id=$1::UUID;"; public static final String INSERT_USER_TABLE = - "insert into user_table(_id,email_id,first_name,last_name) values ($1,$2,$3,$4) returning _id;"; + "insert into user_table(_id,email_id,first_name,last_name) values ($1,$2,$3,$4) returning _id;"; } diff --git a/src/main/java/iudx/data/marketplace/common/CatalogueService.java b/src/main/java/iudx/data/marketplace/common/CatalogueService.java index 1b15d383..9284419b 100644 --- a/src/main/java/iudx/data/marketplace/common/CatalogueService.java +++ b/src/main/java/iudx/data/marketplace/common/CatalogueService.java @@ -10,8 +10,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.concurrent.TimeUnit; - /** * The Catalogue Service * diff --git a/src/main/java/iudx/data/marketplace/common/Constants.java b/src/main/java/iudx/data/marketplace/common/Constants.java index 75b2a5a5..2e212f11 100644 --- a/src/main/java/iudx/data/marketplace/common/Constants.java +++ b/src/main/java/iudx/data/marketplace/common/Constants.java @@ -32,9 +32,8 @@ public class Constants { public static final String RAZORPAY_SERVICE_ADDRESS = "iudx.data.marketplace.razorpay.service"; public static final String AUDITING_SERVICE_ADDRESS = "iudx.data.marketplace.server.auditing"; - public static final String LINKED_ACCOUNT_ADDRESS = "iudx.data.marketplace.apiserver.provider.linked.account.service"; + public static final String LINKED_ACCOUNT_ADDRESS = + "iudx.data.marketplace.apiserver.provider.linked.account.service"; public static final String WEBHOOK_SERVICE_ADDRESS = "iudx.data.marketplace.webhook.service"; public static final int JWT_LEEWAY_TIME = 30; - - } diff --git a/src/main/java/iudx/data/marketplace/common/RespBuilder.java b/src/main/java/iudx/data/marketplace/common/RespBuilder.java index 9d9983bb..9748af03 100644 --- a/src/main/java/iudx/data/marketplace/common/RespBuilder.java +++ b/src/main/java/iudx/data/marketplace/common/RespBuilder.java @@ -1,11 +1,11 @@ package iudx.data.marketplace.common; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; - import static iudx.data.marketplace.apiserver.util.Constants.*; import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; + public class RespBuilder { private JsonObject response = new JsonObject(); diff --git a/src/main/java/iudx/data/marketplace/common/ResponseUrn.java b/src/main/java/iudx/data/marketplace/common/ResponseUrn.java index 1aee29d5..a46afe70 100644 --- a/src/main/java/iudx/data/marketplace/common/ResponseUrn.java +++ b/src/main/java/iudx/data/marketplace/common/ResponseUrn.java @@ -11,18 +11,18 @@ public enum ResponseUrn { INVALID_ATTR_VALUE_URN("urn:dx:dmp:invalidAttributeValue", "Invalid attribute value"), INVALID_OPERATION_URN("urn:dx:dmp:invalidOperation", "Invalid operation"), UNAUTHORIZED_ENDPOINT_URN( - "urn:dx:dmp:unauthorizedEndpoint", "Access to endpoint is not available"), + "urn:dx:dmp:unauthorizedEndpoint", "Access to endpoint is not available"), UNAUTHORIZED_RESOURCE_URN( - "urn,dx:dmp:unauthorizedResource", "Access to resource is not available"), + "urn,dx:dmp:unauthorizedResource", "Access to resource is not available"), EXPIRED_TOKEN_URN("urn:dx:dmp:expiredAuthorizationToken", "Token has expired"), MISSING_TOKEN_URN("urn:dx:dmp:missingAuthorizationToken", "Token needed and not present"), INVALID_TOKEN_URN("urn:dx:dmp:invalidAuthorizationToken", "Token is invalid"), RESOURCE_NOT_FOUND_URN("urn:dx:dmp:resourceNotFound", "Document of given id does not exist"), RESOURCE_ALREADY_EXISTS_URN( - "urn:dx:dmp:resourceAlreadyExists", "Document of given id already exists"), + "urn:dx:dmp:resourceAlreadyExists", "Document of given id already exists"), LIMIT_EXCEED_URN( - "urn:dx:dmp:requestLimitExceeded", "Operation exceeds the default value of limit"), + "urn:dx:dmp:requestLimitExceeded", "Operation exceeds the default value of limit"), PAYLOAD_TOO_LARGE_URN("urn:dx:dmp:payloadTooLarge", "Response size exceeds limit"), @@ -31,7 +31,7 @@ public enum ResponseUrn { INVALID_ID_VALUE_URN("urn:dx:dmp:invalidIdValue", "Invalid id"), INVALID_NAME_URN("urn:dx:dmp:invalidNameValue", "Invalid name"), INVALID_PAYLOAD_FORMAT_URN( - "urn:dx:dmp:invalidPayloadFormat", "Invalid json format in post request [schema mismatch]"), + "urn:dx:dmp:invalidPayloadFormat", "Invalid json format in post request [schema mismatch]"), INVALID_PARAM_VALUE_URN("urn:dx:dmp:invalidParamameterValue", "Invalid parameter value passed"), BAD_REQUEST_URN("urn:dx:dmp:badRequest", "bad request parameter"), INVALID_HEADER_VALUE_URN("urn:dx:dmp:invalidHeaderValue", "Invalid header value"), @@ -45,7 +45,7 @@ public enum ResponseUrn { PAYMENT_STATUS_NOT_FOUND("urn:dx:dmp:invalidPaymentStatus", "Payment status does not exist"), BACKING_SERVICE_FORMAT_URN( - "urn:dx:dmp:backend", "format error from backing service [cat,auth etc.]"), + "urn:dx:dmp:backend", "format error from backing service [cat,auth etc.]"), SCHEMA_READ_ERROR_URN("urn:dx:dmp:readError", "Fail to read file"), VERIFY_FORBIDDEN_URN("urn:apd:Deny", "Policy does not exist"), FORBIDDEN_URN("urn:dx:dmp:forbidden", "Resource is forbidden to access"), @@ -53,12 +53,16 @@ public enum ResponseUrn { YET_NOT_IMPLEMENTED_URN("urn:dx:dmp:general", "urn yet not implemented in backend verticle."), FORBIDDEN_PRODUCT_CREATION("urn:dx:dmp:forbidden", "Product creation is forbidden"), - //RazorPay related URNs + // RazorPay related URNs ORDER_NOT_CREATED("urn:dx:dmp:RazorPay:OrderNotCreatedError", "Order Not Created"), - ORDER_CREATION_FAILED("urn:dx:dmp:RazorPay:OrderCreationFailedError", "Order creation returned with error"), + ORDER_CREATION_FAILED( + "urn:dx:dmp:RazorPay:OrderCreationFailedError", "Order creation returned with error"), INVALID_PAYMENT("urn:dx:dmp:RazorPay:InvalidPayment", "Payment Signature verification failed"), - INVALID_WEBHOOK_REQUEST("urn:dx:dmp:RazorPay:InvalidWebhookRequest", "Webhook request validation failed - Invalid Signature/Payload"), - RAZORPAY_WEBHOOK_ERROR("urn:dx:dmp:RazorPay:WebhookFailedError", "Unexpected error while capturing webhook event"); + INVALID_WEBHOOK_REQUEST( + "urn:dx:dmp:RazorPay:InvalidWebhookRequest", + "Webhook request validation failed - Invalid Signature/Payload"), + RAZORPAY_WEBHOOK_ERROR( + "urn:dx:dmp:RazorPay:WebhookFailedError", "Unexpected error while capturing webhook event"); private final String urn; private final String message; @@ -70,9 +74,9 @@ public enum ResponseUrn { public static ResponseUrn fromCode(final String urn) { return Stream.of(values()) - .filter(v -> v.urn.equalsIgnoreCase(urn)) - .findAny() - .orElse(YET_NOT_IMPLEMENTED_URN); // if backend service dont respond with urn + .filter(v -> v.urn.equalsIgnoreCase(urn)) + .findAny() + .orElse(YET_NOT_IMPLEMENTED_URN); // if backend service dont respond with urn } public String getUrn() { @@ -86,4 +90,4 @@ public String getMessage() { public String toString() { return "[" + urn + " : " + message + " ]"; } -} \ No newline at end of file +} diff --git a/src/main/java/iudx/data/marketplace/common/Util.java b/src/main/java/iudx/data/marketplace/common/Util.java index 56320ecb..b7f9c4af 100644 --- a/src/main/java/iudx/data/marketplace/common/Util.java +++ b/src/main/java/iudx/data/marketplace/common/Util.java @@ -3,7 +3,6 @@ import io.vertx.core.json.JsonObject; import iudx.data.marketplace.apiserver.util.Role; import iudx.data.marketplace.policies.User; - import java.util.List; public class Util { diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java index 2a81fdbe..03327a64 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java @@ -10,7 +10,8 @@ import io.vertx.core.json.JsonObject; import iudx.data.marketplace.policies.User; -@VertxGen @ProxyGen +@VertxGen +@ProxyGen public interface ConsumerService { /** @@ -27,65 +28,77 @@ static ConsumerService createProxy(Vertx vertx, String address) { /** * The listResources method fetches some or all resources available on the IUDX marketplace + * * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler * @return ConsumerService which ia service */ @Fluent - ConsumerService listResources(User consumer, JsonObject request, Handler> handler); + ConsumerService listResources( + User consumer, JsonObject request, Handler> handler); /** * The listProviders method fetches all or one providers available on the IUDX marketplace + * * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler * @return ConsumerService which ia service */ @Fluent - ConsumerService listProviders(User consumer, JsonObject request, Handler> handler); + ConsumerService listProviders( + User consumer, JsonObject request, Handler> handler); /** * The listProducts method fetches some or all products available on the IUDX marketplace + * * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler * @return ConsumerService which ia service */ @Fluent - ConsumerService listProducts(User consumer, JsonObject request, Handler> handler); + ConsumerService listProducts( + User consumer, JsonObject request, Handler> handler); /** * The createOrder method creates an order for the consumer against a product variant + * * @param request * @param user Consumer User * @param handler * @return */ @Fluent - ConsumerService createOrder(JsonObject request, User user, Handler> handler); + ConsumerService createOrder( + JsonObject request, User user, Handler> handler); /** - * The listProductVariants method fetches all the ACTIVE product variants of a given product + * The listProductVariants method fetches all the ACTIVE product variants of a given + * product + * * @param user as consumer User object * @param request containing the productId of a given product * @param handler AsyncResult JsonObject request handler * @return ConsumerService object */ @Fluent - ConsumerService listProductVariants(User user,JsonObject request, Handler> handler); + ConsumerService listProductVariants( + User user, JsonObject request, Handler> handler); /** - * List purchase will fetch invoice related info, provider, consumer and product variant related information - * After the purchase is made. Pending, successful, failed payments are displayed - * List purchase will list all the purchases if no query parameters are given - * It can also list purchases based on the productId, resourceId if it is given in the query parameter + * List purchase will fetch invoice related info, provider, consumer and product variant related + * information After the purchase is made. Pending, successful, failed payments are displayed List + * purchase will list all the purchases if no query parameters are given It can also list + * purchases based on the productId, resourceId if it is given in the query parameter + * * @param user Consumer user * @param request query param if any * @param handler Asynchronous JsonObject handler that contains the list of purchases * @return */ @Fluent - ConsumerService listPurchase(User user, JsonObject request, Handler> handler); - + ConsumerService listPurchase( + User user, JsonObject request, Handler> handler); } diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java index 20168115..3613c5d5 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerVerticle.java @@ -1,5 +1,7 @@ package iudx.data.marketplace.consumer; +import static iudx.data.marketplace.common.Constants.*; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -10,8 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.*; - public class ConsumerVerticle extends AbstractVerticle { public static final Logger LOGGER = LogManager.getLogger(ConsumerVerticle.class); private MessageConsumer consumer; diff --git a/src/main/java/iudx/data/marketplace/consumer/util/Constants.java b/src/main/java/iudx/data/marketplace/consumer/util/Constants.java index f0855a64..0fab1e30 100644 --- a/src/main/java/iudx/data/marketplace/consumer/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/consumer/util/Constants.java @@ -30,30 +30,30 @@ public class Constants { + " ORDER BY modified_at DESC "; public static final String LIST_PROVIDERS_QUERY = - "SELECT DISTINCT U._id AS \"providerId\", COUNT(R._id) AS \"numberOfResources\", \n" - + "R.provider_name AS \"providerName\", \n" - + "R.resource_server AS \"resourceServerUrl\",\n" - + "U.modified_at AS \"updatedAt\"\n" - + ",U.created_at AS \"createdAt\"\n" - + "FROM user_table U\n" - + "INNER JOIN resource_entity R \n" - + "ON U._id = R.provider_id\n" - + "WHERE R.resource_server = $1 \n" - + "GROUP BY U._id, R.provider_name, R.resource_server, U.modified_at\n" - + "ORDER BY U.modified_at DESC"; + "SELECT DISTINCT U._id AS \"providerId\", COUNT(R._id) AS \"numberOfResources\", \n" + + "R.provider_name AS \"providerName\", \n" + + "R.resource_server AS \"resourceServerUrl\",\n" + + "U.modified_at AS \"updatedAt\"\n" + + ",U.created_at AS \"createdAt\"\n" + + "FROM user_table U\n" + + "INNER JOIN resource_entity R \n" + + "ON U._id = R.provider_id\n" + + "WHERE R.resource_server = $1 \n" + + "GROUP BY U._id, R.provider_name, R.resource_server, U.modified_at\n" + + "ORDER BY U.modified_at DESC"; public static final String LIST_PROVIDER_WITH_GIVEN_PROVIDER_ID = - "SELECT DISTINCT U._id AS \"providerId\", COUNT(R._id) AS \"numberOfResources\", \n" - + "R.provider_name AS \"providerName\", \n" - + "R.resource_server AS \"resourceServerUrl\",\n" - + "U.modified_at AS \"updatedAt\"\n" - + ",U.created_at AS \"createdAt\"\n" - + "FROM user_table U\n" - + "INNER JOIN resource_entity R \n" - + "ON U._id = R.provider_id\n" - + "WHERE R.resource_server = $1 \n" - + "AND U._id = $2 \n" - + "GROUP BY U._id, R.provider_name, R.resource_server, U.modified_at\n" - + "ORDER BY U.modified_at DESC"; + "SELECT DISTINCT U._id AS \"providerId\", COUNT(R._id) AS \"numberOfResources\", \n" + + "R.provider_name AS \"providerName\", \n" + + "R.resource_server AS \"resourceServerUrl\",\n" + + "U.modified_at AS \"updatedAt\"\n" + + ",U.created_at AS \"createdAt\"\n" + + "FROM user_table U\n" + + "INNER JOIN resource_entity R \n" + + "ON U._id = R.provider_id\n" + + "WHERE R.resource_server = $1 \n" + + "AND U._id = $2 \n" + + "GROUP BY U._id, R.provider_name, R.resource_server, U.modified_at\n" + + "ORDER BY U.modified_at DESC"; public static final String LIST_PRODUCTS = "select pt.product_id AS \"productId\", pt.provider_name AS \"providerName\", " @@ -67,12 +67,12 @@ public class Constants { + "where pt.status='ACTIVE' AND rt.resource_server = $1"; public static final String GET_PRODUCT_VARIANT_INFO = - "select pv._id, pv.product_variant_name, pv.product_id, pv.provider_id, pv.price, m.account_id " - + "from $0 as pv inner join $9 as m on pv.provider_id = m.provider_id " - + "where pv._id=$1 and pv.status=$2"; + "select pv._id, pv.product_variant_name, pv.product_id, pv.provider_id, pv.price, m.account_id " + + "from $0 as pv inner join $9 as m on pv.provider_id = m.provider_id " + + "where pv._id=$1 and pv.status=$2"; public static final String INSERT_ORDER_QUERY = - "insert into $0 (order_id, amount, currency, account_id, notes) values ('$1', $2, '$3', '$4', '$5')"; + "insert into $0 (order_id, amount, currency, account_id, notes) values ('$1', $2, '$3', '$4', '$5')"; public static final String LIST_FAILED_OR_PENDING_PAYMENTS = "SELECT DISTINCT I._id AS \"invoiceId\", P.\"providerId\",\n" + "U.email_id AS \"providerEmailId\", U.first_name AS \"providerFirstName\",\n" @@ -126,13 +126,14 @@ public class Constants { + " AND P.\"resourceServerUrl\" = '$3'"; public static final String LIST_SUCCESSFUL_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER = - LIST_SUCCESSFUL_PAYMENTS + LIST_SUCCESSFUL_PAYMENTS + " WHERE \n" + " I.order_id = $1 AND I.consumer_id = '$2'" - + " AND P.\"resourceServerUrl\" = '$3'"; + + " AND P.\"resourceServerUrl\" = '$3'"; public static final String LIST_PENDING_PAYMENTS_4_CONSUMER = - LIST_FAILED_OR_PENDING_PAYMENTS + " WHERE I.consumer_id = '$1' AND I.payment_status = 'PENDING' " - + " AND P.\"resourceServerUrl\" = '$2'"; + LIST_FAILED_OR_PENDING_PAYMENTS + + " WHERE I.consumer_id = '$1' AND I.payment_status = 'PENDING' " + + " AND P.\"resourceServerUrl\" = '$2'"; public static final String LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT = LIST_FAILED_OR_PENDING_PAYMENTS + " WHERE\n" @@ -148,26 +149,25 @@ public class Constants { + " AND P.\"resourceServerUrl\" = '$3'"; public static final String LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER = - LIST_FAILED_OR_PENDING_PAYMENTS - + " WHERE \n" - + " I.order_id = $1 " - + " AND I.consumer_id = '$2' AND I.payment_status = 'PENDING' " - + " AND P.\"resourceServerUrl\" = '$3'"; - - public static final String LIST_FAILED_PAYMENTS_4_CONSUMER = LIST_PENDING_PAYMENTS_4_CONSUMER.replace("PENDING","FAILED"); - public static final String LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT = LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT - .replace("PENDING", "FAILED"); - public static final String LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE = LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE - .replace("PENDING", "FAILED"); + LIST_FAILED_OR_PENDING_PAYMENTS + + " WHERE \n" + + " I.order_id = $1 " + + " AND I.consumer_id = '$2' AND I.payment_status = 'PENDING' " + + " AND P.\"resourceServerUrl\" = '$3'"; + public static final String LIST_FAILED_PAYMENTS_4_CONSUMER = + LIST_PENDING_PAYMENTS_4_CONSUMER.replace("PENDING", "FAILED"); + public static final String LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT = + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_PRODUCT.replace("PENDING", "FAILED"); + public static final String LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE = + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_RESOURCE.replace("PENDING", "FAILED"); public static final String LIST_FAILED_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER = - LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER - .replace("PENDING", "FAILED"); + LIST_PENDING_PAYMENTS_4_CONSUMER_WITH_GIVEN_ORDER.replace("PENDING", "FAILED"); public static final String INSERT_INVOICE_QUERY = - "insert into $0 (_id, consumer_id, order_id, product_variant_id, payment_status, payment_time, expiry) " - + "values ('$1', '$2', '$3', '$4', '$5', '$6', (select validity from $p where _id = '$4'))"; + "insert into $0 (_id, consumer_id, order_id, product_variant_id, payment_status, payment_time, expiry) " + + "values ('$1', '$2', '$3', '$4', '$5', '$6', (select validity from $p where _id = '$4'))"; public static final String TRANSFER_ID = "id"; public static final String SOURCE = "source"; @@ -180,21 +180,21 @@ public class Constants { public static final String TRANSFERS = "transfers"; public static final String TABLES = "tables"; -// public static final String FETCH_ACTIVE_PRODUCT_VARIANTS = -// "SELECT _id AS \"productVariantId\"," -// + " product_variant_name AS \"productVariantName\", \"product_id\" AS \"productId\",\n" -// + "provider_id AS \"providerId\", resource_info AS \"resources\", \n" -// + "price AS \"price\", validity AS \"expiryInMonths\"\n" -// + " , modified_at AS \"updatedAt\" " -// + " , created_at AS \"createdAt\" " -// + "FROM product_variant\n" -// + "WHERE product_id = '$1'\n" -// + "AND status = 'ACTIVE' " -// + " ORDER BY modified_at DESC"; + // public static final String FETCH_ACTIVE_PRODUCT_VARIANTS = + // "SELECT _id AS \"productVariantId\"," + // + " product_variant_name AS \"productVariantName\", \"product_id\" AS + // \"productId\",\n" + // + "provider_id AS \"providerId\", resource_info AS \"resources\", \n" + // + "price AS \"price\", validity AS \"expiryInMonths\"\n" + // + " , modified_at AS \"updatedAt\" " + // + " , created_at AS \"createdAt\" " + // + "FROM product_variant\n" + // + "WHERE product_id = '$1'\n" + // + "AND status = 'ACTIVE' " + // + " ORDER BY modified_at DESC"; public static final String FETCH_ACTIVE_PRODUCT_VARIANTS = "SELECT * FROM product_variant_view P\n" + "WHERE P.\"productId\" = $1 \n" + "AND P.\"productVariantStatus\" = 'ACTIVE'\n" + "AND P.\"resourceServerUrl\" = $2\n"; - -} \ No newline at end of file +} diff --git a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java index e94f5a1d..a8bd900c 100644 --- a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java +++ b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java @@ -5,28 +5,26 @@ import java.util.stream.Stream; import static iudx.data.marketplace.common.ResponseUrn.PAYMENT_STATUS_NOT_FOUND; + public enum PaymentStatus { PENDING("PENDING"), SUCCESSFUL("SUCCEEDED"), FAILED("FAILED"); private final String paymentStatus; - PaymentStatus(String value) - { + + PaymentStatus(String value) { paymentStatus = value; } - public static PaymentStatus fromString(String value) - { + public static PaymentStatus fromString(String value) { return Stream.of(values()) - .filter(element -> element.getPaymentStatus().equalsIgnoreCase(value)) - .findAny() - .orElseThrow(() -> new DxRuntimeException(404, PAYMENT_STATUS_NOT_FOUND)); + .filter(element -> element.getPaymentStatus().equalsIgnoreCase(value)) + .findAny() + .orElseThrow(() -> new DxRuntimeException(404, PAYMENT_STATUS_NOT_FOUND)); } - public String getPaymentStatus() - { + public String getPaymentStatus() { return paymentStatus; } - } diff --git a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java index 2682a477..f7f913e7 100644 --- a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java @@ -2,23 +2,16 @@ import static iudx.data.marketplace.apiserver.util.Constants.*; import static iudx.data.marketplace.auditing.util.Constants.*; -import static iudx.data.marketplace.auditing.util.Constants.RESPONSE_SIZE; -import static iudx.data.marketplace.auditing.util.Constants.USERID; import static iudx.data.marketplace.common.HttpStatusCode.BAD_REQUEST; import static iudx.data.marketplace.common.HttpStatusCode.FORBIDDEN; import static iudx.data.marketplace.common.ResponseUrn.FORBIDDEN_URN; import static iudx.data.marketplace.policies.util.Constants.CHECK_IF_POLICY_PRESENT_QUERY; import static iudx.data.marketplace.policies.util.Constants.DELETE_POLICY_QUERY; -import io.vertx.core.AsyncResult; import io.vertx.core.Future; -import io.vertx.core.Handler; import io.vertx.core.Promise; import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonObject; -import io.vertx.ext.web.RoutingContext; import io.vertx.pgclient.PgPool; import io.vertx.sqlclient.Tuple; import iudx.data.marketplace.auditing.AuditingService; @@ -27,11 +20,6 @@ import iudx.data.marketplace.common.ResponseUrn; import iudx.data.marketplace.policies.util.Status; import iudx.data.marketplace.postgres.PostgresService; -import iudx.data.marketplace.postgres.PostgresServiceImpl; - -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoUnit; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java b/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java index 63a52382..c5709481 100644 --- a/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java +++ b/src/main/java/iudx/data/marketplace/policies/FetchPolicyUsingPvId.java @@ -1,5 +1,9 @@ package iudx.data.marketplace.policies; +import static iudx.data.marketplace.policies.util.Constants.FETCH_POLICY; +import static iudx.data.marketplace.policies.util.Constants.FETCH_PRODUCT_VARIANT; +import static iudx.data.marketplace.product.util.Constants.RESULTS; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonObject; @@ -7,15 +11,10 @@ import iudx.data.marketplace.common.RespBuilder; import iudx.data.marketplace.common.ResponseUrn; import iudx.data.marketplace.postgres.PostgresService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.List; import java.util.stream.Collectors; - -import static iudx.data.marketplace.policies.util.Constants.FETCH_POLICY; -import static iudx.data.marketplace.policies.util.Constants.FETCH_PRODUCT_VARIANT; -import static iudx.data.marketplace.product.util.Constants.RESULTS; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class FetchPolicyUsingPvId { private static final Logger LOG = LoggerFactory.getLogger(FetchPolicyUsingPvId.class); diff --git a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java index 914c43b6..730041fc 100644 --- a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java @@ -1,25 +1,20 @@ package iudx.data.marketplace.policies; +import static iudx.data.marketplace.apiserver.util.Constants.*; +import static iudx.data.marketplace.common.HttpStatusCode.BAD_REQUEST; +import static iudx.data.marketplace.policies.util.Constants.GET_POLICY_4_CONSUMER_QUERY; +import static iudx.data.marketplace.policies.util.Constants.GET_POLICY_4_PROVIDER_QUERY; + import io.vertx.core.Future; import io.vertx.core.Promise; -import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; -import io.vertx.sqlclient.Tuple; import iudx.data.marketplace.apiserver.util.Role; - import iudx.data.marketplace.common.HttpStatusCode; import iudx.data.marketplace.common.ResponseUrn; import iudx.data.marketplace.postgres.PostgresService; -import iudx.data.marketplace.postgres.PostgresServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import static iudx.data.marketplace.apiserver.util.Constants.*; -import static iudx.data.marketplace.common.HttpStatusCode.BAD_REQUEST; -import static iudx.data.marketplace.policies.util.Constants.GET_POLICY_4_CONSUMER_QUERY; -import static iudx.data.marketplace.policies.util.Constants.GET_POLICY_4_PROVIDER_QUERY; - public class GetPolicy { public static final String FAILURE_MESSAGE = "Policy could not be fetched"; private static final Logger LOG = LoggerFactory.getLogger(GetPolicy.class); diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java index 233f7b94..378d1373 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java @@ -1,25 +1,13 @@ package iudx.data.marketplace.policies; +import static iudx.data.marketplace.common.Constants.*; + import io.vertx.core.AbstractVerticle; -import io.vertx.core.Vertx; -import io.vertx.pgclient.PgConnectOptions; -import io.vertx.pgclient.PgPool; import io.vertx.serviceproxy.ServiceBinder; -import io.vertx.sqlclient.PoolOptions; -import iudx.data.marketplace.apiserver.ApiServerVerticle; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.common.CatalogueService; import iudx.data.marketplace.postgres.PostgresService; -import iudx.data.marketplace.postgres.PostgresServiceImpl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import iudx.data.marketplace.common.CatalogueService; -import iudx.data.marketplace.postgres.PostgresServiceImpl; - -import java.util.Map; - -import static iudx.data.marketplace.common.Constants.*; public class PolicyVerticle extends AbstractVerticle { diff --git a/src/main/java/iudx/data/marketplace/policies/User.java b/src/main/java/iudx/data/marketplace/policies/User.java index 8d4f3336..c1bdbb51 100644 --- a/src/main/java/iudx/data/marketplace/policies/User.java +++ b/src/main/java/iudx/data/marketplace/policies/User.java @@ -1,14 +1,12 @@ package iudx.data.marketplace.policies; +import static iudx.data.marketplace.apiserver.util.Constants.*; + import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import iudx.data.marketplace.apiserver.util.Role; -import iudx.data.marketplace.policies.UserConverter; - import java.util.Objects; -import static iudx.data.marketplace.apiserver.util.Constants.*; - /** * User class is used to initialize information about the user like id, role, email-Id etc.,
    * User class can store information about Consumer, Provider.
    diff --git a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java index f4958739..d109b012 100644 --- a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java @@ -1,30 +1,24 @@ package iudx.data.marketplace.policies; +import static iudx.data.marketplace.apiserver.util.Constants.*; +import static iudx.data.marketplace.common.HttpStatusCode.INTERNAL_SERVER_ERROR; +import static iudx.data.marketplace.common.HttpStatusCode.VERIFY_FORBIDDEN; +import static iudx.data.marketplace.policies.util.Constants.*; + import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; -import io.vertx.sqlclient.Row; import io.vertx.sqlclient.Tuple; -import iudx.data.marketplace.common.CatalogueService; import iudx.data.marketplace.common.HttpStatusCode; import iudx.data.marketplace.common.ResponseUrn; import iudx.data.marketplace.policies.util.Status; import iudx.data.marketplace.postgres.PostgresService; -import iudx.data.marketplace.postgres.PostgresServiceImpl; +import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import static iudx.data.marketplace.apiserver.util.Constants.*; -import static iudx.data.marketplace.common.HttpStatusCode.INTERNAL_SERVER_ERROR; -import static iudx.data.marketplace.common.HttpStatusCode.VERIFY_FORBIDDEN; -import static iudx.data.marketplace.policies.util.Constants.*; - public class VerifyPolicy { private static final Logger LOGGER = LogManager.getLogger(VerifyPolicy.class); private final PostgresService postgresService; diff --git a/src/main/java/iudx/data/marketplace/policies/util/Constants.java b/src/main/java/iudx/data/marketplace/policies/util/Constants.java index 2382b5cb..cc3244f1 100644 --- a/src/main/java/iudx/data/marketplace/policies/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/policies/util/Constants.java @@ -1,76 +1,76 @@ package iudx.data.marketplace.policies.util; public class Constants { - public static final String CHECK_EXISTING_POLICY = - "SELECT _id,constraints FROM policy " - + "WHERE resource_id =$1::UUID AND provider_id = $2::UUID AND status = $3::policy_status" - + " AND consumer_email_id = $4::text AND expiry_at > now()"; + public static final String CHECK_EXISTING_POLICY = + "SELECT _id,constraints FROM policy " + + "WHERE resource_id =$1::UUID AND provider_id = $2::UUID AND status = $3::policy_status" + + " AND consumer_email_id = $4::text AND expiry_at > now()"; - public static final String CHECK_POLICY_FROM_ORDER_ID = - " SELECT _id,constraints FROM policy " + - " WHERE resource_id =$1::UUID " + - " AND provider_id = $2::UUID AND status = $3::policy_status " + - " AND consumer_email_id = $4::text " + - " AND expiry_at > now() " + - " AND invoice_id = ( SELECT I._id FROM invoice AS I WHERE I.order_id = $5::text)"; + public static final String CHECK_POLICY_FROM_ORDER_ID = + " SELECT _id,constraints FROM policy " + + " WHERE resource_id =$1::UUID " + + " AND provider_id = $2::UUID AND status = $3::policy_status " + + " AND consumer_email_id = $4::text " + + " AND expiry_at > now() " + + " AND invoice_id = ( SELECT I._id FROM invoice AS I WHERE I.order_id = $5::text)"; - public static final String CREATE_POLICY_QUERY = - "INSERT INTO public.policy( " + - " _id, resource_id, invoice_id, constraints, provider_id, consumer_email_id, expiry_at, " + - " status, product_variant_id) " + - " VALUES ('$1', '$2', '$3', '$4'::JSON, '$5', '$6', '$7', '$8', '$9') RETURNING _id;"; + public static final String CREATE_POLICY_QUERY = + "INSERT INTO public.policy( " + + " _id, resource_id, invoice_id, constraints, provider_id, consumer_email_id, expiry_at, " + + " status, product_variant_id) " + + " VALUES ('$1', '$2', '$3', '$4'::JSON, '$5', '$6', '$7', '$8', '$9') RETURNING _id;"; - public static final String GET_POLICY_4_PROVIDER_QUERY = - "SELECT P._id AS \"policyId\", P.resource_id AS \"resourceId\",\n" - + "RE.resource_server AS \"resourceServerUrl\",\n" - + "P.invoice_id AS \"purchaseId\",\n" - + "RE.resource_name AS \"resourceName\",\n" - + "P.product_variant_id AS \"productVariantId\",\n" - + "RE.accesspolicy AS \"accessPolicy\",\n" - + "P.consumer_email_id AS \"consumerEmailId\",\n" - + "U.first_name AS \"consumerFirstName\",\n" - + "U.last_name AS \"consumerLastName\", U._id AS \"consumerId\",\n" - + "P.status AS \"status\", P.expiry_at AS \"expiryAt\",\n" - + "P.constraints AS \"constraints\" " - + " ,P.modified_at AS \"updatedAt\" " - + " ,P.created_at AS \"createdAt\" " - + " FROM policy AS P \n" - + "LEFT JOIN user_table AS U\n" - + "ON P.consumer_email_id = U.email_id \n" - + "INNER JOIN resource_entity AS RE\n" - + "ON RE._id = P.resource_id\n" - + "AND P.provider_id = $1::uuid \n" - + "AND RE.resource_server = $2 " - + " ORDER BY P.modified_at DESC"; - public static final String GET_POLICY_4_CONSUMER_QUERY = - "SELECT P._id AS \"policyId\", P.resource_id AS \"resourceId\",\n" - + "RE.resource_server AS \"resourceServerUrl\",\n" - + "P.invoice_id AS \"purchaseId\",\n" - + "RE.resource_name AS \"resourceName\",\n" - + "P.product_variant_id AS \"productVariantId\",\n" - + "RE.accesspolicy AS \"accessPolicy\",\n" - + "P.provider_id AS \"providerId\", U.first_name AS \"providerFirstName\",\n" - + "U.last_name AS \"providerLastName\", U.email_id AS \"providerEmailId\",\n" - + "P.status as \"status\", P.expiry_at AS \"expiryAt\",\n" - + "P.constraints AS \"constraints\" \n" - + " ,P.modified_at AS \"updatedAt\" " - + " ,P.created_at AS \"createdAt\" " - + "FROM policy AS P \n" - + "INNER JOIN user_table AS U\n" - + "ON P.provider_id = U._id \n" - + "INNER JOIN resource_entity AS RE\n" - + "ON RE._id = P.resource_id\n" - + "AND P.consumer_email_id = $1 \n" - + "AND RE.resource_server = $2 " - + " ORDER BY P.modified_at DESC"; - public static final String DELETE_POLICY_QUERY = - "UPDATE policy SET status='DELETED' " - + "WHERE _id = $1::uuid AND expiry_at > NOW() RETURNING _id"; - public static final String CHECK_IF_POLICY_PRESENT_QUERY = - "SELECT p.provider_id, p.status, r.resource_server" - + " FROM policy p" - + " INNER JOIN resource_entity r ON p.resource_id = r._id" - + " WHERE p._id = $1;"; + public static final String GET_POLICY_4_PROVIDER_QUERY = + "SELECT P._id AS \"policyId\", P.resource_id AS \"resourceId\",\n" + + "RE.resource_server AS \"resourceServerUrl\",\n" + + "P.invoice_id AS \"purchaseId\",\n" + + "RE.resource_name AS \"resourceName\",\n" + + "P.product_variant_id AS \"productVariantId\",\n" + + "RE.accesspolicy AS \"accessPolicy\",\n" + + "P.consumer_email_id AS \"consumerEmailId\",\n" + + "U.first_name AS \"consumerFirstName\",\n" + + "U.last_name AS \"consumerLastName\", U._id AS \"consumerId\",\n" + + "P.status AS \"status\", P.expiry_at AS \"expiryAt\",\n" + + "P.constraints AS \"constraints\" " + + " ,P.modified_at AS \"updatedAt\" " + + " ,P.created_at AS \"createdAt\" " + + " FROM policy AS P \n" + + "LEFT JOIN user_table AS U\n" + + "ON P.consumer_email_id = U.email_id \n" + + "INNER JOIN resource_entity AS RE\n" + + "ON RE._id = P.resource_id\n" + + "AND P.provider_id = $1::uuid \n" + + "AND RE.resource_server = $2 " + + " ORDER BY P.modified_at DESC"; + public static final String GET_POLICY_4_CONSUMER_QUERY = + "SELECT P._id AS \"policyId\", P.resource_id AS \"resourceId\",\n" + + "RE.resource_server AS \"resourceServerUrl\",\n" + + "P.invoice_id AS \"purchaseId\",\n" + + "RE.resource_name AS \"resourceName\",\n" + + "P.product_variant_id AS \"productVariantId\",\n" + + "RE.accesspolicy AS \"accessPolicy\",\n" + + "P.provider_id AS \"providerId\", U.first_name AS \"providerFirstName\",\n" + + "U.last_name AS \"providerLastName\", U.email_id AS \"providerEmailId\",\n" + + "P.status as \"status\", P.expiry_at AS \"expiryAt\",\n" + + "P.constraints AS \"constraints\" \n" + + " ,P.modified_at AS \"updatedAt\" " + + " ,P.created_at AS \"createdAt\" " + + "FROM policy AS P \n" + + "INNER JOIN user_table AS U\n" + + "ON P.provider_id = U._id \n" + + "INNER JOIN resource_entity AS RE\n" + + "ON RE._id = P.resource_id\n" + + "AND P.consumer_email_id = $1 \n" + + "AND RE.resource_server = $2 " + + " ORDER BY P.modified_at DESC"; + public static final String DELETE_POLICY_QUERY = + "UPDATE policy SET status='DELETED' " + + "WHERE _id = $1::uuid AND expiry_at > NOW() RETURNING _id"; + public static final String CHECK_IF_POLICY_PRESENT_QUERY = + "SELECT p.provider_id, p.status, r.resource_server" + + " FROM policy p" + + " INNER JOIN resource_entity r ON p.resource_id = r._id" + + " WHERE p._id = $1;"; public static final String GET_REQUIRED_INFO_QUERY = "SELECT DISTINCT I._id AS \"invoiceId\", I.product_variant_id AS \"productVariantId\", I.expiry, " @@ -88,17 +88,16 @@ public class Constants { + " WHERE payment_status = 'SUCCEEDED' " + " AND order_id = '$1';"; - public static final String FETCH_PRODUCT_VARIANT = - " SELECT \"resourceServerUrl\", \"resources\" " - + "FROM product_variant_view " - + "WHERE \"productVariantId\" = '$1' " - + "AND \"productVariantStatus\" = 'ACTIVE'"; + public static final String FETCH_PRODUCT_VARIANT = + " SELECT \"resourceServerUrl\", \"resources\" " + + "FROM product_variant_view " + + "WHERE \"productVariantId\" = '$1' " + + "AND \"productVariantStatus\" = 'ACTIVE'"; - - public static final String FETCH_POLICY = - " SELECT DISTINCT resource_id AS \"resources\" FROM policy " - + "WHERE resource_id = ANY($1) " - + "AND status = 'ACTIVE' " - + " AND consumer_email_id = $2" - + " AND expiry_at > NOW(); "; -} \ No newline at end of file + public static final String FETCH_POLICY = + " SELECT DISTINCT resource_id AS \"resources\" FROM policy " + + "WHERE resource_id = ANY($1) " + + "AND status = 'ACTIVE' " + + " AND consumer_email_id = $2" + + " AND expiry_at > NOW(); "; +} diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java index 222b25d1..3d5991ad 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java @@ -12,12 +12,12 @@ import java.util.List; /** - * The Postgres Service + * The Postgres Service * - *

    Postgres Service

    + *

    Postgres Service

    * - *

    The Postgres Service in the IUDX Data Marketplace defines the operations to be performed - * on the marketplace database

    + *

    The Postgres Service in the IUDX Data Marketplace defines the operations to be performed on + * the marketplace database * * @see io.vertx.codegen.annotations.ProxyGen * @see io.vertx.codegen.annotations.VertxGen @@ -30,6 +30,7 @@ public interface PostgresService { /** * The createProxy helps the code generation blocks to generate proxy code. + * * @param vertx which is the vertx instance * @param address which is the proxy address * @return PostgresServiceVertxRBProxy which is a service proxy @@ -60,7 +61,8 @@ static PostgresService createProxy(Vertx vertx, String address) { PostgresService executeCountQuery(final String query, Handler> handler); /** - * The executePreparedQuery implements a single query operation with configurable queryParams on the database. + * The executePreparedQuery implements a single query operation with configurable queryParams on + * the database. * * @param query which is a String * @param queryparams which is a JsonObject @@ -72,15 +74,18 @@ PostgresService executePreparedQuery( final String query, final JsonObject queryparams, Handler> handler); /** - * The executeTransaction implements a transaction operation(with multiple queries) on the database. + * The executeTransaction implements a transaction operation(with multiple queries) on the + * database. * * @param queries which is a List of String * @param handler which is a Request Handler * @return PostgresService which ia a service */ @Fluent - PostgresService executeTransaction(final List queries, Handler> handler); + PostgresService executeTransaction( + final List queries, Handler> handler); @Fluent - PostgresService checkPolicy(final String query,final JsonObject param, Handler> handler); + PostgresService checkPolicy( + final String query, final JsonObject param, Handler> handler); } diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java index d77fe094..459d20b0 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java @@ -27,11 +27,11 @@ import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; import static iudx.data.marketplace.apiserver.util.Constants.STATUS_CODE; - public class PostgresServiceImpl implements PostgresService { private static final Logger LOGGER = LogManager.getLogger(PostgresServiceImpl.class); private final PgPool client; + public PostgresServiceImpl(final PgPool pgclient) { this.client = pgclient; } @@ -53,14 +53,16 @@ private static Future executeBatch( .map(rows -> rows.value()) .onSuccess( successHandler -> { - executeBatch(conn, statements).onComplete(h -> { - promise.complete(); - }); + executeBatch(conn, statements) + .onComplete( + h -> { + promise.complete(); + }); }) .onFailure( failureHandler -> { - LOGGER.debug("Failure : {}",failureHandler.getMessage() ); - LOGGER.error("Fail db"); + LOGGER.debug("Failure : {}", failureHandler.getMessage()); + LOGGER.error("Fail db"); promise.fail(failureHandler); }); return promise.future(); @@ -93,8 +95,8 @@ public PostgresService executeQuery( }) .onFailure( failureHandler -> { - LOGGER.debug("Failure : {}",failureHandler.getMessage() ); - String response = + LOGGER.debug("Failure : {}", failureHandler.getMessage()); + String response = new RespBuilder() .withType(ResponseUrn.DB_ERROR_URN.getUrn()) .withTitle(ResponseUrn.DB_ERROR_URN.getMessage()) @@ -118,8 +120,8 @@ public PostgresService executeCountQuery( }) .onFailure( failureHandler -> { - LOGGER.debug("Failure : {}",failureHandler.getMessage() ); - String response = + LOGGER.debug("Failure : {}", failureHandler.getMessage()); + String response = new RespBuilder() .withType(ResponseUrn.DB_ERROR_URN.getUrn()) .withTitle(ResponseUrn.DB_ERROR_URN.getMessage()) @@ -153,8 +155,8 @@ public PostgresService executeTransaction( handler.handle(Future.succeededFuture(responseJson)); } else { LOGGER.debug("transaction failed"); - LOGGER.debug("Failure : {}",completeHandler.cause().getMessage()); - String response = + LOGGER.debug("Failure : {}", completeHandler.cause().getMessage()); + String response = new RespBuilder() .withType(ResponseUrn.DB_ERROR_URN.getUrn()) .withTitle(ResponseUrn.DB_ERROR_URN.getMessage()) @@ -201,7 +203,7 @@ public PostgresService executePreparedQuery( }) .onFailure( failureHandler -> { - LOGGER.debug("Failure : {}",failureHandler.getMessage()); + LOGGER.debug("Failure : {}", failureHandler.getMessage()); String response = new RespBuilder() .withType(ResponseUrn.DB_ERROR_URN.getUrn()) @@ -223,10 +225,10 @@ public PostgresService checkPolicy( LOGGER.debug("query params : " + queryParams.encode()); // Tuple tuple = Tuple.of(resourceIds,consumerEmailId); - UUID[] ids = resourceIds.stream().map(e -> UUID.fromString(e.toString())).toArray(UUID[]::new); + UUID[] ids = resourceIds.stream().map(e -> UUID.fromString(e.toString())).toArray(UUID[]::new); Tuple tuple = Tuple.of(ids, consumerEmailId); - Collector> rowCollector = + Collector> rowCollector = Collectors.mapping(row -> row.toJson(), Collectors.toList()); client @@ -242,8 +244,11 @@ public PostgresService checkPolicy( LOGGER.debug("response from DB from fetch policy : {}", successHandler); if (successHandler.isEmpty()) { LOGGER.error("Empty from DB while fetching policy related info"); - JsonObject response = new JsonObject() - .put(RESULTS, new RespBuilder() + JsonObject response = + new JsonObject() + .put( + RESULTS, + new RespBuilder() .withType(HttpStatusCode.NO_CONTENT.getValue()) .withTitle(HttpStatusCode.NO_CONTENT.getUrn()) .getJsonResponse()); @@ -252,10 +257,13 @@ public PostgresService checkPolicy( response.put(STATUS_CODE, HttpStatusCode.NO_CONTENT.getValue()))); } else { - List resourceId = successHandler.stream().map(e -> e.getString("resources")).collect(Collectors.toList()); + List resourceId = + successHandler.stream() + .map(e -> e.getString("resources")) + .collect(Collectors.toList()); LOGGER.info( "Policy exists for the resource IDs : {} present in the product variant", - resourceId); + resourceId); JsonObject responseJson = new JsonObject() .put( @@ -263,8 +271,9 @@ public PostgresService checkPolicy( new RespBuilder() .withType(ResponseUrn.SUCCESS_URN.getUrn()) .withTitle(ResponseUrn.SUCCESS_URN.getMessage()) - .withDetail("Policy exists for the resource ID(s) : " + - resourceId + .withDetail( + "Policy exists for the resource ID(s) : " + + resourceId + " from the product variant") .getJsonResponse()) .put(STATUS_CODE, HttpStatusCode.SUCCESS.getValue()); diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java b/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java index 77cc2504..7dc0d799 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java @@ -1,5 +1,7 @@ package iudx.data.marketplace.postgres; +import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -10,8 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; - public class PostgresVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(PostgresVerticle.class); private MessageConsumer consumer; diff --git a/src/main/java/iudx/data/marketplace/product/ProductVerticle.java b/src/main/java/iudx/data/marketplace/product/ProductVerticle.java index 17449543..85006b05 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductVerticle.java +++ b/src/main/java/iudx/data/marketplace/product/ProductVerticle.java @@ -1,5 +1,7 @@ package iudx.data.marketplace.product; +import static iudx.data.marketplace.common.Constants.*; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -10,8 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.*; - public class ProductVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(ProductVerticle.class); private MessageConsumer consumer; diff --git a/src/main/java/iudx/data/marketplace/product/util/Constants.java b/src/main/java/iudx/data/marketplace/product/util/Constants.java index fba34b66..844ccfab 100644 --- a/src/main/java/iudx/data/marketplace/product/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/product/util/Constants.java @@ -29,11 +29,13 @@ public class Constants { public static final String INSERT_P_R_REL_QUERY = "insert into $0 (product_id, resource_id) values ('$1', '$2')"; - public static final String DELETE_PRODUCT_QUERY = "update $0 set status=$1 where product_id=$2 and status = 'ACTIVE' returning product_id"; - public static final String DELETE_PV_QUERY = "UPDATE product_variant SET status = 'INACTIVE' WHERE \n " + - "product_id = $1 \n " + - "AND provider_id = $2 \n " + - "RETURNING _id"; + public static final String DELETE_PRODUCT_QUERY = + "update $0 set status=$1 where product_id=$2 and status = 'ACTIVE' returning product_id"; + public static final String DELETE_PV_QUERY = + "UPDATE product_variant SET status = 'INACTIVE' WHERE \n " + + "product_id = $1 \n " + + "AND provider_id = $2 \n " + + "RETURNING _id"; public static final String LIST_PRODUCT_FOR_RESOURCE = "select pt.product_id AS \"productId\", pt.provider_name AS \"providerName\", " + " pt.modified_at AS \"updatedAt\" , pt.created_at AS \"createdAt\" ," @@ -59,12 +61,15 @@ public class Constants { + "group by pt.product_id"; public static final String INSERT_PV_QUERY = - "insert into $0 (_id, provider_id, product_id, product_variant_name, resource_info, price, validity, status)" + - " values ('$1', '$2', '$3', '$4','$5'::JSON, '$6', $7, '$s') RETURNING _id"; + "insert into $0 (_id, provider_id, product_id, product_variant_name, resource_info, price, validity, status)" + + " values ('$1', '$2', '$3', '$4','$5'::JSON, '$6', $7, '$s') RETURNING _id"; - public static final String UPDATE_PV_STATUS = "update $0 set status='$4' where product_id='$1' and product_variant_name='$2' and status='$3'"; - public static final String CHECK_IF_PV_EXISTS = "SELECT * FROM product_variant WHERE product_id = '$1' AND product_variant_name = '$2' AND status = 'ACTIVE'"; - public static final String CHECK_IF_PRODUCT_EXISTS = "SELECT * FROM product WHERE product_id = '$1' "; + public static final String UPDATE_PV_STATUS = + "update $0 set status='$4' where product_id='$1' and product_variant_name='$2' and status='$3'"; + public static final String CHECK_IF_PV_EXISTS = + "SELECT * FROM product_variant WHERE product_id = '$1' AND product_variant_name = '$2' AND status = 'ACTIVE'"; + public static final String CHECK_IF_PRODUCT_EXISTS = + "SELECT * FROM product WHERE product_id = '$1' "; public static final String UPDATE_PV_STATUS_QUERY = "update $0 set status='$4' where _id='$1' and status='$3' RETURNING _id"; public static final String SELECT_PV_QUERY = @@ -109,8 +114,9 @@ public class Constants { + " INNER JOIN user_table U\n" + " ON U._id = I.consumer_id "; public static final String LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER = - LIST_SUCCESSFUL_PURCHASE + "WHERE P.\"providerId\" = '$1' " - + " AND P.\"resourceServerUrl\" = '$2'"; + LIST_SUCCESSFUL_PURCHASE + + "WHERE P.\"providerId\" = '$1' " + + " AND P.\"resourceServerUrl\" = '$2'"; public static final String LIST_SUCCESSFUL_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT = LIST_SUCCESSFUL_PURCHASE + "WHERE\n" @@ -129,7 +135,7 @@ public class Constants { public static final String LIST_PENDING_PAYMENTS_4_PROVIDER = LIST_FAILED_OR_PENDING_PAYMENTS + "WHERE P.\"providerId\" = '$1' AND I.payment_status = 'PENDING' " - + " AND P.\"resourceServerUrl\" = '$2'"; + + " AND P.\"resourceServerUrl\" = '$2'"; public static final String LIST_PENDING_PAYMENTS_4_PROVIDER_WITH_GIVEN_PRODUCT = LIST_FAILED_OR_PENDING_PAYMENTS + "WHERE\n" diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index 200a55ed..5b152e00 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -11,7 +11,6 @@ import java.util.List; import java.util.UUID; import java.util.function.Supplier; - import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java index d21e2769..90e088c8 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantVerticle.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.product.variant; +import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; +import static iudx.data.marketplace.common.Constants.PRODUCT_VARIANT_SERVICE_ADDRESS; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -9,9 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; -import static iudx.data.marketplace.common.Constants.PRODUCT_VARIANT_SERVICE_ADDRESS; - public class ProductVariantVerticle extends AbstractVerticle { public static final Logger LOGGER = LogManager.getLogger(ProductVariantVerticle.class); private MessageConsumer consumer; diff --git a/src/main/java/iudx/data/marketplace/razorpay/Constants.java b/src/main/java/iudx/data/marketplace/razorpay/Constants.java index b9527e25..b609f821 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/Constants.java +++ b/src/main/java/iudx/data/marketplace/razorpay/Constants.java @@ -27,5 +27,6 @@ public class Constants { public static final String RAZORPAY_PAYMENT_ID = "razorpay_payment_id"; public static final String RAZORPAY_SIGNATURE = "razorpay_signature"; - public static final String RECORD_PAYMENT = "insert into $0 (order_id, payment_id, payment_signature) values ($1,$2,$3) on conflict do nothing"; + public static final String RECORD_PAYMENT = + "insert into $0 (order_id, payment_id, payment_signature) values ($1,$2,$3) on conflict do nothing"; } diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayVerticle.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayVerticle.java index f1c4ebf8..9297c1fe 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayVerticle.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayVerticle.java @@ -1,5 +1,10 @@ package iudx.data.marketplace.razorpay; +import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; +import static iudx.data.marketplace.common.Constants.RAZORPAY_SERVICE_ADDRESS; +import static iudx.data.marketplace.razorpay.Constants.RAZORPAY_KEY; +import static iudx.data.marketplace.razorpay.Constants.RAZORPAY_SECRET; + import com.razorpay.RazorpayClient; import com.razorpay.RazorpayException; import io.vertx.core.AbstractVerticle; @@ -10,11 +15,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.POSTGRES_SERVICE_ADDRESS; -import static iudx.data.marketplace.common.Constants.RAZORPAY_SERVICE_ADDRESS; -import static iudx.data.marketplace.razorpay.Constants.RAZORPAY_KEY; -import static iudx.data.marketplace.razorpay.Constants.RAZORPAY_SECRET; - public class RazorPayVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(AbstractVerticle.class); private MessageConsumer consumer; diff --git a/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java b/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java index af94b4b7..1113d4de 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java +++ b/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java @@ -1,11 +1,10 @@ package iudx.data.marketplace.razorpay.util; -import iudx.data.marketplace.common.ResponseUrn; +import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; +import iudx.data.marketplace.common.ResponseUrn; import java.util.Map; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; - public class ErrorMessageBuilder { public static Map initialiseMap() { diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java index 11fc35fe..4b8d71ba 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java @@ -7,7 +7,8 @@ import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; -@VertxGen @ProxyGen +@VertxGen +@ProxyGen public interface WebhookService { /** diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java index ec4df868..4e3e1bb2 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.webhook; +import static iudx.data.marketplace.common.Constants.*; +import static iudx.data.marketplace.product.util.Constants.TABLES; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -9,9 +12,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.data.marketplace.common.Constants.*; -import static iudx.data.marketplace.product.util.Constants.TABLES; - public class WebhookVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(WebhookVerticle.class); From 6594b1707ab767ded81dd7f27e026cef4f485dc7 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 12:19:57 +0530 Subject: [PATCH 03/15] Refactor: resolve checsktyle issues --- .../apiserver/handlers/ExceptionHandler.java | 4 +- .../linkedAccount/CreateLinkedAccount.java | 17 +++-- .../validation/ValidationHandlerFactory.java | 10 +-- .../types/JsonSchemaTypeValidator.java | 12 ++-- .../types/OrderIdTypeValidator.java | 4 +- .../types/ProductIdTypeValidator.java | 4 +- .../validation/types/UuidTypeValidator.java | 4 +- .../AuthenticationServiceImpl.java | 22 +++--- .../authorization/AuthorizationRequest.java | 9 ++- .../authenticator/authorization/IudxRole.java | 1 - .../marketplace/common/CatalogueService.java | 28 ++++---- .../consumer/ConsumerServiceImpl.java | 16 ++--- .../consumer/util/PaymentStatus.java | 5 +- .../data/marketplace/policies/GetPolicy.java | 67 +++++++++---------- .../marketplace/postgres/PostgresService.java | 1 - .../postgres/PostgresServiceImpl.java | 11 ++- .../postgres/PostgresVerticle.java | 6 +- .../product/ProductServiceImpl.java | 38 +++++------ .../product/util/QueryBuilder.java | 18 ++--- .../variant/ProductVariantServiceImpl.java | 34 +++++----- .../marketplace/razorpay/RazorPayService.java | 2 +- .../razorpay/RazorPayServiceImpl.java | 4 +- .../marketplace/webhook/WebhookService.java | 4 +- 23 files changed, 157 insertions(+), 164 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java index 9f071fec..5bfdbe3f 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java @@ -59,7 +59,7 @@ public void handle(RoutingContext routingContext) { LOGGER.error(" -------------- "); LOGGER.error(failure.fillInStackTrace()); - String INTERNAL_ERROR_RESP = + String internalErrorResp = new RespBuilder() .withType(ResponseUrn.INTERNAL_SERVER_ERR_URN.getUrn()) .withTitle(ResponseUrn.INTERNAL_SERVER_ERR_URN.getMessage()) @@ -69,7 +69,7 @@ public void handle(RoutingContext routingContext) { .response() .setStatusCode(500) .putHeader(HEADER_CONTENT_TYPE, APPLICATION_JSON) - .end(INTERNAL_ERROR_RESP); + .end(internalErrorResp); routingContext.next(); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index 06fb8fe8..cb658d82 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.apiserver.provider.linkedAccount; +import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.util.Constants.*; + import com.google.common.hash.Hashing; import io.vertx.core.Future; import io.vertx.core.Promise; @@ -13,16 +16,12 @@ import iudx.data.marketplace.policies.User; import iudx.data.marketplace.postgres.PostgresService; import iudx.data.marketplace.razorpay.RazorPayService; -import org.apache.commons.lang.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Arrays; - -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; -import static iudx.data.marketplace.apiserver.util.Constants.*; +import org.apache.commons.lang.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class CreateLinkedAccount { private static final Logger LOGGER = LogManager.getLogger(CreateLinkedAccount.class); @@ -73,7 +72,7 @@ public Future initiateCreatingLinkedAccount(JsonObject request, User isRazorpayFlowSuccessful -> { if (isRazorpayFlowSuccessful) { /* insert in DB */ - return insertInfoInDB(INSERT_MERCHANT_INFO_QUERY, referenceId); + return insertInfoInDb(INSERT_MERCHANT_INFO_QUERY, referenceId); } else { return Future.failedFuture(razorpayFlowFuture.cause().getMessage()); } @@ -214,7 +213,7 @@ public JsonObject getLinkedAccountDetails( * @param referenceId Acts as primary key to store record * @return Success or failure response of type Future Json object */ - Future insertInfoInDB(String query, String referenceId) { + Future insertInfoInDb(String query, String referenceId) { Promise promise = Promise.promise(); String finalQuery = query diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java index f6f49aa0..ba9c303b 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java @@ -34,10 +34,10 @@ public List build( validator = listProductVariantValidators(parameters); break; case RESOURCE: - validator = getResourceIDValidators(parameters); + validator = getResourceIdValidators(parameters); break; case PROVIDER: - validator = getProviderIDValidators(parameters); + validator = getProviderIdValidators(parameters); break; case POLICY: validator = getPolicyValidators(body); @@ -69,6 +69,8 @@ public List build( case CHECK_POLICY: validator = getCheckPolicyValidator(parameters); break; + default: + break; } return validator; } @@ -137,7 +139,7 @@ private List getPolicyValidators(final JsonObject body) { return validators; } - private List getResourceIDValidators(final MultiMap parameters) { + private List getResourceIdValidators(final MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get("resourceId"), false)); @@ -145,7 +147,7 @@ private List getResourceIDValidators(final MultiMap parameters) { return validators; } - private List getProviderIDValidators(final MultiMap parameters) { + private List getProviderIdValidators(final MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get(PROVIDER_ID), false)); diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java index 4a85a33b..32eed0d0 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -1,9 +1,11 @@ package iudx.data.marketplace.apiserver.validation.types; +import static iudx.data.marketplace.common.ResponseUrn.INVALID_PAYLOAD_FORMAT_URN; +import static iudx.data.marketplace.common.ResponseUrn.SCHEMA_READ_ERROR_URN; + import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.exceptions.ProcessingException; -import com.github.fge.jsonschema.core.report.ProcessingMessage; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; @@ -11,16 +13,10 @@ import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; import iudx.data.marketplace.apiserver.util.RequestType; import iudx.data.marketplace.common.HttpStatusCode; +import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; - -import static iudx.data.marketplace.common.ResponseUrn.INVALID_PAYLOAD_FORMAT_URN; -import static iudx.data.marketplace.common.ResponseUrn.SCHEMA_READ_ERROR_URN; - public class JsonSchemaTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(JsonSchemaTypeValidator.class); private static String pkg = Validator.class.getPackageName(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java index 89fc0bde..7ea5e9a1 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/OrderIdTypeValidator.java @@ -20,7 +20,7 @@ public OrderIdTypeValidator(final String value, final boolean required) { this.required = required; } - public boolean isValidID(final String value) { + public boolean isValidId(final String value) { return ORDER_ID_PATTERN.matcher(value).matches(); } @@ -43,7 +43,7 @@ public boolean isValid() { LOGGER.error("Validation error : Value exceed min character limit."); throw new DxRuntimeException(failureCode(), INVALID_ID_VALUE_URN, failureMessage(value)); } - if (!isValidID(value)) { + if (!isValidId(value)) { LOGGER.error("Validation error : Invalid Order ID"); throw new DxRuntimeException(failureCode(), INVALID_ID_VALUE_URN, failureMessage(value)); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/ProductIdTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/ProductIdTypeValidator.java index f17cbce5..6266243c 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/ProductIdTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/ProductIdTypeValidator.java @@ -21,7 +21,7 @@ public ProductIdTypeValidator(final String value, final boolean required) { this.required = required; } - public boolean isValidID(final String value) { + public boolean isValidId(final String value) { String[] variable = value.split(":"); try { boolean isValidUrn = StringUtils.isNotBlank(variable[0]) && variable[0].equals(STRING_URN); @@ -57,7 +57,7 @@ public boolean isValid() { LOGGER.error("Validation error : Value exceed max character limit."); throw new DxRuntimeException(failureCode(), INVALID_ID_VALUE_URN, failureMessage(value)); } - if (!isValidID(value)) { + if (!isValidId(value)) { LOGGER.error("Validation error : Invalid Name"); throw new DxRuntimeException(failureCode(), INVALID_ID_VALUE_URN, failureMessage(value)); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/UuidTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/UuidTypeValidator.java index 9002a391..c4bc493e 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/UuidTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/UuidTypeValidator.java @@ -20,7 +20,7 @@ public UuidTypeValidator(final String value, final boolean required) { this.required = required; } - public boolean isValidID(final String value) { + public boolean isValidId(final String value) { return VALIDATION_IUDX_ID_REGEX.matcher(value).matches(); } @@ -43,7 +43,7 @@ public boolean isValid() { LOGGER.error("Validation error : Value mismatch character limit."); throw new DxRuntimeException(failureCode(), INVALID_ID_URN, failureMessage(value)); } - if (!isValidID(value)) { + if (!isValidId(value)) { LOGGER.error("Validation error : Invalid ID"); throw new DxRuntimeException(failureCode(), INVALID_ID_URN, failureMessage(value)); } diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java index 5dcb3c11..75dfaa23 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java @@ -1,10 +1,10 @@ package iudx.data.marketplace.authenticator; -import iudx.data.marketplace.authenticator.authorization.*; -import iudx.data.marketplace.authenticator.model.JwtData; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import iudx.data.marketplace.common.Api; +import static iudx.data.marketplace.apiserver.util.Constants.*; +import static iudx.data.marketplace.apiserver.util.Constants.API_ENDPOINT; +import static iudx.data.marketplace.authenticator.authorization.IudxRole.DELEGATE; +import static iudx.data.marketplace.authenticator.util.Constants.*; +import static iudx.data.marketplace.common.Constants.APD_URL; import io.vertx.core.AsyncResult; import io.vertx.core.Future; @@ -14,13 +14,11 @@ import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.authentication.TokenCredentials; import io.vertx.ext.auth.jwt.JWTAuth; - -import static iudx.data.marketplace.apiserver.util.Constants.*; -import static iudx.data.marketplace.apiserver.util.Constants.API_ENDPOINT; -import static iudx.data.marketplace.apiserver.util.Constants.METHOD; -import static iudx.data.marketplace.authenticator.authorization.IudxRole.DELEGATE; -import static iudx.data.marketplace.authenticator.util.Constants.*; -import static iudx.data.marketplace.common.Constants.APD_URL; +import iudx.data.marketplace.authenticator.authorization.*; +import iudx.data.marketplace.authenticator.model.JwtData; +import iudx.data.marketplace.common.Api; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class AuthenticationServiceImpl implements AuthenticationService { diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java index 004f3477..61c5466f 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationRequest.java @@ -1,6 +1,5 @@ package iudx.data.marketplace.authenticator.authorization; - import java.util.Objects; public class AuthorizationRequest { @@ -23,8 +22,12 @@ public Method getMethod() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuthorizationRequest)) return false; + if (this == o) { + return true; + } + if (!(o instanceof AuthorizationRequest)) { + return false; + } AuthorizationRequest that = (AuthorizationRequest) o; return method == that.method && Objects.equals(api, that.api); } diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java index 3d9ed735..eca9b2e9 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/IudxRole.java @@ -1,7 +1,6 @@ package iudx.data.marketplace.authenticator.authorization; import iudx.data.marketplace.authenticator.model.JwtData; - import java.util.stream.Stream; public enum IudxRole { diff --git a/src/main/java/iudx/data/marketplace/common/CatalogueService.java b/src/main/java/iudx/data/marketplace/common/CatalogueService.java index 9284419b..04031f42 100644 --- a/src/main/java/iudx/data/marketplace/common/CatalogueService.java +++ b/src/main/java/iudx/data/marketplace/common/CatalogueService.java @@ -48,15 +48,15 @@ public CatalogueService(Vertx vertx, JsonObject config) { * using a webClient * * @see io.vertx.ext.web.client.WebClient - * @param itemID which is String + * @param itemId which is String * @return Future which is of type JsonObject */ - public Future getItemDetails(String itemID) { + public Future getItemDetails(String itemId) { Promise promise = Promise.promise(); JsonObject itemDetails = new JsonObject(); catWebClient .get(catPort, catHost, catItemPath) - .addQueryParam("id", itemID) + .addQueryParam("id", itemId) .send( catItemHandler -> { if (catItemHandler.succeeded()) { @@ -67,13 +67,13 @@ public Future getItemDetails(String itemID) { if (result.getJsonArray("type").contains(TYPE_PROVIDER)) { itemDetails .put("type", TYPE_PROVIDER) - .put(PROVIDER_ID, itemID) + .put(PROVIDER_ID, itemId) .put("ownerUserId", result.getString("ownerUserId", "")) .put(PROVIDER_NAME, result.getString("description", "")); } else if (result.getJsonArray("type").contains(TYPE_RI)) { itemDetails .put("type", TYPE_RI) - .put(RESOURCE_ID, itemID) + .put(RESOURCE_ID, itemId) .put(RESOURCE_NAME, result.getString("label", "")) .put(RESOURCE_SERVER, result.getValue(RESOURCE_SERVER)) .put(PROVIDER, result.getValue(PROVIDER)) @@ -82,11 +82,11 @@ public Future getItemDetails(String itemID) { } promise.complete(itemDetails); } else { - promise.fail("Item with id { " + itemID + " } not found "); + promise.fail("Item with id { " + itemId + " } not found "); } } else { - LOGGER.debug("Cat web client call to {} failed for id: {} ", catItemPath, itemID); - promise.fail("Cat web client call to " + catItemPath + " failed for id: " + itemID); + LOGGER.debug("Cat web client call to {} failed for id: {} ", catItemPath, itemId); + promise.fail("Cat web client call to " + catItemPath + " failed for id: " + itemId); } }); @@ -97,27 +97,27 @@ public Future getItemDetails(String itemID) { * The getResourceCount method calls the IUDX catalogue relationship endpoint using a webClient * * @see io.vertx.ext.web.client.WebClient - * @param resourceID which is a String + * @param resourceId which is a String * @return Future which is of type JsonObject */ - public Future getResourceCount(String resourceID) { + public Future getResourceCount(String resourceId) { Promise promise = Promise.promise(); catWebClient .get(catPort, catHost, catRelPath) - .addQueryParam("id", resourceID) + .addQueryParam("id", resourceId) .addQueryParam("rel", "resource") .send( catRelHandler -> { if (catRelHandler.succeeded()) { int totalHits = catRelHandler.result().bodyAsJsonObject().getInteger("totalHits"); JsonObject res = - new JsonObject().put(RESOURCE_ID, resourceID).put("totalHits", totalHits); + new JsonObject().put(RESOURCE_ID, resourceId).put("totalHits", totalHits); promise.complete(res); } else { LOGGER.debug( - "Cat web client call to {} failed for id: {} ", catRelPath, resourceID); + "Cat web client call to {} failed for id: {} ", catRelPath, resourceId); promise.fail( - "Cat web client call to " + catItemPath + " failed for id: " + resourceID); + "Cat web client call to " + catItemPath + " failed for id: " + resourceId); } }); diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java index 109e8232..cdfd5512 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java @@ -70,12 +70,12 @@ public ConsumerService listResources( StringBuilder query = new StringBuilder(LIST_RESOURCES_QUERY.replace("$0", resourceTable)); if (request.containsKey("resourceId")) { - String resourceID = request.getString("resourceId"); - params.put("resourceId", resourceID); + String resourceId = request.getString("resourceId"); + params.put("resourceId", resourceId); query = new StringBuilder(LIST_RESOURCES_QUERY_4_RESOURCE.replace("$0", resourceTable)); } else if (request.containsKey("providerId")) { - String providerID = request.getString("providerId"); - params.put("providerId", providerID); + String providerId = request.getString("providerId"); + params.put("providerId", providerId); query = new StringBuilder(LIST_RESOURCES_QUERY_4_PROVIDER.replace("$0", resourceTable)); } LOGGER.debug("List resources query : {}", query); @@ -102,8 +102,8 @@ public ConsumerService listProviders( String query = LIST_PROVIDERS_QUERY; if (request.containsKey("providerId")) { - String providerID = request.getString("providerId"); - params.put("providerId", providerID); + String providerId = request.getString("providerId"); + params.put("providerId", providerId); query = LIST_PROVIDER_WITH_GIVEN_PROVIDER_ID; } LOGGER.debug("Query : " + query); @@ -144,8 +144,8 @@ public ConsumerService listProducts( params.put("resourceId", resourceID); query.append(" and rt._id=$2"); } else if (request.containsKey("providerId")) { - String providerID = request.getString("providerId"); - params.put("providerId", providerID); + String providerId = request.getString("providerId"); + params.put("providerId", providerId); query.append(" and pt.provider_id=$2"); } query.append(" group by pt.product_id, rt.resource_server"); diff --git a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java index a8bd900c..4f4e005c 100644 --- a/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java +++ b/src/main/java/iudx/data/marketplace/consumer/util/PaymentStatus.java @@ -1,11 +1,10 @@ package iudx.data.marketplace.consumer.util; -import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; +import static iudx.data.marketplace.common.ResponseUrn.PAYMENT_STATUS_NOT_FOUND; +import iudx.data.marketplace.apiserver.exceptions.DxRuntimeException; import java.util.stream.Stream; -import static iudx.data.marketplace.common.ResponseUrn.PAYMENT_STATUS_NOT_FOUND; - public enum PaymentStatus { PENDING("PENDING"), SUCCESSFUL("SUCCEEDED"), diff --git a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java index 730041fc..317cb2e9 100644 --- a/src/main/java/iudx/data/marketplace/policies/GetPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/GetPolicy.java @@ -16,14 +16,13 @@ import org.slf4j.LoggerFactory; public class GetPolicy { - public static final String FAILURE_MESSAGE = "Policy could not be fetched"; - private static final Logger LOG = LoggerFactory.getLogger(GetPolicy.class); - private final PostgresService postgresService; + public static final String FAILURE_MESSAGE = "Policy could not be fetched"; + private static final Logger LOG = LoggerFactory.getLogger(GetPolicy.class); + private final PostgresService postgresService; public GetPolicy(PostgresService postgresService) { this.postgresService = postgresService; -} - + } public Future initiateGetPolicy(User user) { Role role = user.getUserRole(); @@ -58,9 +57,9 @@ public Future getProviderPolicy(User provider, String query) { String resourceServerUrl = provider.getResourceServerUrl(); LOG.trace(provider.toString()); - String finalQuery = query.replace("$1", "'" + ownerIdValue + "'") - .replace("$2", "'" + resourceServerUrl + "'"); -// Tuple tuple = Tuple.of(ownerIdValue, resourceServerUrl); + String finalQuery = + query.replace("$1", "'" + ownerIdValue + "'").replace("$2", "'" + resourceServerUrl + "'"); + // Tuple tuple = Tuple.of(ownerIdValue, resourceServerUrl); JsonObject jsonObject = new JsonObject() .put("email", provider.getEmailId()) @@ -99,7 +98,7 @@ public Future getConsumerPolicy(User consumer, String query) { String emailId = consumer.getEmailId(); String resourceServerUrl = consumer.getResourceServerUrl(); LOG.trace(consumer.toString()); -// Tuple tuple = Tuple.of("consumer@gmail.com", resourceServerUrl); + // Tuple tuple = Tuple.of("consumer@gmail.com", resourceServerUrl); JsonObject jsonObject = new JsonObject() .put("email", emailId) @@ -111,7 +110,8 @@ public Future getConsumerPolicy(User consumer, String query) { .put("id", consumer.getUserId()); JsonObject consumerInfo = new JsonObject().put("consumer", jsonObject); - String finalQuery = query + String finalQuery = + query .replace("$1", "'" + consumer.getEmailId() + "'") .replace("$2", "'" + resourceServerUrl + "'"); this.executeGetPolicy(finalQuery, consumerInfo, Role.CONSUMER) @@ -135,47 +135,44 @@ public Future getConsumerPolicy(User consumer, String query) { * @param information Information to be added in the response * @return the response as Future JsonObject type */ - private Future executeGetPolicy( - String query, JsonObject information, Role role) { + private Future executeGetPolicy(String query, JsonObject information, Role role) { Promise promise = Promise.promise(); - postgresService - .executeQuery(query, handler -> { - if(handler.succeeded()) - { + postgresService.executeQuery( + query, + handler -> { + if (handler.succeeded()) { boolean isResultFromDbEmpty = handler.result().getJsonArray(RESULTS).isEmpty(); if (!isResultFromDbEmpty) { - for(int i = 0; i < handler.result().getJsonArray(RESULTS).size() ; i++) - { + for (int i = 0; i < handler.result().getJsonArray(RESULTS).size(); i++) { JsonObject jsonObject = handler.result().getJsonArray(RESULTS).getJsonObject(i); jsonObject.mergeIn(information).mergeIn(getInformation(jsonObject, role)); } JsonObject response = - new JsonObject() - .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) - .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) - .put(RESULT, handler.result().getJsonArray(RESULTS)); + new JsonObject() + .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) + .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) + .put(RESULT, handler.result().getJsonArray(RESULTS)); promise.complete( - new JsonObject() - .put(RESULT, response) - .put(STATUS_CODE, HttpStatusCode.SUCCESS.getValue())); + new JsonObject() + .put(RESULT, response) + .put(STATUS_CODE, HttpStatusCode.SUCCESS.getValue())); } else { JsonObject response = - new JsonObject() - .put(TYPE, HttpStatusCode.NOT_FOUND.getValue()) - .put(TITLE, ResponseUrn.RESOURCE_NOT_FOUND_URN.getUrn()) - .put(DETAIL, "Policy Not found"); + new JsonObject() + .put(TYPE, HttpStatusCode.NOT_FOUND.getValue()) + .put(TITLE, ResponseUrn.RESOURCE_NOT_FOUND_URN.getUrn()) + .put(DETAIL, "Policy Not found"); LOG.error("No policy found!"); promise.fail(response.encode()); } - }else - { + } else { LOG.error("Failed : " + handler.cause()); JsonObject failureMessage = - new JsonObject() - .put(TYPE, HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) - .put(TITLE, ResponseUrn.DB_ERROR_URN.getUrn()) - .put(DETAIL, FAILURE_MESSAGE + ", Failure while executing query"); + new JsonObject() + .put(TYPE, HttpStatusCode.INTERNAL_SERVER_ERROR.getValue()) + .put(TITLE, ResponseUrn.DB_ERROR_URN.getUrn()) + .put(DETAIL, FAILURE_MESSAGE + ", Failure while executing query"); promise.fail(failureMessage.encode()); } }); diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java index 3d5991ad..addec458 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresService.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresService.java @@ -8,7 +8,6 @@ import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; - import java.util.List; /** diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java index 459d20b0..a31d7b17 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java @@ -1,5 +1,8 @@ package iudx.data.marketplace.postgres; +import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; +import static iudx.data.marketplace.apiserver.util.Constants.STATUS_CODE; + import io.vertx.core.*; import io.vertx.core.AsyncResult; import io.vertx.core.Future; @@ -14,18 +17,14 @@ import iudx.data.marketplace.common.HttpStatusCode; import iudx.data.marketplace.common.RespBuilder; import iudx.data.marketplace.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.UUID; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collector; import java.util.stream.Collectors; - -import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; -import static iudx.data.marketplace.apiserver.util.Constants.STATUS_CODE; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class PostgresServiceImpl implements PostgresService { private static final Logger LOGGER = LogManager.getLogger(PostgresServiceImpl.class); diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java b/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java index 7dc0d799..2c84ea1d 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresVerticle.java @@ -21,7 +21,7 @@ public class PostgresVerticle extends AbstractVerticle { private PoolOptions poolOptions; private PgPool pool; - private String databaseIP; + private String databaseIp; private int databasePort; private String databaseName; private String databaseUserName; @@ -33,7 +33,7 @@ public class PostgresVerticle extends AbstractVerticle { @Override public void start() throws Exception { - databaseIP = config().getString("databaseIP"); + databaseIp = config().getString("databaseIP"); databasePort = config().getInteger("databasePort"); databaseName = config().getString("databaseName"); databaseUserName = config().getString("databaseUserName"); @@ -43,7 +43,7 @@ public void start() throws Exception { this.connectOptions = new PgConnectOptions() .setPort(databasePort) - .setHost(databaseIP) + .setHost(databaseIp) .setDatabase(databaseName) .setUser(databaseUserName) .setPassword(databasePassword) diff --git a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java index 2a30dd2a..6ed2993b 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java @@ -79,16 +79,16 @@ public ProductService createProduct( User user, JsonObject request, Handler> handler) { JsonArray resourceDetails = new JsonArray(); - String providerID = user.getUserId(); - String productID = - URN_PREFIX.concat(providerID).concat(":").concat(request.getString(PRODUCT_ID)); + String providerId = user.getUserId(); + String productId = + URN_PREFIX.concat(providerId).concat(":").concat(request.getString(PRODUCT_ID)); /* Check Merchant Account Existence on RazorPay */ checkMerchantAccountStatus(user) .compose( merchantAccountStatus -> { List itemFutures = - fetchItemDetailsFromCat(request, providerID, productID, resourceDetails); + fetchItemDetailsFromCat(request, providerId, productId, resourceDetails); return CompositeFuture.all(itemFutures); }) @@ -108,7 +108,7 @@ public ProductService createProduct( if (!sameProviderForAll) { return Future.failedFuture("The resources listed belong to different providers"); } else { - return checkIfProductExists(providerID, productID); + return checkIfProductExists(providerId, productId); } }) /* Check if product already exists */ @@ -128,7 +128,7 @@ public ProductService createProduct( if (!completeHandler .result() .getString("ownerUserId") - .equalsIgnoreCase(providerID)) { + .equalsIgnoreCase(providerId)) { handler.handle( Future.failedFuture( @@ -155,7 +155,7 @@ public ProductService createProduct( new RespBuilder() .withType(ResponseUrn.SUCCESS_URN.getUrn()) .withTitle(ResponseUrn.SUCCESS_URN.getMessage()) - .withResult(new JsonObject().put(PRODUCT_ID, productID)) + .withResult(new JsonObject().put(PRODUCT_ID, productId)) .withDetail("Product created successfully") .getJsonResponse(); handler.handle(Future.succeededFuture(result)); @@ -193,8 +193,8 @@ public ProductService createProduct( } private List fetchItemDetailsFromCat( - JsonObject request, String providerID, String productID, JsonArray resourceDetails) { - request.put(PROVIDER_ID, providerID).put(PRODUCT_ID, productID); + JsonObject request, String providerId, String productID, JsonArray resourceDetails) { + request.put(PROVIDER_ID, providerId).put(PRODUCT_ID, productID); JsonArray resourceIds = request.getJsonArray(RESOURCE_IDS); @@ -216,14 +216,14 @@ private List fetchItemDetailsFromCat( return itemFutures; } - Future checkIfProductExists(String providerID, String productID) { + Future checkIfProductExists(String providerId, String productId) { Promise promise = Promise.promise(); StringBuilder query = new StringBuilder( SELECT_PRODUCT_QUERY .replace("$0", productTableName) - .replace("$1", providerID) - .replace("$2", productID)); + .replace("$1", providerId) + .replace("$2", productId)); LOGGER.debug("checkQuery: {}", query); pgService.executeCountQuery( @@ -247,15 +247,15 @@ Future checkIfProductExists(String providerID, String productID) { public ProductService deleteProduct( User user, JsonObject request, Handler> handler) { - String providerID = user.getUserId(); - String productID = request.getString(PRODUCT_ID); + String providerId = user.getUserId(); + String productId = request.getString(PRODUCT_ID); JsonObject params = - new JsonObject().put(STATUS, Status.INACTIVE.toString()).put(PRODUCT_ID, productID); + new JsonObject().put(STATUS, Status.INACTIVE.toString()).put(PRODUCT_ID, productId); JsonObject deleteProductVariantParams = - new JsonObject().put(PRODUCT_ID, productID).put(PROVIDER_ID, providerID); + new JsonObject().put(PRODUCT_ID, productId).put(PROVIDER_ID, providerId); - checkIfProductExists(providerID, productID) + checkIfProductExists(providerId, productId) .onComplete( existsHandler -> { LOGGER.error(existsHandler.result()); @@ -329,12 +329,12 @@ public ProductService deleteProduct( public ProductService listProducts( User user, JsonObject request, Handler> handler) { - String providerID = user.getUserId(); + String providerId = user.getUserId(); String resourceServerUrl = user.getResourceServerUrl(); JsonObject params = new JsonObject() .put(STATUS, Status.ACTIVE.toString()) - .put(PROVIDER_ID, providerID) + .put(PROVIDER_ID, providerId) .put("resourceServerUrl", resourceServerUrl); if (request.containsKey("resourceId")) { diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index 5b152e00..e11cc97c 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -30,7 +30,7 @@ public QueryBuilder(JsonArray tables) { } public List buildCreateProductQueries(JsonObject request, JsonArray resourceDetails) { - String productID = request.getString(PRODUCT_ID); + String productId = request.getString(PRODUCT_ID); String providerID = request.getString(PROVIDER_ID); String providerName = request.getString(PROVIDER_NAME); List queries = new ArrayList(); @@ -40,7 +40,7 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso new StringBuilder( INSERT_PRODUCT_QUERY .replace("$0", productTable) - .replace("$1", productID) + .replace("$1", productId) .replace("$2", providerID) .replace("$3", providerName) .replace("$4", Status.ACTIVE.toString())) @@ -66,7 +66,7 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso new StringBuilder( INSERT_P_R_REL_QUERY .replace("$0", productResourceRelationTable) - .replace("$1", productID) + .replace("$1", productId) .replace("$2", ((JsonObject) resource).getString(RESOURCE_ID))) .toString()); }); @@ -93,14 +93,14 @@ public String buildListProductsQuery(JsonObject request) { return query.toString(); } - public String buildProductDetailsQuery(String productID, String providerId) { + public String buildProductDetailsQuery(String productId, String providerId) { StringBuilder query = new StringBuilder( SELECT_PRODUCT_DETAILS .replace("$0", productTable) .replace("$9", productResourceRelationTable) .replace("$8", resourceTable) - .replace("$1", productID) + .replace("$1", productId) .replace("$2", providerId)); return query.toString(); @@ -131,12 +131,12 @@ public String buildCreateProductVariantQuery(JsonObject request) { return query.toString(); } - public String updateProductVariantStatusQuery(String productID, String variant) { + public String updateProductVariantStatusQuery(String productId, String variant) { StringBuilder query = new StringBuilder( UPDATE_PV_STATUS .replace("$0", productVariantTable) - .replace("$1", productID) + .replace("$1", productId) .replace("$2", variant) .replace("$3", Status.ACTIVE.toString()) .replace("$4", Status.INACTIVE.toString())); @@ -171,12 +171,12 @@ public String updateProductVariantStatusQuery(String productVariantId) { return query.toString(); } - public String selectProductVariant(String productID, String variantName) { + public String selectProductVariant(String productId, String variantName) { StringBuilder query = new StringBuilder( SELECT_PV_QUERY .replace("$0", productVariantTable) - .replace("$1", productID) + .replace("$1", productId) .replace("$2", variantName) .replace("$3", Status.ACTIVE.toString())); LOGGER.debug("select product variant query : {}", query); diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java index 49c515f0..5420a6c6 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java @@ -40,18 +40,18 @@ public ProductVariantServiceImpl(JsonObject config, PostgresService postgresServ @Override public ProductVariantService createProductVariant( User user, JsonObject request, Handler> handler) { - String productID = request.getString(PRODUCT_ID); + String productId = request.getString(PRODUCT_ID); String variantName = request.getString(PRODUCT_VARIANT_NAME); String providerId = user.getUserId(); - Future productDetailsFuture = getProductDetails(productID, providerId); + Future productDetailsFuture = getProductDetails(productId, providerId); JsonArray resources = request.getJsonArray(RESOURCES_ARRAY); - Future checkIfProductExists = checkForExistenceOfProduct(productID, providerId); + Future checkIfProductExists = checkForExistenceOfProduct(productId, providerId); Future checkForExistence = checkIfProductExists.compose( isProductFound -> { if (isProductFound) { - return checkIfProductVariantExists(productID, variantName); + return checkIfProductVariantExists(productId, variantName); } else { String failureMessage = new RespBuilder() @@ -109,9 +109,9 @@ public ProductVariantService createProductVariant( int i, j; for (i = 0; i < resources.size(); i++) { for (j = 0; j < resResources.size(); j++) { - String reqID = resources.getJsonObject(i).getString(ID); - String resID = resResources.getJsonObject(j).getString(ID); - if (reqID.equalsIgnoreCase(resID)) { + String reqId = resources.getJsonObject(i).getString(ID); + String resId = resResources.getJsonObject(j).getString(ID); + if (reqId.equalsIgnoreCase(resId)) { resResources.getJsonObject(j).mergeIn(resources.getJsonObject(i)); break; } @@ -139,7 +139,7 @@ public ProductVariantService createProductVariant( .add( new JsonObject() .put("productVariantId", productVariantId) - .put("productId", productID) + .put("productId", productId) .put(PRODUCT_VARIANT_NAME, variantName))) .withDetail("Product Variant created successfully"); handler.handle(Future.succeededFuture(respBuilder.getJsonResponse())); @@ -154,9 +154,9 @@ public ProductVariantService createProductVariant( return this; } - private Future checkIfProductVariantExists(String productID, String variantName) { + private Future checkIfProductVariantExists(String productId, String variantName) { Promise promise = Promise.promise(); - String query = queryBuilder.selectProductVariant(productID, variantName); + String query = queryBuilder.selectProductVariant(productId, variantName); pgService.executeCountQuery( query, handler -> { @@ -170,10 +170,10 @@ private Future checkIfProductVariantExists(String productID, String var return promise.future(); } - Future getProductDetails(String productID, String providerId) { + Future getProductDetails(String productId, String providerId) { Promise promise = Promise.promise(); - String query = queryBuilder.buildProductDetailsQuery(productID, providerId); + String query = queryBuilder.buildProductDetailsQuery(productId, providerId); LOGGER.debug(query); pgService.executeQuery( query, @@ -242,10 +242,10 @@ Future checkForExistenceOfProduct(String productId, String providerId) public ProductVariantService updateProductVariant( User user, JsonObject request, Handler> handler) { - String productID = request.getString(PRODUCT_ID); + String productId = request.getString(PRODUCT_ID); String variant = request.getString(PRODUCT_VARIANT_NAME); /* check if the product variant exists */ - String query = queryBuilder.checkProductVariantExistence(productID, variant); + String query = queryBuilder.checkProductVariantExistence(productId, variant); pgService.executeQuery( query, existenceHandler -> { @@ -254,7 +254,7 @@ public ProductVariantService updateProductVariant( if (!isEmpty) { Future updateProductVariantFuture = - updateProductVariantStatus(productID, variant); + updateProductVariantStatus(productId, variant); updateProductVariantFuture.onComplete( updateHandler -> { if (updateHandler.result()) { @@ -297,9 +297,9 @@ public ProductVariantService updateProductVariant( return this; } - Future updateProductVariantStatus(String productID, String variant) { + Future updateProductVariantStatus(String productId, String variant) { Promise promise = Promise.promise(); - String query = queryBuilder.updateProductVariantStatusQuery(productID, variant); + String query = queryBuilder.updateProductVariantStatusQuery(productId, variant); pgService.executeQuery( query, diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java index e48d54b1..8234a1fa 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java @@ -36,7 +36,7 @@ static RazorPayService createProxy(Vertx vertx, String address) { * RazorPay This method also creates a payment record in the marketplace database * * @param request which is a JsonObject - * @retun Future which is a vertx Future + * @retun Future JsonObject which is a vertx Future */ Future verifyPayment(JsonObject request); diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java index 37cacdea..8a28527f 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java @@ -264,7 +264,9 @@ public Future fetchProductConfiguration(JsonObject request) { } else { LOGGER.error("Linked account not activated"); String detail = - "To activate linked account please complete the KYC, filling account information etc., in your Razorpay merchant dashboard"; + "To activate linked account please complete the KYC, filling account information etc., " + + + "in your Razorpay merchant dashboard"; promise.fail(detail); } } catch (RazorpayException e) { diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java index 4b8d71ba..ed3f8823 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookService.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookService.java @@ -25,13 +25,13 @@ static WebhookService createProxy(Vertx vertx, String address) { /** * @param orderId which is a String generated from Razorpay - * @return Future which is a vertx Future + * @return Future JsonObject which is a vertx Future */ Future recordOrderPaid(String orderId); /** * @param orderId which is a String generated from Razorpay - * @return Future which is a vertx Future + * @return Future Void which is a vertx Future */ Future recordPaymentFailure(String orderId); } From bc1fe674bd1828c3d51ca1a5515005fbc2eb5155 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 12:21:05 +0530 Subject: [PATCH 04/15] Refactor: update exlusion Updated exclusions for pmd, checkstyle in pom and jenkinsfile --- Jenkinsfile | 2 +- pom.xml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 877c4671..b6a1cc93 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -43,7 +43,7 @@ pipeline { thresholds: [ skipped(failureThreshold: '0'), failed(failureThreshold: '40') ], tools: [ JUnit(pattern: 'target/surefire-reports/*.xml') ] ) - jacoco classPattern: 'target/classes', execPattern: 'target/jacoco.exec', sourcePattern: 'src/main/java', exclusionPattern:'iudx/data/marketplace/apiserver/ApiServerVerticle.class, **/*VertxEBProxy.class, **/*Constants.class, **/*VertxProxyHandler.class, **/*Verticle.class, **/JwtDataConverter.class, iudx/data/marketplace/apiserver/ProviderApis.class, iudx/data/marketplace/apiserver/ConsumerApis.class,iudx/data/marketplace/deploy/*.class, **/*Service.class, **/PolicyServiceImpl.class' + jacoco classPattern: 'target/classes', execPattern: 'target/jacoco.exec', sourcePattern: 'src/main/java', exclusionPattern:'iudx/data/marketplace/apiserver/ApiServerVerticle.class, **/*VertxEBProxy.class, **/*Constants.class, **/*VertxProxyHandler.class, **/*Verticle.class, **/JwtDataConverter.class, iudx/data/marketplace/apiserver/ProviderApis.class, iudx/data/marketplace/apiserver/ConsumerApis.class,iudx/data/marketplace/deploy/*.class, **/*Service.class, **/PolicyServiceImpl.class, **/package-info.class' recordIssues( enabledForFailure: true, diff --git a/pom.xml b/pom.xml index 8efff516..7a2b7214 100644 --- a/pom.xml +++ b/pom.xml @@ -327,6 +327,8 @@ **/*Service.class + + **/package-info.class iudx/data/marketplace/policies/PolicyServiceImpl.class From d82ce20452b892775c30435a2f2253717ed14a16 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 12:36:24 +0530 Subject: [PATCH 05/15] Refactor: update plugin --- pom.xml | 48 ++++++++++++++++-------------------------------- 1 file changed, 16 insertions(+), 32 deletions(-) diff --git a/pom.xml b/pom.xml index 7a2b7214..180adef3 100644 --- a/pom.xml +++ b/pom.xml @@ -272,6 +272,22 @@ flyway-maven-plugin 8.5.13 + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + ${openjdk.version} + + ./iudx-pmd-ruleset.xml + + true + + + target/generated-sources + + + org.jacoco jacoco-maven-plugin @@ -492,22 +508,6 @@ - - org.apache.maven.plugins - maven-pmd-plugin - ${maven-pmd-plugin.version} - - ${openjdk.version} - - ./iudx-pmd-ruleset.xml - - true - - - target/generated-sources - - - org.apache.maven.plugins maven-checkstyle-plugin @@ -540,22 +540,6 @@ - - org.apache.maven.plugins - maven-pmd-plugin - ${maven-pmd-plugin.version} - - ${openjdk.version} - - ./iudx-pmd-ruleset.xml - - true - - - target/generated-sources - - - From 2ca6fbcde062311d0920ab9ce48222b971b03910 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 12:49:19 +0530 Subject: [PATCH 06/15] Refactor: update plugin --- pom.xml | 21 +++++++++++++++++++ .../apiserver/ApiServerVerticle.java | 5 ----- .../linkedAccount/CreateLinkedAccount.java | 4 ++-- .../types/JsonSchemaTypeValidator.java | 10 ++++----- 4 files changed, 28 insertions(+), 12 deletions(-) diff --git a/pom.xml b/pom.xml index 180adef3..fc7f03a2 100644 --- a/pom.xml +++ b/pom.xml @@ -288,6 +288,27 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin-google.version} + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + + true + UTF-8 + ./google_checks.xml + + ${project.build.sourceDirectory} + + + org.jacoco jacoco-maven-plugin diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index fb08b6f1..21b6e2a4 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -63,7 +63,6 @@ public class ApiServerVerticle extends AbstractVerticle { private WebClientOptions webClientOptions; private AuthenticationService authenticationService; private LinkedAccountService linkedAccountService; - private AuditingService auditingService; private WebhookService webhookService; /** @@ -329,7 +328,6 @@ private void handleWebhookSignatureValidation(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); HttpServerRequest request = routingContext.request(); - HttpServerResponse response = routingContext.response(); String xRazorpaySignature = request.headers().get(HEADER_X_RAZORPAY_SIGNATURE); razorPayService @@ -349,7 +347,6 @@ private void handleWebhookSignatureValidation(RoutingContext routingContext) { private void paymentFailedRequestHandler(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); - HttpServerRequest request = routingContext.request(); HttpServerResponse response = routingContext.response(); LOGGER.debug(requestBody); @@ -374,7 +371,6 @@ private void paymentFailedRequestHandler(RoutingContext routingContext) { private void paymentAuthorizedRequestHandler(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); - HttpServerRequest request = routingContext.request(); HttpServerResponse response = routingContext.response(); LOGGER.debug(requestBody); @@ -385,7 +381,6 @@ private void paymentAuthorizedRequestHandler(RoutingContext routingContext) { private void orderPaidRequestHandler(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); - HttpServerRequest request = routingContext.request(); HttpServerResponse response = routingContext.response(); String orderId = diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index cb658d82..4fa4510f 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -80,8 +80,8 @@ public Future initiateCreatingLinkedAccount(JsonObject request, User /* send the information for auditing */ /* audit info = Ids generated by Razorpay + Necessary information (Non-sensitive PII) */ - Future auditingFuture = - userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); +// Future auditingFuture = +// userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); return userResponse; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java index 32eed0d0..49473ee6 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -63,11 +63,11 @@ private boolean validateJson(JsonObject body, RequestType requestType) LOGGER.debug(schemaPath); final JsonSchema schema; - try { - final JsonNode sc = loadResource(schemaPath); - } catch (Exception e) { - LOGGER.error("Validation Error {}", e.getMessage()); - } +// try { +// final JsonNode sc = loadResource(schemaPath); +// } catch (Exception e) { +// LOGGER.error("Validation Error {}", e.getMessage()); +// } final JsonNode schemaNode = loadResource(schemaPath); LOGGER.debug(schemaNode.asText()); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); From 212c73278cb9cc15c9cf25064bd20dd1b11ab06a Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 12:57:29 +0530 Subject: [PATCH 07/15] Refactor: update CreateLinkedAccount --- .../apiserver/provider/linkedAccount/CreateLinkedAccount.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index 4fa4510f..c03f0685 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -81,7 +81,7 @@ public Future initiateCreatingLinkedAccount(JsonObject request, User /* send the information for auditing */ /* audit info = Ids generated by Razorpay + Necessary information (Non-sensitive PII) */ // Future auditingFuture = -// userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); + userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); return userResponse; } From 68c3d0ca7399dd23d93501aeec2361af8520e937 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 13:37:22 +0530 Subject: [PATCH 08/15] Refactor: Add pmd,checkstyle ruleset Added pmd, checkstyle ruleset for the pipeline --- docker-compose.test.yml | 3 ++- docker/depl.dockerfile | 2 ++ docker/dev.dockerfile | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docker-compose.test.yml b/docker-compose.test.yml index ca3c66eb..03531fcc 100644 --- a/docker-compose.test.yml +++ b/docker-compose.test.yml @@ -12,7 +12,8 @@ services: - /home/ubuntu/configs/dmp-apd-server-config.json:/usr/share/app/configs/dmp-apd-server.json - /home/ubuntu/configs/dmp-apd-server-keystore.jks:/usr/share/app/configs/keystore.jks - dmp-apd-server-volume:/usr/share/app/storage/temp-dir - depends_on: + - ./iudx-pmd-ruleset.xml:/usr/share/app/iudx-pmd-ruleset.xml + - ./google_checks.xml:/usr/share/app/google_checks.xml - zookeeper ports: - "8080:8080" diff --git a/docker/depl.dockerfile b/docker/depl.dockerfile index 5a42970e..97ee613d 100644 --- a/docker/depl.dockerfile +++ b/docker/depl.dockerfile @@ -20,6 +20,8 @@ ENV JAR="iudx.data.marketplace-cluster-${VERSION}-fat.jar" WORKDIR /usr/share/app # Copying openapi docs COPY docs docs +COPY iudx-pmd-ruleset.xml iudx-pmd-ruleset.xml +COPY google_checks.xml google_checks.xml # Copying dev fatjar from builder stage to final image COPY --from=builder /usr/share/app/target/${JAR} ./fatjar.jar EXPOSE 8080 8443 diff --git a/docker/dev.dockerfile b/docker/dev.dockerfile index 6397049c..f2db65ca 100644 --- a/docker/dev.dockerfile +++ b/docker/dev.dockerfile @@ -20,6 +20,8 @@ ENV JAR="iudx.data.marketplace-dev-${VERSION}-fat.jar" WORKDIR /usr/share/app # Copying openapi docs COPY docs docs +COPY iudx-pmd-ruleset.xml iudx-pmd-ruleset.xml +COPY google_checks.xml google_checks.xml # Copying dev fatjar from builder stage to final image COPY --from=builder /usr/share/app/target/${JAR} ./fatjar.jar EXPOSE 8080 8443 From 3e80c5852bbd82646f14105af00eeafb0b655dde Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 13:42:39 +0530 Subject: [PATCH 09/15] Refactor: update docker-compose.test.yml --- docker-compose.test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docker-compose.test.yml b/docker-compose.test.yml index 03531fcc..40777e23 100644 --- a/docker-compose.test.yml +++ b/docker-compose.test.yml @@ -12,9 +12,10 @@ services: - /home/ubuntu/configs/dmp-apd-server-config.json:/usr/share/app/configs/dmp-apd-server.json - /home/ubuntu/configs/dmp-apd-server-keystore.jks:/usr/share/app/configs/keystore.jks - dmp-apd-server-volume:/usr/share/app/storage/temp-dir + - zookeeper - ./iudx-pmd-ruleset.xml:/usr/share/app/iudx-pmd-ruleset.xml - ./google_checks.xml:/usr/share/app/google_checks.xml - - zookeeper + ports: - "8080:8080" restart: on-failure From bf9ad8355390711cc56c0447d3a9b26eb2cf1acd Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 13:49:11 +0530 Subject: [PATCH 10/15] Refactor: update docker-compose.test.yml --- docker-compose.test.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docker-compose.test.yml b/docker-compose.test.yml index 40777e23..91170c2d 100644 --- a/docker-compose.test.yml +++ b/docker-compose.test.yml @@ -12,10 +12,10 @@ services: - /home/ubuntu/configs/dmp-apd-server-config.json:/usr/share/app/configs/dmp-apd-server.json - /home/ubuntu/configs/dmp-apd-server-keystore.jks:/usr/share/app/configs/keystore.jks - dmp-apd-server-volume:/usr/share/app/storage/temp-dir - - zookeeper - ./iudx-pmd-ruleset.xml:/usr/share/app/iudx-pmd-ruleset.xml - ./google_checks.xml:/usr/share/app/google_checks.xml - + depends_on: + - zookeeper ports: - "8080:8080" restart: on-failure @@ -36,4 +36,4 @@ services: - dmp-apd-server-net volumes: - dmp-apd-server-volume: + dmp-apd-server-volume: \ No newline at end of file From 49fdd2e7b9c0a0047dda85a0b4f0b8abdcc5cbf9 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 15:44:25 +0530 Subject: [PATCH 11/15] Test: resolve pmd issues --- .../apiserver/ApiServerVerticle.java | 27 +++++++++---------- .../marketplace/apiserver/ConsumerApis.java | 10 +++---- .../marketplace/apiserver/ProviderApis.java | 12 ++++----- .../apiserver/handlers/ValidationHandler.java | 5 +--- .../LinkedAccountServiceImpl.java | 2 +- .../linkedAccount/LinkedAccountVerticle.java | 2 +- .../apiserver/util/RequestType.java | 2 +- .../validation/ValidationHandlerFactory.java | 8 +++--- .../AuthenticationServiceImpl.java | 2 +- .../authenticator/AuthenticationVerticle.java | 5 ++-- .../authorization/JwtAuthorization.java | 2 +- .../marketplace/common/CatalogueService.java | 2 -- .../consumer/ConsumerServiceImpl.java | 4 +-- .../marketplace/policies/CreatePolicy.java | 2 +- .../marketplace/policies/DeletePolicy.java | 3 +-- .../marketplace/policies/PolicyVerticle.java | 2 -- .../marketplace/policies/VerifyPolicy.java | 2 +- .../product/util/QueryBuilder.java | 5 ++-- .../variant/ProductVariantServiceImpl.java | 2 +- .../razorpay/RazorPayServiceImpl.java | 4 +-- .../marketplace/webhook/WebhookVerticle.java | 3 +-- .../handlers/ValidationHandlerTest.java | 2 +- .../authenticator/AuthServiceTest.java | 4 +-- 23 files changed, 51 insertions(+), 61 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index 21b6e2a4..5badc030 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -22,7 +22,6 @@ import iudx.data.marketplace.apiserver.handlers.ValidationHandler; import iudx.data.marketplace.apiserver.provider.linkedAccount.LinkedAccountService; import iudx.data.marketplace.apiserver.util.RequestType; -import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.authenticator.AuthClient; import iudx.data.marketplace.authenticator.AuthenticationService; import iudx.data.marketplace.common.*; @@ -178,12 +177,12 @@ public void start() throws Exception { ExceptionHandler exceptionHandler = new ExceptionHandler(); ValidationHandler checkPolicyValidationHandler = - new ValidationHandler(vertx, RequestType.CHECK_POLICY); - ValidationHandler verifyValidationHandler = new ValidationHandler(vertx, RequestType.VERIFY); + new ValidationHandler(RequestType.CHECK_POLICY); + ValidationHandler verifyValidationHandler = new ValidationHandler(RequestType.VERIFY); ValidationHandler postLinkedAccountHandler = - new ValidationHandler(vertx, RequestType.POST_ACCOUNT); + new ValidationHandler(RequestType.POST_ACCOUNT); ValidationHandler putLinkedAccountHandler = - new ValidationHandler(vertx, RequestType.PUT_ACCOUNT); + new ValidationHandler(RequestType.PUT_ACCOUNT); router .get(api.getPoliciesUrl()) @@ -191,10 +190,10 @@ public void start() throws Exception { .handler(this::getPoliciesHandler) .failureHandler(exceptionHandler); - router - .post(api.getProductUserMapsPath()) - .handler(this::mapUserToProduct) - .failureHandler(exceptionHandler); +// router +// .post(api.getProductUserMapsPath()) +// .handler(this::mapUserToProduct) +// .failureHandler(exceptionHandler); router .post(api.getVerifyUrl()) @@ -204,7 +203,7 @@ public void start() throws Exception { .failureHandler(exceptionHandler); ValidationHandler verifyPaymentValidationHandler = - new ValidationHandler(vertx, RequestType.VERIFY_PAYMENT); + new ValidationHandler(RequestType.VERIFY_PAYMENT); router .post(api.getVerifyPaymentApi()) .handler(verifyPaymentValidationHandler) @@ -242,7 +241,7 @@ public void start() throws Exception { /*Webhook routes */ ValidationHandler orderPaidRequestValidationHandler = - new ValidationHandler(vertx, RequestType.ORDER_PAID_WEBHOOK); + new ValidationHandler(RequestType.ORDER_PAID_WEBHOOK); router .post("/order-paid-webhooks") .handler(this::handleWebhookSignatureValidation) @@ -251,7 +250,7 @@ public void start() throws Exception { .failureHandler(exceptionHandler); ValidationHandler paymentAuthorizedRequestValidationHandler = - new ValidationHandler(vertx, RequestType.PAYMENT_AUTHORIZED_WEBHOOK); + new ValidationHandler(RequestType.PAYMENT_AUTHORIZED_WEBHOOK); router .post("/payment-authorized") .handler(this::handleWebhookSignatureValidation) @@ -259,7 +258,7 @@ public void start() throws Exception { .handler(this::paymentAuthorizedRequestHandler); ValidationHandler paymentFailedRequestValidationHandler = - new ValidationHandler(vertx, RequestType.PAYMENT_FAILED_WEBHOOK); + new ValidationHandler(RequestType.PAYMENT_FAILED_WEBHOOK); router .post("/payments-failed") .handler(this::handleWebhookSignatureValidation) @@ -444,7 +443,7 @@ private void getPoliciesHandler(RoutingContext routingContext) { }); } - private void mapUserToProduct(RoutingContext routingContext) {} +// private void mapUserToProduct(RoutingContext routingContext) {} private void handlePostLinkedAccount(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java index eb3c41cb..efebccd2 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java @@ -60,14 +60,14 @@ public class ConsumerApis { Router init() { ValidationHandler resourceValidationHandler = - new ValidationHandler(vertx, RequestType.RESOURCE); + new ValidationHandler(RequestType.RESOURCE); ValidationHandler providerValidationHandler = - new ValidationHandler(vertx, RequestType.PROVIDER); - ValidationHandler orderValidationHandler = new ValidationHandler(vertx, RequestType.ORDER); + new ValidationHandler(RequestType.PROVIDER); + ValidationHandler orderValidationHandler = new ValidationHandler(RequestType.ORDER); ValidationHandler purchaseValidationHandler = - new ValidationHandler(vertx, RequestType.PURCHASE); + new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); - ValidationHandler productVariantHandler = new ValidationHandler(vertx, RequestType.PRODUCT); + ValidationHandler productVariantHandler = new ValidationHandler(RequestType.PRODUCT); consumerService = ConsumerService.createProxy(vertx, CONSUMER_SERVICE_ADDRESS); diff --git a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java index e7a717de..f0faec5d 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java @@ -63,17 +63,17 @@ public class ProviderApis { Router init() { - ValidationHandler productValidationHandler = new ValidationHandler(vertx, RequestType.PRODUCT); + ValidationHandler productValidationHandler = new ValidationHandler(RequestType.PRODUCT); ValidationHandler variantValidationHandler = - new ValidationHandler(vertx, RequestType.PRODUCT_VARIANT); + new ValidationHandler(RequestType.PRODUCT_VARIANT); ValidationHandler deleteVariantValidationHandler = - new ValidationHandler(vertx, RequestType.DELETE_PRODUCT_VARIANT); + new ValidationHandler(RequestType.DELETE_PRODUCT_VARIANT); ValidationHandler listVariantValidationHandler = - new ValidationHandler(vertx, RequestType.LIST_PRODUCT_VARIANT); + new ValidationHandler(RequestType.LIST_PRODUCT_VARIANT); ValidationHandler resourceValidationHandler = - new ValidationHandler(vertx, RequestType.RESOURCE); + new ValidationHandler(RequestType.RESOURCE); ValidationHandler purchaseValidationHandler = - new ValidationHandler(vertx, RequestType.PURCHASE); + new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); productService = ProductService.createProxy(vertx, PRODUCT_SERVICE_ADDRESS); diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java index e931b214..4498d886 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ValidationHandler.java @@ -2,7 +2,6 @@ import io.vertx.core.Handler; import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import iudx.data.marketplace.apiserver.util.RequestType; @@ -20,10 +19,8 @@ public class ValidationHandler implements Handler { private static final Logger LOGGER = LogManager.getLogger(ValidationHandler.class); private RequestType requestType; - private Vertx vertx; - public ValidationHandler(Vertx vertx, RequestType requestType) { - this.vertx = vertx; + public ValidationHandler(RequestType requestType) { this.requestType = requestType; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java index 33a00c9d..4f82765c 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; public class LinkedAccountServiceImpl implements LinkedAccountService { - private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountServiceImpl.class); +// private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountServiceImpl.class); private final CreateLinkedAccount createLinkedAccount; private final FetchLinkedAccount fetchLinkedAccount; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java index 68491c27..49ad5434 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java @@ -13,7 +13,7 @@ import org.apache.logging.log4j.Logger; public class LinkedAccountVerticle extends AbstractVerticle { - private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); +// private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); private PostgresService postgresService; private LinkedAccountServiceImpl linkedAccountService; diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java index 25f3813b..28ad04e6 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java @@ -25,7 +25,7 @@ public enum RequestType { private String filename; - private RequestType(String filename) { + RequestType(String filename) { this.filename = filename; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java index ba9c303b..fe8d0072 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java @@ -28,7 +28,7 @@ public List build( validator = getProductVariantValidators(parameters, body, requestType); break; case DELETE_PRODUCT_VARIANT: - validator = getDeleteProductVariantValidators(parameters, requestType); + validator = getDeleteProductVariantValidators(parameters); break; case LIST_PRODUCT_VARIANT: validator = listProductVariantValidators(parameters); @@ -43,7 +43,7 @@ public List build( validator = getPolicyValidators(body); break; case VERIFY: - validator = getVerifyPolicyValidator(parameters, body); + validator = getVerifyPolicyValidator(body); break; case ORDER: validator = getOrderValidator(parameters); @@ -127,7 +127,7 @@ private List getOrderValidator(MultiMap parameters) { return validators; } - private List getVerifyPolicyValidator(MultiMap parameters, JsonObject body) { + private List getVerifyPolicyValidator(JsonObject body) { List validators = new ArrayList<>(); validators.add(new JsonSchemaTypeValidator(body, RequestType.VERIFY)); return validators; @@ -181,7 +181,7 @@ private List getProductVariantValidators( } private List getDeleteProductVariantValidators( - final MultiMap parameters, final RequestType requestType) { + final MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get(PRODUCT_VARIANT_ID), true)); return validators; diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java index 75dfaa23..8254da3c 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java @@ -30,7 +30,7 @@ public class AuthenticationServiceImpl implements AuthenticationService { final Api apis; public AuthenticationServiceImpl( - Vertx vertx, final JWTAuth jwtAuth, final JsonObject config, final Api apis) { + final JWTAuth jwtAuth, final JsonObject config, final Api apis) { this.jwtAuth = jwtAuth; this.issuer = config.getString("issuer"); this.apdUrl = config.getString(APD_URL); diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java index 81fdeb9c..d08d18ff 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java @@ -24,7 +24,6 @@ public class AuthenticationVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(AuthenticationVerticle.class); private AuthenticationService authenticationService; - private CatalogueService catalogueService; private ServiceBinder binder; private MessageConsumer consumer; private WebClient webClient; @@ -76,9 +75,9 @@ public void start() throws Exception { } JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); - catalogueService = new CatalogueService(vertx, config()); +// CatalogueService catalogueService = new CatalogueService(vertx, config()); api = Api.getInstance(config().getString("dxApiBasePath")); - authenticationService = new AuthenticationServiceImpl(vertx, jwtAuth, config(), api); + authenticationService = new AuthenticationServiceImpl(jwtAuth, config(), api); /* Publish the Authentication service with the Event Bus against an address. */ consumer = diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java index 5753f174..29a3eabb 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java @@ -6,7 +6,7 @@ public class JwtAuthorization { - private static final Logger LOGGER = LogManager.getLogger(JwtAuthorization.class); +// private static final Logger LOGGER = LogManager.getLogger(JwtAuthorization.class); private final AuthorizationStatergy authStrategy; diff --git a/src/main/java/iudx/data/marketplace/common/CatalogueService.java b/src/main/java/iudx/data/marketplace/common/CatalogueService.java index 04031f42..27c9cce8 100644 --- a/src/main/java/iudx/data/marketplace/common/CatalogueService.java +++ b/src/main/java/iudx/data/marketplace/common/CatalogueService.java @@ -27,10 +27,8 @@ public class CatalogueService { private static String catHost; private static int catPort; private static String catItemPath, catRelPath; - private Vertx vertx; public CatalogueService(Vertx vertx, JsonObject config) { - this.vertx = vertx; catHost = config.getString(CAT_SERVER_HOST); catPort = config.getInteger(CAT_SERVER_PORT); catItemPath = config.getString(CAT_ITEM_PATH); diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java index cdfd5512..bd0c14ed 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java @@ -170,7 +170,7 @@ public ConsumerService listProducts( @Override public ConsumerService createOrder( JsonObject request, User user, Handler> handler) { - String resourceServerUrl = user.getResourceServerUrl(); +// String resourceServerUrl = user.getResourceServerUrl(); String variantId = request.getString(PRODUCT_VARIANT_ID); String consumerId = user.getUserId(); @@ -228,7 +228,7 @@ public ConsumerService listPurchase( Future paymentFuture = executePurchaseQuery(query, resourceId, productId, user); - Future userResponseFuture = +// Future userResponseFuture = paymentFuture.onComplete( pgHandler -> { if (pgHandler.succeeded()) { diff --git a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java index 5cc3ea55..1cc1478f 100644 --- a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java @@ -31,7 +31,7 @@ public class CreatePolicy { private int expiryInMonths; private String consumerEmailId; private String expiryAt; - private User provider; +// private User provider; public CreatePolicy(PostgresService postgresService, AuditingService auditingService, Api api) { this.postgresService = postgresService; diff --git a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java index f7f913e7..bb33eea5 100644 --- a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java @@ -28,7 +28,6 @@ public class DeletePolicy { private static final Logger LOG = LoggerFactory.getLogger(DeletePolicy.class); private static final String FAILURE_MESSAGE = "Policy could not be deleted"; private final PostgresService postgresService; - private PgPool pool; private AuditingService auditingService; private Api api; @@ -57,7 +56,7 @@ private String getFailureResponse(JsonObject response, String detail) { public Future executeUpdateQuery(String query, UUID policyUuid, User user) { LOG.debug("inside executeUpdateQuery"); Promise promise = Promise.promise(); - Tuple tuple = Tuple.of(policyUuid); +// Tuple tuple = Tuple.of(policyUuid); JsonObject param = new JsonObject().put("$1", policyUuid.toString()); postgresService.executePreparedQuery( diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java index 378d1373..475a55cd 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java @@ -17,14 +17,12 @@ public class PolicyVerticle extends AbstractVerticle { private CreatePolicy createPolicy; private VerifyPolicy verifyPolicy; private GetPolicy getPolicy; - private CatalogueService catalogueService; private AuditingService auditingService; private Api api; private FetchPolicyUsingPvId fetchPolicyUsingPvId; @Override public void start() { - catalogueService = new CatalogueService(vertx, config()); postgresServiceImpl = PostgresService.createProxy(vertx, POSTGRES_SERVICE_ADDRESS); auditingService = AuditingService.createProxy(vertx, AUDITING_SERVICE_ADDRESS); api = Api.getInstance(config().getString("dxApiBasePath")); diff --git a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java index d109b012..9e09cfbc 100644 --- a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java @@ -72,7 +72,7 @@ public Future initiateVerifyPolicy(JsonObject request) { private Future checkExistingPoliciesForId( UUID itemId, UUID ownerId, String userEmailId) { - Tuple selectTuples = Tuple.of(itemId, ownerId, Status.ACTIVE, userEmailId); +// Tuple selectTuples = Tuple.of(itemId, ownerId, Status.ACTIVE, userEmailId); String query; JsonObject params = diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index e11cc97c..a26c6646 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -4,6 +4,7 @@ import static iudx.data.marketplace.common.Constants.*; import static iudx.data.marketplace.consumer.util.Constants.*; import static iudx.data.marketplace.product.util.Constants.*; +import static iudx.data.marketplace.product.util.Constants.PRODUCT_VARIANT_NAME; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; @@ -121,7 +122,7 @@ public String buildCreateProductVariantQuery(JsonObject request) { .replace("$1", pvID) .replace("$2", request.getString("provider_id")) .replace("$3", request.getString(PRODUCT_ID)) - .replace("$4", request.getString(Constants.PRODUCT_VARIANT_NAME)) + .replace("$4", request.getString(PRODUCT_VARIANT_NAME)) .replace("$5", resources.encode()) .replace("$6", request.getDouble(PRICE).toString()) .replace("$7", request.getInteger(DURATION).toString()) @@ -188,7 +189,7 @@ public String listProductVariants(JsonObject request, String providerId) { StringBuilder query = new StringBuilder(FETCH_ACTIVE_PRODUCT_VARIANTS); query.append(" AND P.\"providerId\"=$3"); - if (request.containsKey(Constants.PRODUCT_VARIANT_NAME)) { + if (request.containsKey(PRODUCT_VARIANT_NAME)) { query.append(" AND P.\"productVariantName\"=$4"); } query.append(" ORDER BY P.\"updatedAt\" DESC"); diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java index 5420a6c6..89e6c530 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java @@ -446,7 +446,7 @@ public ProductVariantService listPurchase( } Future paymentFuture = executePurchaseQuery(query, resourceId, productId, user); - Future userResponseFuture = +// Future userResponseFuture = paymentFuture.onComplete( pgHandler -> { if (pgHandler.succeeded()) { diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java index 8a28527f..433b9dc2 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java @@ -47,7 +47,7 @@ public Future createOrder(JsonObject request) { Promise promise = Promise.promise(); LOGGER.debug(request); - Integer amountInPaise = (int) (Double.parseDouble((request.getString(PRICE))) * 100); + Integer amountInPaise = (int) (Double.parseDouble(request.getString(PRICE)) * 100); JSONObject orderRequest = new JSONObject() .put(AMOUNT, amountInPaise) @@ -78,7 +78,7 @@ public Future createOrder(JsonObject request) { throw new DxRuntimeException( 400, ResponseUrn.ORDER_NOT_CREATED, - ("Order creation returned with status : " + status)); + "Order creation returned with status : " + status); } JSONArray transfersArray = order.get(TRANFERS); JSONObject transferResponse = transfersArray.getJSONObject(0); diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java index 4e3e1bb2..91d4eab5 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java @@ -16,7 +16,6 @@ public class WebhookVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(WebhookVerticle.class); - private MessageConsumer consumer; private ServiceBinder binder; private PostgresService postgresService; private PolicyService policyService; @@ -32,7 +31,7 @@ public void start() { webhookService = new WebhookServiceImpl(postgresService, policyService, invoiceTable); binder = new ServiceBinder(vertx); - consumer = +// MessageConsumer consumer = binder.setAddress(WEBHOOK_SERVICE_ADDRESS).register(WebhookService.class, webhookService); LOGGER.info("webhook Service started"); } diff --git a/src/test/java/iudx/data/marketplace/apiserver/handlers/ValidationHandlerTest.java b/src/test/java/iudx/data/marketplace/apiserver/handlers/ValidationHandlerTest.java index b21a770c..22eb2093 100644 --- a/src/test/java/iudx/data/marketplace/apiserver/handlers/ValidationHandlerTest.java +++ b/src/test/java/iudx/data/marketplace/apiserver/handlers/ValidationHandlerTest.java @@ -114,7 +114,7 @@ public void testHandleMethod( when(routingContext.body()).thenReturn(requestBody); when(routingContext.body().asJsonObject()).thenReturn(req); when(routingContext.pathParams()).thenReturn(hashMap); - validationHandler = new ValidationHandler(vertx, requestType); + validationHandler = new ValidationHandler(requestType); validationHandler.handle(routingContext); verify(routingContext, times(numberOfInvocations)).request(); verify(routingContext, times(numberOfInvocations)).body(); diff --git a/src/test/java/iudx/data/marketplace/authenticator/AuthServiceTest.java b/src/test/java/iudx/data/marketplace/authenticator/AuthServiceTest.java index f1046608..4cf4040f 100644 --- a/src/test/java/iudx/data/marketplace/authenticator/AuthServiceTest.java +++ b/src/test/java/iudx/data/marketplace/authenticator/AuthServiceTest.java @@ -59,7 +59,7 @@ public static void setup(Vertx vertx, VertxTestContext testContext) { JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); catService = mock(CatalogueService.class); - authenticationServiceImpl = new AuthenticationServiceImpl(vertx, jwtAuth, config, api); + authenticationServiceImpl = new AuthenticationServiceImpl( jwtAuth, config, api); testContext.completeNow(); } @@ -176,7 +176,7 @@ public void testTokenIntrospectForVerifyFailure(Vertx vertx, VertxTestContext ve JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); catService = mock(CatalogueService.class); - AuthenticationServiceImpl authenticationServiceImpl = new AuthenticationServiceImpl(vertx, jwtAuth, config, api); + AuthenticationServiceImpl authenticationServiceImpl = new AuthenticationServiceImpl( jwtAuth, config, api); JsonObject authInfo = new JsonObject() .put(TOKEN, JwtHelper.providerToken); From 479ce0794d78020324996cbb525da2aab416566c Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 15:51:52 +0530 Subject: [PATCH 12/15] Refactor: fix test cases --- .../data/marketplace/consumer/ConsumerServiceTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/iudx/data/marketplace/consumer/ConsumerServiceTest.java b/src/test/java/iudx/data/marketplace/consumer/ConsumerServiceTest.java index 712b03ff..2b410c73 100644 --- a/src/test/java/iudx/data/marketplace/consumer/ConsumerServiceTest.java +++ b/src/test/java/iudx/data/marketplace/consumer/ConsumerServiceTest.java @@ -351,7 +351,7 @@ public AsyncResult answer(InvocationOnMock invocationOnMock) @DisplayName("Test Create Order - Success") public void testCreateOrderSuccess(VertxTestContext testContext) { - when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); + lenient().when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); when(consumer.getUserId()).thenReturn("consumer-id"); request.put(PRODUCT_VARIANT_ID, "pv-id"); doAnswer( @@ -386,7 +386,7 @@ public void testCreateOrderSuccess(VertxTestContext testContext) { @DisplayName("Test Order Create - Get Order Related Info Failed") public void testOrderCreateRelatedInfoFailed(VertxTestContext testContext) { - when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); + lenient().when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); when(consumer.getUserId()).thenReturn("consumer-id"); request.put(PRODUCT_VARIANT_ID, "pv-id"); doAnswer(Answer -> Future.failedFuture("Expected Message")).when(consumerServiceSpy).getOrderRelatedInfo(anyString()); @@ -405,7 +405,7 @@ public void testOrderCreateRelatedInfoFailed(VertxTestContext testContext) { @DisplayName("Test Order Create - RazorPay create order Failed") public void testOrderCreateRazorpayFailed(VertxTestContext testContext) { - when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); + lenient().when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); when(consumer.getUserId()).thenReturn("consumer-id"); request.put(PRODUCT_VARIANT_ID, "pv-id"); doAnswer( @@ -434,7 +434,7 @@ public void testOrderCreateRazorpayFailed(VertxTestContext testContext) { @DisplayName("Test Order Create - Generate Order Entry Failed") public void testOrderCreateGenerateOrderFailed(VertxTestContext testContext) { - when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); + lenient().when(consumer.getResourceServerUrl()).thenReturn("rs.iudx.io"); when(consumer.getUserId()).thenReturn("consumer-id"); request.put(PRODUCT_VARIANT_ID, "pv-id"); doAnswer( From 9b1f4f9a4fce56b6b298383cfe402f80528b9cc6 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 16:20:00 +0530 Subject: [PATCH 13/15] Refactor: resolve checkstyle issues --- .../apiserver/ApiServerVerticle.java | 20 ++++----- .../marketplace/apiserver/ConsumerApis.java | 9 ++-- .../marketplace/apiserver/ProviderApis.java | 11 +++-- .../apiserver/handlers/AuthHandler.java | 3 +- .../apiserver/handlers/ExceptionHandler.java | 4 +- .../linkedAccount/CreateLinkedAccount.java | 4 +- .../LinkedAccountServiceImpl.java | 2 +- .../linkedAccount/LinkedAccountVerticle.java | 2 +- .../provider/linkedAccount/package-info.java | 7 ++-- .../apiserver/util/RequestType.java | 2 +- .../validation/ValidationHandlerFactory.java | 3 +- .../types/JsonSchemaTypeValidator.java | 10 ++--- .../marketplace/auditing/package-info.java | 7 +++- .../AuthenticationServiceImpl.java | 1 - .../authenticator/AuthenticationVerticle.java | 1 - .../authorization/JwtAuthorization.java | 2 +- .../marketplace/common/HttpStatusCode.java | 4 +- .../consumer/ConsumerServiceImpl.java | 36 ++++++++-------- .../marketplace/consumer/package-info.java | 7 ++-- .../data/marketplace/deploy/Deployer.java | 1 - .../marketplace/policies/CreatePolicy.java | 3 +- .../marketplace/policies/DeletePolicy.java | 2 - .../marketplace/policies/PolicyVerticle.java | 1 - .../iudx/data/marketplace/policies/User.java | 8 +++- .../marketplace/policies/VerifyPolicy.java | 1 - .../postgres/PostgresServiceImpl.java | 3 +- .../marketplace/postgres/package-info.java | 7 ++-- .../product/ProductServiceImpl.java | 8 ++-- .../marketplace/product/util/Constants.java | 4 +- .../product/util/QueryBuilder.java | 10 ++--- .../variant/ProductVariantServiceImpl.java | 42 +++++++++++-------- .../product/variant/package-info.java | 7 ++-- .../marketplace/razorpay/RazorPayService.java | 2 +- .../razorpay/RazorPayServiceImpl.java | 7 +--- .../marketplace/razorpay/package-info.java | 5 ++- .../marketplace/webhook/WebhookVerticle.java | 6 +-- 36 files changed, 126 insertions(+), 126 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index 5badc030..47b0b519 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -179,10 +179,8 @@ public void start() throws Exception { ValidationHandler checkPolicyValidationHandler = new ValidationHandler(RequestType.CHECK_POLICY); ValidationHandler verifyValidationHandler = new ValidationHandler(RequestType.VERIFY); - ValidationHandler postLinkedAccountHandler = - new ValidationHandler(RequestType.POST_ACCOUNT); - ValidationHandler putLinkedAccountHandler = - new ValidationHandler(RequestType.PUT_ACCOUNT); + ValidationHandler postLinkedAccountHandler = new ValidationHandler(RequestType.POST_ACCOUNT); + ValidationHandler putLinkedAccountHandler = new ValidationHandler(RequestType.PUT_ACCOUNT); router .get(api.getPoliciesUrl()) @@ -190,10 +188,10 @@ public void start() throws Exception { .handler(this::getPoliciesHandler) .failureHandler(exceptionHandler); -// router -// .post(api.getProductUserMapsPath()) -// .handler(this::mapUserToProduct) -// .failureHandler(exceptionHandler); + // router + // .post(api.getProductUserMapsPath()) + // .handler(this::mapUserToProduct) + // .failureHandler(exceptionHandler); router .post(api.getVerifyUrl()) @@ -327,10 +325,10 @@ private void handleWebhookSignatureValidation(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); HttpServerRequest request = routingContext.request(); - String xRazorpaySignature = request.headers().get(HEADER_X_RAZORPAY_SIGNATURE); + String xrazorpaySignature = request.headers().get(HEADER_X_RAZORPAY_SIGNATURE); razorPayService - .webhookSignatureValidator(requestBody, xRazorpaySignature) + .webhookSignatureValidator(requestBody, xrazorpaySignature) .onSuccess( requestValidated -> { LOGGER.debug("Request Validated"); @@ -443,7 +441,7 @@ private void getPoliciesHandler(RoutingContext routingContext) { }); } -// private void mapUserToProduct(RoutingContext routingContext) {} + // private void mapUserToProduct(RoutingContext routingContext) {} private void handlePostLinkedAccount(RoutingContext routingContext) { JsonObject requestBody = routingContext.body().asJsonObject(); diff --git a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java index efebccd2..66c48f5e 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java @@ -59,13 +59,10 @@ public class ConsumerApis { Router init() { - ValidationHandler resourceValidationHandler = - new ValidationHandler(RequestType.RESOURCE); - ValidationHandler providerValidationHandler = - new ValidationHandler(RequestType.PROVIDER); + ValidationHandler resourceValidationHandler = new ValidationHandler(RequestType.RESOURCE); + ValidationHandler providerValidationHandler = new ValidationHandler(RequestType.PROVIDER); ValidationHandler orderValidationHandler = new ValidationHandler(RequestType.ORDER); - ValidationHandler purchaseValidationHandler = - new ValidationHandler(RequestType.PURCHASE); + ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); ValidationHandler productVariantHandler = new ValidationHandler(RequestType.PRODUCT); diff --git a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java index f0faec5d..1e381a8e 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java @@ -64,16 +64,13 @@ public class ProviderApis { Router init() { ValidationHandler productValidationHandler = new ValidationHandler(RequestType.PRODUCT); - ValidationHandler variantValidationHandler = - new ValidationHandler(RequestType.PRODUCT_VARIANT); + ValidationHandler variantValidationHandler = new ValidationHandler(RequestType.PRODUCT_VARIANT); ValidationHandler deleteVariantValidationHandler = new ValidationHandler(RequestType.DELETE_PRODUCT_VARIANT); ValidationHandler listVariantValidationHandler = new ValidationHandler(RequestType.LIST_PRODUCT_VARIANT); - ValidationHandler resourceValidationHandler = - new ValidationHandler(RequestType.RESOURCE); - ValidationHandler purchaseValidationHandler = - new ValidationHandler(RequestType.PURCHASE); + ValidationHandler resourceValidationHandler = new ValidationHandler(RequestType.RESOURCE); + ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); productService = ProductService.createProxy(vertx, PRODUCT_SERVICE_ADDRESS); @@ -432,6 +429,8 @@ private void handleSuccessResponse( .setStatusCode(statusCode) .end(); break; + default: + break; } } } diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java index 86e73b13..697c47e6 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/AuthHandler.java @@ -91,8 +91,7 @@ public void handle(RoutingContext context) { } else { processAuthFailure(context, "Invalid token"); } - } else // for all the other endpoints - { + } else { // for all the other endpoints checkAuth(requestJson, authInfo) .onSuccess( userObject -> { diff --git a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java index 5bfdbe3f..2ed0e211 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java +++ b/src/main/java/iudx/data/marketplace/apiserver/handlers/ExceptionHandler.java @@ -86,7 +86,7 @@ private JsonObject validationFailureReponse(String message) { /** * Handles the JsonDecode Exception. * - * @param routingContext + * @param routingContext associated with the request to add the appropriate response */ public void handleDecodeException(RoutingContext routingContext) { @@ -116,7 +116,7 @@ public void handleDecodeException(RoutingContext routingContext) { /** * Handles the exception from casting a object to different object. * - * @param routingContext + * @param routingContext associated with the request to add the appropriate response */ public void handleClassCastException(RoutingContext routingContext) { diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java index c03f0685..b9b0b342 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java @@ -80,8 +80,8 @@ public Future initiateCreatingLinkedAccount(JsonObject request, User /* send the information for auditing */ /* audit info = Ids generated by Razorpay + Necessary information (Non-sensitive PII) */ -// Future auditingFuture = - userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); + // Future auditingFuture = + userResponse.compose(insertInDBSuccessful -> addAuditLogs(referenceId, provider)); return userResponse; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java index 4f82765c..b83d5e38 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; public class LinkedAccountServiceImpl implements LinkedAccountService { -// private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountServiceImpl.class); + // private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountServiceImpl.class); private final CreateLinkedAccount createLinkedAccount; private final FetchLinkedAccount fetchLinkedAccount; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java index 49ad5434..7084f376 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java @@ -13,7 +13,7 @@ import org.apache.logging.log4j.Logger; public class LinkedAccountVerticle extends AbstractVerticle { -// private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); + // private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); private PostgresService postgresService; private LinkedAccountServiceImpl linkedAccountService; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java index 42fabd73..7804e510 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java @@ -1,8 +1,7 @@ - @ModuleGen( - groupPackage = "iudx.data.marketplace.apiserver.provider", - name = "iudx-data-marketplace-apiserver-provider", - useFutures = true) + groupPackage = "iudx.data.marketplace.apiserver.provider", + name = "iudx-data-marketplace-apiserver-provider", + useFutures = true) package iudx.data.marketplace.apiserver.provider.linkedAccount; import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java index 28ad04e6..e2b9d2ce 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java +++ b/src/main/java/iudx/data/marketplace/apiserver/util/RequestType.java @@ -25,7 +25,7 @@ public enum RequestType { private String filename; - RequestType(String filename) { + RequestType(String filename) { this.filename = filename; } diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java index fe8d0072..c8ba7980 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/ValidationHandlerFactory.java @@ -180,8 +180,7 @@ private List getProductVariantValidators( return validators; } - private List getDeleteProductVariantValidators( - final MultiMap parameters) { + private List getDeleteProductVariantValidators(final MultiMap parameters) { List validators = new ArrayList<>(); validators.add(new UuidTypeValidator(parameters.get(PRODUCT_VARIANT_ID), true)); return validators; diff --git a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java index 49473ee6..8df55903 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/data/marketplace/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -63,11 +63,11 @@ private boolean validateJson(JsonObject body, RequestType requestType) LOGGER.debug(schemaPath); final JsonSchema schema; -// try { -// final JsonNode sc = loadResource(schemaPath); -// } catch (Exception e) { -// LOGGER.error("Validation Error {}", e.getMessage()); -// } + // try { + // final JsonNode sc = loadResource(schemaPath); + // } catch (Exception e) { + // LOGGER.error("Validation Error {}", e.getMessage()); + // } final JsonNode schemaNode = loadResource(schemaPath); LOGGER.debug(schemaNode.asText()); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); diff --git a/src/main/java/iudx/data/marketplace/auditing/package-info.java b/src/main/java/iudx/data/marketplace/auditing/package-info.java index c17ec06e..8d0521dd 100644 --- a/src/main/java/iudx/data/marketplace/auditing/package-info.java +++ b/src/main/java/iudx/data/marketplace/auditing/package-info.java @@ -1,4 +1,7 @@ -@ModuleGen(groupPackage = "iudx.data.marketplace.auditing", name = "iudx-data-marketplace-auditing", - useFutures = true) +@ModuleGen( + groupPackage = "iudx.data.marketplace.auditing", + name = "iudx-data-marketplace-auditing", + useFutures = true) package iudx.data.marketplace.auditing; + import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java index 8254da3c..23682875 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationServiceImpl.java @@ -10,7 +10,6 @@ import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Promise; -import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.authentication.TokenCredentials; import io.vertx.ext.auth.jwt.JWTAuth; diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java index d08d18ff..7fed2065 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java @@ -16,7 +16,6 @@ import io.vertx.ext.web.client.WebClientOptions; import io.vertx.serviceproxy.ServiceBinder; import iudx.data.marketplace.common.Api; -import iudx.data.marketplace.common.CatalogueService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java index 29a3eabb..063c70c0 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/JwtAuthorization.java @@ -6,7 +6,7 @@ public class JwtAuthorization { -// private static final Logger LOGGER = LogManager.getLogger(JwtAuthorization.class); + // private static final Logger LOGGER = LogManager.getLogger(JwtAuthorization.class); private final AuthorizationStatergy authStrategy; diff --git a/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java b/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java index a9398925..755f5069 100644 --- a/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java +++ b/src/main/java/iudx/data/marketplace/common/HttpStatusCode.java @@ -73,7 +73,9 @@ public enum HttpStatusCode { public static HttpStatusCode getByValue(int value) { for (HttpStatusCode status : values()) { - if (status.value == value) return status; + if (status.value == value) { + return status; + } } throw new IllegalArgumentException("Invalid status code: " + value); } diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java index bd0c14ed..296ca04c 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerServiceImpl.java @@ -140,8 +140,8 @@ public ConsumerService listProducts( .replace("$8", resourceTable)); if (request.containsKey("resourceId")) { - String resourceID = request.getString("resourceId"); - params.put("resourceId", resourceID); + String resourceId = request.getString("resourceId"); + params.put("resourceId", resourceId); query.append(" and rt._id=$2"); } else if (request.containsKey("providerId")) { String providerId = request.getString("providerId"); @@ -170,7 +170,7 @@ public ConsumerService listProducts( @Override public ConsumerService createOrder( JsonObject request, User user, Handler> handler) { -// String resourceServerUrl = user.getResourceServerUrl(); + // String resourceServerUrl = user.getResourceServerUrl(); String variantId = request.getString(PRODUCT_VARIANT_ID); String consumerId = user.getUserId(); @@ -228,21 +228,21 @@ public ConsumerService listPurchase( Future paymentFuture = executePurchaseQuery(query, resourceId, productId, user); -// Future userResponseFuture = - paymentFuture.onComplete( - pgHandler -> { - if (pgHandler.succeeded()) { - JsonObject response = - new JsonObject() - .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) - .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) - .put(RESULTS, pgHandler.result()); - handler.handle(Future.succeededFuture(response)); - - } else { - handler.handle(Future.failedFuture(pgHandler.cause().getMessage())); - } - }); + // Future userResponseFuture = + paymentFuture.onComplete( + pgHandler -> { + if (pgHandler.succeeded()) { + JsonObject response = + new JsonObject() + .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) + .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) + .put(RESULTS, pgHandler.result()); + handler.handle(Future.succeededFuture(response)); + + } else { + handler.handle(Future.failedFuture(pgHandler.cause().getMessage())); + } + }); } catch (DxRuntimeException exception) { LOGGER.debug("Exception : " + exception.getMessage()); String failureMessage = diff --git a/src/main/java/iudx/data/marketplace/consumer/package-info.java b/src/main/java/iudx/data/marketplace/consumer/package-info.java index 75acd9e4..28670180 100644 --- a/src/main/java/iudx/data/marketplace/consumer/package-info.java +++ b/src/main/java/iudx/data/marketplace/consumer/package-info.java @@ -1,5 +1,6 @@ -@ModuleGen(groupPackage = "iudx.data.marketplace.consumer", -name = "iudx-data-marketplace-consumer-service") +@ModuleGen( + groupPackage = "iudx.data.marketplace.consumer", + name = "iudx-data-marketplace-consumer-service") package iudx.data.marketplace.consumer; -import io.vertx.codegen.annotations.ModuleGen; \ No newline at end of file +import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/deploy/Deployer.java b/src/main/java/iudx/data/marketplace/deploy/Deployer.java index 40f5ca26..7cc43a48 100644 --- a/src/main/java/iudx/data/marketplace/deploy/Deployer.java +++ b/src/main/java/iudx/data/marketplace/deploy/Deployer.java @@ -53,7 +53,6 @@ *

  • --modules/-m : comma separated list of module names to deploy, by default all is used to * deploy every verticle * - * * Replace the fatjar file with respective path to fat jar for clustered or non-clustered mode * Replace the configs with the respective path to config.json * diff --git a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java index 1cc1478f..40beb1e3 100644 --- a/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/CreatePolicy.java @@ -31,7 +31,8 @@ public class CreatePolicy { private int expiryInMonths; private String consumerEmailId; private String expiryAt; -// private User provider; + + // private User provider; public CreatePolicy(PostgresService postgresService, AuditingService auditingService, Api api) { this.postgresService = postgresService; diff --git a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java index bb33eea5..1cff6c50 100644 --- a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java @@ -12,8 +12,6 @@ import io.vertx.core.Promise; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; -import io.vertx.pgclient.PgPool; -import io.vertx.sqlclient.Tuple; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.common.HttpStatusCode; diff --git a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java index 475a55cd..4d1ab071 100644 --- a/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java +++ b/src/main/java/iudx/data/marketplace/policies/PolicyVerticle.java @@ -6,7 +6,6 @@ import io.vertx.serviceproxy.ServiceBinder; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; -import iudx.data.marketplace.common.CatalogueService; import iudx.data.marketplace.postgres.PostgresService; public class PolicyVerticle extends AbstractVerticle { diff --git a/src/main/java/iudx/data/marketplace/policies/User.java b/src/main/java/iudx/data/marketplace/policies/User.java index c1bdbb51..1d182336 100644 --- a/src/main/java/iudx/data/marketplace/policies/User.java +++ b/src/main/java/iudx/data/marketplace/policies/User.java @@ -94,8 +94,12 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof User)) return false; + if (this == o) { + return true; + } + if (!(o instanceof User)) { + return false; + } User user = (User) o; return Objects.equals(userId, user.userId) && userRole == user.userRole diff --git a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java index 9e09cfbc..c62d4925 100644 --- a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java @@ -9,7 +9,6 @@ import io.vertx.core.Promise; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; -import io.vertx.sqlclient.Tuple; import iudx.data.marketplace.common.HttpStatusCode; import iudx.data.marketplace.common.ResponseUrn; import iudx.data.marketplace.policies.util.Status; diff --git a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java index a31d7b17..12f0a2fc 100644 --- a/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/postgres/PostgresServiceImpl.java @@ -139,8 +139,7 @@ public PostgresService executeTransaction( .withTransaction( connection -> { ConcurrentLinkedQueue statements = new ConcurrentLinkedQueue<>(queries); - Future eB = executeBatch(connection, statements); - return eB; + return executeBatch(connection, statements); }) .onComplete( completeHandler -> { diff --git a/src/main/java/iudx/data/marketplace/postgres/package-info.java b/src/main/java/iudx/data/marketplace/postgres/package-info.java index 411dd09c..b44b8964 100644 --- a/src/main/java/iudx/data/marketplace/postgres/package-info.java +++ b/src/main/java/iudx/data/marketplace/postgres/package-info.java @@ -1,5 +1,6 @@ -@ModuleGen(groupPackage = "iudx.data.marketplace.postgres", - name="iudx-data-marketplace-postgres-service") +@ModuleGen( + groupPackage = "iudx.data.marketplace.postgres", + name = "iudx-data-marketplace-postgres-service") package iudx.data.marketplace.postgres; -import io.vertx.codegen.annotations.ModuleGen; \ No newline at end of file +import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java index 6ed2993b..9857c374 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java @@ -193,8 +193,8 @@ public ProductService createProduct( } private List fetchItemDetailsFromCat( - JsonObject request, String providerId, String productID, JsonArray resourceDetails) { - request.put(PROVIDER_ID, providerId).put(PRODUCT_ID, productID); + JsonObject request, String providerId, String productId, JsonArray resourceDetails) { + request.put(PROVIDER_ID, providerId).put(PRODUCT_ID, productId); JsonArray resourceIds = request.getJsonArray(RESOURCE_IDS); @@ -424,13 +424,13 @@ public Future fetchRazorpayDetailsOfProvider(String query, String pr if (!handler.result().getJsonArray(RESULTS).isEmpty()) { JsonObject result = handler.result().getJsonArray(RESULTS).getJsonObject(0); String accountId = result.getString("account_id"); - String rzp_account_product_id = result.getString("rzp_account_product_id"); + String rzpAccountProductId = result.getString("rzp_account_product_id"); String status = result.getString("status"); LOGGER.info( "Provider with _id : {} , with accountId {}, accountProductId {} has status : {}", providerId, accountId, - rzp_account_product_id, + rzpAccountProductId, status); promise.complete(result); } else { diff --git a/src/main/java/iudx/data/marketplace/product/util/Constants.java b/src/main/java/iudx/data/marketplace/product/util/Constants.java index 844ccfab..fa908af2 100644 --- a/src/main/java/iudx/data/marketplace/product/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/product/util/Constants.java @@ -24,7 +24,9 @@ public class Constants { public static final String INSERT_PRODUCT_QUERY = "insert into $0 (product_id, provider_id, provider_name, status) values ('$1', '$2', '$3', '$4')"; public static final String INSERT_RESOURCE_QUERY = - "insert into $0 (_id, resource_name, provider_id, provider_name, resource_server, accessPolicy) values ('$1', '$2', '$3', '$4', '$5', '$6') on conflict (_id) do nothing"; + "insert into $0 (_id, resource_name, provider_id, provider_name, resource_server, accessPolicy)" + + + " values ('$1', '$2', '$3', '$4', '$5', '$6') on conflict (_id) do nothing"; public static final String INSERT_P_R_REL_QUERY = "insert into $0 (product_id, resource_id) values ('$1', '$2')"; diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index a26c6646..e2ece2a2 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -32,7 +32,7 @@ public QueryBuilder(JsonArray tables) { public List buildCreateProductQueries(JsonObject request, JsonArray resourceDetails) { String productId = request.getString(PRODUCT_ID); - String providerID = request.getString(PROVIDER_ID); + String providerId = request.getString(PROVIDER_ID); String providerName = request.getString(PROVIDER_NAME); List queries = new ArrayList(); @@ -42,7 +42,7 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso INSERT_PRODUCT_QUERY .replace("$0", productTable) .replace("$1", productId) - .replace("$2", providerID) + .replace("$2", providerId) .replace("$3", providerName) .replace("$4", Status.ACTIVE.toString())) .toString()); @@ -56,7 +56,7 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso .replace("$0", resourceTable) .replace("$1", ((JsonObject) resource).getString(RESOURCE_ID)) .replace("$2", ((JsonObject) resource).getString(RESOURCE_NAME)) - .replace("$3", providerID) + .replace("$3", providerId) .replace("$4", providerName) .replace("$5", request.getString(RESOURCE_SERVER)) .replace("$6", ((JsonObject) resource).getString("accessPolicy"))) @@ -112,14 +112,14 @@ public String buildCreateProductVariantQuery(JsonObject request) { JsonArray resources = request.getJsonArray(RESOURCES_ARRAY); // UUID for each product variant. - String pvID = supplier.get(); + String pvId = supplier.get(); LOGGER.debug("request is : " + request.encodePrettily()); StringBuilder query = new StringBuilder( INSERT_PV_QUERY .replace("$0", productVariantTable) - .replace("$1", pvID) + .replace("$1", pvId) .replace("$2", request.getString("provider_id")) .replace("$3", request.getString(PRODUCT_ID)) .replace("$4", request.getString(PRODUCT_VARIANT_NAME)) diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java index 89e6c530..610d0e68 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java @@ -161,8 +161,12 @@ private Future checkIfProductVariantExists(String productId, String var query, handler -> { if (handler.succeeded()) { - if (handler.result().getInteger("totalHits") != 0) promise.complete(true); - else promise.complete(false); + if (handler.result().getInteger("totalHits") != 0) { + promise.complete(true); + } + else { + promise.complete(false); + } } else { promise.fail(handler.cause()); } @@ -284,7 +288,9 @@ public ProductVariantService updateProductVariant( .withType(ResponseUrn.RESOURCE_NOT_FOUND_URN.getUrn()) .withTitle(ResponseUrn.RESOURCE_NOT_FOUND_URN.getMessage()) .withDetail( - "Product Variant cannot be updated as the product is in INACTIVE state or product is not found") + "Product Variant cannot be updated as the product is in INACTIVE state or " + + + "product is not found") .getResponse())); } @@ -446,21 +452,21 @@ public ProductVariantService listPurchase( } Future paymentFuture = executePurchaseQuery(query, resourceId, productId, user); -// Future userResponseFuture = - paymentFuture.onComplete( - pgHandler -> { - if (pgHandler.succeeded()) { - JsonObject response = - new JsonObject() - .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) - .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) - .put(RESULTS, pgHandler.result()); - handler.handle(Future.succeededFuture(response)); - - } else { - handler.handle(Future.failedFuture(pgHandler.cause().getMessage())); - } - }); + // Future userResponseFuture = + paymentFuture.onComplete( + pgHandler -> { + if (pgHandler.succeeded()) { + JsonObject response = + new JsonObject() + .put(TYPE, ResponseUrn.SUCCESS_URN.getUrn()) + .put(TITLE, ResponseUrn.SUCCESS_URN.getMessage()) + .put(RESULTS, pgHandler.result()); + handler.handle(Future.succeededFuture(response)); + + } else { + handler.handle(Future.failedFuture(pgHandler.cause().getMessage())); + } + }); } catch (DxRuntimeException exception) { LOGGER.debug("Exception : " + exception.getMessage()); diff --git a/src/main/java/iudx/data/marketplace/product/variant/package-info.java b/src/main/java/iudx/data/marketplace/product/variant/package-info.java index b745e7eb..3f457137 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/package-info.java +++ b/src/main/java/iudx/data/marketplace/product/variant/package-info.java @@ -1,5 +1,6 @@ -@ModuleGen(groupPackage = "iudx.data.marketplace.product.variant", -name = "iudx-data-marketplace-product-variant-service") +@ModuleGen( + groupPackage = "iudx.data.marketplace.product.variant", + name = "iudx-data-marketplace-product-variant-service") package iudx.data.marketplace.product.variant; -import io.vertx.codegen.annotations.ModuleGen; \ No newline at end of file +import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java index 8234a1fa..05718c26 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayService.java @@ -27,7 +27,7 @@ static RazorPayService createProxy(Vertx vertx, String address) { * method also creates a transfer from the order to the respective merchant account * * @param request which is a JsonObject - * @retun Future which is a vertx Future + * @retun Future JsonObject which is a vertx Future */ Future createOrder(JsonObject request); diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java index 433b9dc2..239370c6 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java @@ -76,9 +76,7 @@ public Future createOrder(JsonObject request) { String status = order.get(STATUS); if (!status.equals(CREATED)) { throw new DxRuntimeException( - 400, - ResponseUrn.ORDER_NOT_CREATED, - "Order creation returned with status : " + status); + 400, ResponseUrn.ORDER_NOT_CREATED, "Order creation returned with status : " + status); } JSONArray transfersArray = order.get(TRANFERS); JSONObject transferResponse = transfersArray.getJSONObject(0); @@ -265,8 +263,7 @@ public Future fetchProductConfiguration(JsonObject request) { LOGGER.error("Linked account not activated"); String detail = "To activate linked account please complete the KYC, filling account information etc., " - + - "in your Razorpay merchant dashboard"; + + "in your Razorpay merchant dashboard"; promise.fail(detail); } } catch (RazorpayException e) { diff --git a/src/main/java/iudx/data/marketplace/razorpay/package-info.java b/src/main/java/iudx/data/marketplace/razorpay/package-info.java index f0bba14d..9c44228c 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/package-info.java +++ b/src/main/java/iudx/data/marketplace/razorpay/package-info.java @@ -1,6 +1,7 @@ @ModuleGen( groupPackage = "iudx.data.marketplace.razorpay", - name = "iudx-data-marketplace-razorpay-service", useFutures = true) + name = "iudx-data-marketplace-razorpay-service", + useFutures = true) package iudx.data.marketplace.razorpay; -import io.vertx.codegen.annotations.ModuleGen; \ No newline at end of file +import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java index 91d4eab5..72948215 100644 --- a/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java +++ b/src/main/java/iudx/data/marketplace/webhook/WebhookVerticle.java @@ -4,8 +4,6 @@ import static iudx.data.marketplace.product.util.Constants.TABLES; import io.vertx.core.AbstractVerticle; -import io.vertx.core.eventbus.MessageConsumer; -import io.vertx.core.json.JsonObject; import io.vertx.serviceproxy.ServiceBinder; import iudx.data.marketplace.policies.PolicyService; import iudx.data.marketplace.postgres.PostgresService; @@ -31,8 +29,8 @@ public void start() { webhookService = new WebhookServiceImpl(postgresService, policyService, invoiceTable); binder = new ServiceBinder(vertx); -// MessageConsumer consumer = - binder.setAddress(WEBHOOK_SERVICE_ADDRESS).register(WebhookService.class, webhookService); + // MessageConsumer consumer = + binder.setAddress(WEBHOOK_SERVICE_ADDRESS).register(WebhookService.class, webhookService); LOGGER.info("webhook Service started"); } } From 732929fd7898702bdecd3c1f235aada7ba59f173 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 17:27:59 +0530 Subject: [PATCH 14/15] Refactor: resolve checkstyle issues --- .../apiserver/ApiServerVerticle.java | 11 +-- .../marketplace/apiserver/ConsumerApis.java | 27 ++++--- .../marketplace/apiserver/ProviderApis.java | 15 ++-- .../CreateLinkedAccount.java | 33 +++------ .../FetchLinkedAccount.java | 23 +++--- .../LinkedAccountService.java | 2 +- .../LinkedAccountServiceImpl.java | 4 +- .../LinkedAccountVerticle.java | 4 +- .../UpdateLinkedAccount.java | 55 ++++++-------- .../package-info.java | 2 +- .../util/Constants.java | 2 +- .../marketplace/auditing/AuditingService.java | 4 +- .../authenticator/AuthenticationVerticle.java | 2 +- .../AuthorizationContextFactory.java | 14 ++-- .../marketplace/common/CatalogueService.java | 8 +- .../iudx/data/marketplace/common/Util.java | 11 ++- .../marketplace/consumer/ConsumerService.java | 14 ++-- .../marketplace/policies/DeletePolicy.java | 1 - .../marketplace/policies/VerifyPolicy.java | 1 - .../product/ProductServiceImpl.java | 3 +- .../product/util/QueryBuilder.java | 73 +++++++++---------- .../variant/ProductVariantService.java | 2 +- .../variant/ProductVariantServiceImpl.java | 6 +- .../razorpay/RazorPayServiceImpl.java | 4 +- .../razorpay/util/ErrorMessageBuilder.java | 2 +- .../TestCreateLinkedAccount.java | 3 +- .../linkedAccount/TestFetchLinkedAccount.java | 1 + .../TestUpdateLinkedAccount.java | 1 + .../marketplace/policy/TestCreatePolicy.java | 2 - 29 files changed, 155 insertions(+), 175 deletions(-) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/CreateLinkedAccount.java (94%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/FetchLinkedAccount.java (97%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/LinkedAccountService.java (96%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/LinkedAccountServiceImpl.java (95%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/LinkedAccountVerticle.java (92%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/UpdateLinkedAccount.java (96%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/package-info.java (75%) rename src/main/java/iudx/data/marketplace/apiserver/provider/{linkedAccount => linkedaccount}/util/Constants.java (96%) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java index 47b0b519..2b93443a 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ApiServerVerticle.java @@ -20,7 +20,7 @@ import iudx.data.marketplace.apiserver.handlers.AuthHandler; import iudx.data.marketplace.apiserver.handlers.ExceptionHandler; import iudx.data.marketplace.apiserver.handlers.ValidationHandler; -import iudx.data.marketplace.apiserver.provider.linkedAccount.LinkedAccountService; +import iudx.data.marketplace.apiserver.provider.linkedaccount.LinkedAccountService; import iudx.data.marketplace.apiserver.util.RequestType; import iudx.data.marketplace.authenticator.AuthClient; import iudx.data.marketplace.authenticator.AuthenticationService; @@ -95,7 +95,6 @@ public void start() throws Exception { webClientOptions.setTrustAll(false).setVerifyHost(true).setSsl(true); webClient = WebClient.create(vertx, webClientOptions); - Api api = Api.getInstance(config().getString("dxApiBasePath")); /* Initialize service proxy */ policyService = PolicyService.createProxy(vertx, POLICY_SERVICE_ADDRESS); @@ -163,6 +162,7 @@ public void start() throws Exception { serverOptions.setCompressionSupported(true).setCompressionLevel(5); server = vertx.createHttpServer(serverOptions); server.requestHandler(router).listen(port); + Api api = Api.getInstance(config().getString("dxApiBasePath")); router .route(PROVIDER_PATH + "/*") @@ -533,9 +533,6 @@ private void handleSuccessResponse(HttpServerResponse response, int statusCode, response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); } - private void handleResponse(HttpServerResponse response, int statusCode, String result) { - response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); - } /** * Handles Failed HTTP Response @@ -582,6 +579,10 @@ private void handleFailureResponse(RoutingContext routingContext, String failure } } + private void handleResponse(HttpServerResponse response, int statusCode, String result) { + response.putHeader(CONTENT_TYPE, APPLICATION_JSON).setStatusCode(statusCode).end(result); + } + private void handleResponse( HttpServerResponse response, HttpStatusCode statusCode, ResponseUrn urn) { handleResponse(response, statusCode, urn, statusCode.getDescription()); diff --git a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java index 66c48f5e..4e5c22d2 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java @@ -61,10 +61,7 @@ Router init() { ValidationHandler resourceValidationHandler = new ValidationHandler(RequestType.RESOURCE); ValidationHandler providerValidationHandler = new ValidationHandler(RequestType.PROVIDER); - ValidationHandler orderValidationHandler = new ValidationHandler(RequestType.ORDER); - ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); - ValidationHandler productVariantHandler = new ValidationHandler(RequestType.PRODUCT); consumerService = ConsumerService.createProxy(vertx, CONSUMER_SERVICE_ADDRESS); @@ -89,6 +86,8 @@ Router init() { .handler(this::listProducts) .failureHandler(exceptionHandler); + ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); + router .get(api.getConsumerListPurchases()) .handler(purchaseValidationHandler) @@ -96,6 +95,8 @@ Router init() { .handler(this::listPurchases) .failureHandler(exceptionHandler); + ValidationHandler productVariantHandler = new ValidationHandler(RequestType.PRODUCT); + router .get(api.getConsumerProductVariantPath()) .handler(productVariantHandler) @@ -103,6 +104,8 @@ Router init() { .handler(this::listProductVariants) .failureHandler(exceptionHandler); + ValidationHandler orderValidationHandler = new ValidationHandler(RequestType.ORDER); + router .post(CONSUMER_PATH + ORDERS_PATH + "/:productVariantId") .handler(orderValidationHandler) @@ -263,14 +266,6 @@ private void listPurchases(RoutingContext routingContext) { }); } - private void handleFailureResponse(RoutingContext routingContext, Throwable cause) { - routingContext - .response() - .putHeader(CONTENT_TYPE, APPLICATION_JSON) - .setStatusCode(400) - .end(cause.getMessage()); - } - private void handleSuccessResponse( RoutingContext routingContext, int statusCode, JsonObject result) { @@ -290,9 +285,19 @@ private void handleSuccessResponse( .setStatusCode(statusCode) .end(); break; + default: + break; } } + private void handleFailureResponse(RoutingContext routingContext, Throwable cause) { + routingContext + .response() + .putHeader(CONTENT_TYPE, APPLICATION_JSON) + .setStatusCode(400) + .end(cause.getMessage()); + } + /** * Handles Failed HTTP Response * diff --git a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java index 1e381a8e..b66fe3e6 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ProviderApis.java @@ -64,13 +64,6 @@ public class ProviderApis { Router init() { ValidationHandler productValidationHandler = new ValidationHandler(RequestType.PRODUCT); - ValidationHandler variantValidationHandler = new ValidationHandler(RequestType.PRODUCT_VARIANT); - ValidationHandler deleteVariantValidationHandler = - new ValidationHandler(RequestType.DELETE_PRODUCT_VARIANT); - ValidationHandler listVariantValidationHandler = - new ValidationHandler(RequestType.LIST_PRODUCT_VARIANT); - ValidationHandler resourceValidationHandler = new ValidationHandler(RequestType.RESOURCE); - ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); ExceptionHandler exceptionHandler = new ExceptionHandler(); productService = ProductService.createProxy(vertx, PRODUCT_SERVICE_ADDRESS); @@ -90,6 +83,7 @@ Router init() { .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::handleDeleteProduct) .failureHandler(exceptionHandler); + ValidationHandler resourceValidationHandler = new ValidationHandler(RequestType.RESOURCE); router .get(api.getProviderListProductsPath()) @@ -97,6 +91,7 @@ Router init() { .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::listProducts) .failureHandler(exceptionHandler); + ValidationHandler purchaseValidationHandler = new ValidationHandler(RequestType.PURCHASE); router .get(api.getProviderListPurchasesPath()) @@ -104,6 +99,7 @@ Router init() { .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::listPurchases) .failureHandler(exceptionHandler); + ValidationHandler variantValidationHandler = new ValidationHandler(RequestType.PRODUCT_VARIANT); router .post(api.getProviderProductVariantPath()) @@ -118,13 +114,16 @@ Router init() { .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::handleUpdateProductVariant) .failureHandler(exceptionHandler); - + ValidationHandler listVariantValidationHandler = + new ValidationHandler(RequestType.LIST_PRODUCT_VARIANT); router .get(api.getProviderProductVariantPath()) .handler(listVariantValidationHandler) .handler(AuthHandler.create(authenticationService, api, postgresService, authClient)) .handler(this::handleGetProductVariants) .failureHandler(exceptionHandler); + ValidationHandler deleteVariantValidationHandler = + new ValidationHandler(RequestType.DELETE_PRODUCT_VARIANT); router .delete(api.getProviderProductVariantPath()) diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/CreateLinkedAccount.java similarity index 94% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/CreateLinkedAccount.java index b9b0b342..f9af55e0 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/CreateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/CreateLinkedAccount.java @@ -1,6 +1,6 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.*; import static iudx.data.marketplace.apiserver.util.Constants.*; import com.google.common.hash.Hashing; @@ -130,7 +130,6 @@ private Future createLinkedAccount(JsonObject merchantDetails) { */ public JsonObject getLinkedAccountDetails( JsonObject request, String referenceId, String emailId) { - String businessType = request.getString("businessType"); String category = request.getJsonObject("profile").getString("category"); String subcategory = request.getJsonObject("profile").getString("subcategory"); JsonObject registered = @@ -141,7 +140,6 @@ public JsonObject getLinkedAccountDetails( String state = registered.getString("state"); String postalCode = registered.getString("postalCode"); String country = registered.getString("country"); - String contactName = request.getString("contactName"); JsonObject registeredJson = new JsonObject() @@ -153,11 +151,7 @@ public JsonObject getLinkedAccountDetails( .put("country", country); JsonObject addressJson = new JsonObject().put("registered", registeredJson); - JsonObject profileJson = - new JsonObject() - .put("category", category) - .put("subcategory", subcategory) - .put("addresses", addressJson); + JsonObject legalInfoJson = new JsonObject(); /* checks if optional field legal info is null */ @@ -173,32 +167,27 @@ public JsonObject getLinkedAccountDetails( } String phoneNumber = request.getString("phone"); String legalBusinessName = request.getString("legalBusinessName"); - String customerFacingBusinessName = request.getString("customerFacingBusinessName"); + String businessType = request.getString("businessType"); + JsonObject profileJson = new JsonObject().put("category", category) + .put("subcategory", subcategory).put("addresses", addressJson); + JsonObject details = new JsonObject().put("email", emailId).put("phone", phoneNumber) + .put("legal_business_name", legalBusinessName).put("type", ACCOUNT_TYPE).put("reference_id", referenceId) + .put("business_type", businessType).put("profile", profileJson).put("legal_info", legalInfoJson); setLegalBusinessName(legalBusinessName); setEmailId(emailId); setPhoneNumber(phoneNumber); setBusinessType(businessType); - - JsonObject details = - new JsonObject() - .put("email", emailId) - .put("phone", phoneNumber) - .put("legal_business_name", legalBusinessName) - .put("type", ACCOUNT_TYPE) - .put("reference_id", referenceId) - .put("business_type", businessType) - .put("profile", profileJson) - .put("legal_info", legalInfoJson); - setCustomerFacingBusinessName(legalBusinessName); /* customer facing business name is not a necessary field in the request body * while inserting in the DB, if customer facing business name is null, it is * replaced with the legal business name */ + String customerFacingBusinessName = request.getString("customerFacingBusinessName"); if (StringUtils.isNotBlank(customerFacingBusinessName)) { setCustomerFacingBusinessName(customerFacingBusinessName); details.put("customer_facing_business_name", customerFacingBusinessName); } + String contactName = request.getString("contactName"); if (StringUtils.isNotBlank(contactName)) { details.put("contact_name", contactName); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/FetchLinkedAccount.java similarity index 97% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/FetchLinkedAccount.java index dfd21b1f..3797da7b 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/FetchLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/FetchLinkedAccount.java @@ -1,6 +1,6 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.*; import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; import io.vertx.core.Future; @@ -53,11 +53,9 @@ public Future initiateFetchingLinkedAccount(User provider) { public Future generateSuccessResponse(JsonObject rzpResponseJson) { String emailId = rzpResponseJson.getString("email"); - String accountId = rzpResponseJson.getString("id"); String type = rzpResponseJson.getString("type"); String status = rzpResponseJson.getString("status"); String referenceId = rzpResponseJson.getString("reference_id"); - String businessType = rzpResponseJson.getString("business_type"); String category = rzpResponseJson.getJsonObject("profile").getString("category"); String subcategory = rzpResponseJson.getJsonObject("profile").getString("subcategory"); JsonObject registered = @@ -102,12 +100,8 @@ public Future generateSuccessResponse(JsonObject rzpResponseJson) { } } String phoneNumber = rzpResponseJson.getString("phone"); - String legalBusinessName = rzpResponseJson.getString("legal_business_name"); - String customerFacingBusinessName = rzpResponseJson.getString("customer_facing_business_name"); - - JsonObject details = - new JsonObject() - .put("accountId", accountId) + String accountId = rzpResponseJson.getString("id"); + JsonObject details = new JsonObject().put("accountId", accountId) .put("type", type) .put("status", status) .put("email", emailId) @@ -117,9 +111,16 @@ public Future generateSuccessResponse(JsonObject rzpResponseJson) { if (StringUtils.isNotBlank(contactName)) { details.put("contactName", contactName); } + + String businessType = rzpResponseJson.getString("business_type"); + String legalBusinessName = rzpResponseJson.getString("legal_business_name"); + details.put("referenceId", referenceId); details.put("businessType", businessType); details.put("legalBusinessName", legalBusinessName); + + String customerFacingBusinessName = rzpResponseJson.getString("customer_facing_business_name"); + if (StringUtils.isNotBlank(customerFacingBusinessName)) { details.put("customerFacingBusinessName", customerFacingBusinessName); } @@ -148,13 +149,13 @@ Future getAccountId(String query, User provider) { if (handler.succeeded()) { if (!handler.result().getJsonArray(RESULTS).isEmpty()) { JsonObject result = handler.result().getJsonArray(RESULTS).getJsonObject(0); - String accountId = result.getString("account_id"); String accountProductId = result.getString("rzp_account_product_id"); String updatedAt = result.getString("updatedAt"); String createdAt = result.getString("createdAt"); setRazorpayAccountProductId(accountProductId); setUpdatedAt(updatedAt); setCreatedAt(createdAt); + String accountId = result.getString("account_id"); promise.complete(new JsonObject().put("accountId", accountId)); } else { promise.fail( diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountService.java similarity index 96% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountService.java index 14525255..97e6cdf7 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountService.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountService.java @@ -1,4 +1,4 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.codegen.annotations.ProxyGen; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountServiceImpl.java similarity index 95% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountServiceImpl.java index b83d5e38..63572590 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountServiceImpl.java @@ -1,11 +1,9 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonObject; import iudx.data.marketplace.policies.User; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class LinkedAccountServiceImpl implements LinkedAccountService { // private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountServiceImpl.class); diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountVerticle.java similarity index 92% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountVerticle.java index 7084f376..fbc78bc3 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/LinkedAccountVerticle.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/LinkedAccountVerticle.java @@ -1,4 +1,4 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; import static iudx.data.marketplace.common.Constants.*; @@ -9,8 +9,6 @@ import iudx.data.marketplace.common.Api; import iudx.data.marketplace.postgres.PostgresService; import iudx.data.marketplace.razorpay.RazorPayService; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; public class LinkedAccountVerticle extends AbstractVerticle { // private static final Logger LOGGER = LogManager.getLogger(LinkedAccountVerticle.class); diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/UpdateLinkedAccount.java similarity index 96% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/UpdateLinkedAccount.java index 5428a2f8..148962a3 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/UpdateLinkedAccount.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/UpdateLinkedAccount.java @@ -1,6 +1,6 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.*; import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; import io.vertx.core.Future; @@ -83,34 +83,6 @@ public Future initiateUpdatingLinkedAccount(JsonObject request, User } public String getAccountRequest(JsonObject requestBody) { - String category = requestBody.getJsonObject("profile").getString("category"); - String subcategory = requestBody.getJsonObject("profile").getString("subcategory"); - JsonObject registered = - requestBody.getJsonObject("profile").getJsonObject("addresses").getJsonObject("registered"); - String street1 = registered.getString("street1"); - String street2 = registered.getString("street2"); - String city = registered.getString("city"); - String state = registered.getString("state"); - String postalCode = registered.getString("postalCode"); - String country = registered.getString("country"); - String contactName = requestBody.getString("contactName"); - - JsonObject registeredJson = - new JsonObject() - .put("street1", street1) - .put("street2", street2) - .put("city", city) - .put("state", state) - .put("postal_code", postalCode) - .put("country", country); - - JsonObject addressJson = new JsonObject().put("registered", registeredJson); - JsonObject profileJson = - new JsonObject() - .put("category", category) - .put("subcategory", subcategory) - .put("addresses", addressJson); - JsonObject legalInfoJson = new JsonObject(); /* checks if optional field legal info is null */ if (requestBody.getJsonObject("legalInfo") != null) { @@ -125,10 +97,28 @@ public String getAccountRequest(JsonObject requestBody) { } String phoneNumber = requestBody.getString("phone"); String legalBusinessName = requestBody.getString("legalBusinessName"); - String customerFacingBusinessName = requestBody.getString("customerFacingBusinessName"); setLegalBusinessName(legalBusinessName); setPhoneNumber(phoneNumber); + String category = requestBody.getJsonObject("profile").getString("category"); + String subcategory = requestBody.getJsonObject("profile").getString("subcategory"); + JsonObject registered = + requestBody.getJsonObject("profile").getJsonObject("addresses").getJsonObject("registered"); + String street1 = registered.getString("street1"); + String street2 = registered.getString("street2"); + String city = registered.getString("city"); + String state = registered.getString("state"); + String postalCode = registered.getString("postalCode"); + String country = registered.getString("country"); + JsonObject registeredJson = new JsonObject().put("street1", street1).put("street2", street2).put("city", city) + .put("state", state).put("postal_code", postalCode).put("country", country); + JsonObject addressJson = new JsonObject().put("registered", registeredJson); + + JsonObject profileJson = + new JsonObject() + .put("category", category) + .put("subcategory", subcategory) + .put("addresses", addressJson); JsonObject details = new JsonObject() @@ -136,6 +126,7 @@ public String getAccountRequest(JsonObject requestBody) { .put("legal_business_name", legalBusinessName) .put("profile", profileJson) .put("legal_info", legalInfoJson); + String customerFacingBusinessName = requestBody.getString("customerFacingBusinessName"); setCustomerFacingBusinessName(legalBusinessName); /* customer facing business name is not a necessary field in the request body @@ -145,6 +136,8 @@ public String getAccountRequest(JsonObject requestBody) { setCustomerFacingBusinessName(customerFacingBusinessName); details.put("customer_facing_business_name", customerFacingBusinessName); } + String contactName = requestBody.getString("contactName"); + if (StringUtils.isNotBlank(contactName)) { details.put("contact_name", contactName); } diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/package-info.java similarity index 75% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/package-info.java index 7804e510..71e3ac44 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/package-info.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/package-info.java @@ -2,6 +2,6 @@ groupPackage = "iudx.data.marketplace.apiserver.provider", name = "iudx-data-marketplace-apiserver-provider", useFutures = true) -package iudx.data.marketplace.apiserver.provider.linkedAccount; +package iudx.data.marketplace.apiserver.provider.linkedaccount; import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/util/Constants.java similarity index 96% rename from src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java rename to src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/util/Constants.java index 4fd87d38..c4985598 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/provider/linkedAccount/util/Constants.java +++ b/src/main/java/iudx/data/marketplace/apiserver/provider/linkedaccount/util/Constants.java @@ -1,4 +1,4 @@ -package iudx.data.marketplace.apiserver.provider.linkedAccount.util; +package iudx.data.marketplace.apiserver.provider.linkedaccount.util; public class Constants { public static final String INSERT_MERCHANT_INFO_QUERY = diff --git a/src/main/java/iudx/data/marketplace/auditing/AuditingService.java b/src/main/java/iudx/data/marketplace/auditing/AuditingService.java index 0269e537..cf06a0f5 100644 --- a/src/main/java/iudx/data/marketplace/auditing/AuditingService.java +++ b/src/main/java/iudx/data/marketplace/auditing/AuditingService.java @@ -16,9 +16,9 @@ static AuditingService createProxy(Vertx vertx, String address) { return new AuditingServiceVertxEBProxy(vertx, address); } - /*** - * This methods creates is used to create audit logs to be stored in respective databases + /** This methods creates is used to create audit logs to be stored in respective databases * by sending the messages through the data broker + * * @param user The user Object that is created during user authentication * @param information would contain the request body, response and essential additional information * @param api Endpoint that is called by the user diff --git a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java index 7fed2065..8f4b8fab 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/data/marketplace/authenticator/AuthenticationVerticle.java @@ -74,7 +74,7 @@ public void start() throws Exception { } JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); -// CatalogueService catalogueService = new CatalogueService(vertx, config()); + /*CatalogueService catalogueService = new CatalogueService(vertx, config());*/ api = Api.getInstance(config().getString("dxApiBasePath")); authenticationService = new AuthenticationServiceImpl(jwtAuth, config(), api); diff --git a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java index c2076689..8bd917ee 100644 --- a/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java +++ b/src/main/java/iudx/data/marketplace/authenticator/authorization/AuthorizationContextFactory.java @@ -8,14 +8,12 @@ public static AuthorizationStatergy create(IudxRole role, Api api) { throw new IllegalArgumentException(role + " role is not defined in IUDX"); } switch (role) { - case PROVIDER: - { - return ProviderAuthStatergy.getInstance(api); - } - case CONSUMER: - { - return ConsumerAuthStatergy.getInstance(api); - } + case PROVIDER: { + return ProviderAuthStatergy.getInstance(api); + } + case CONSUMER: { + return ConsumerAuthStatergy.getInstance(api); + } default: throw new IllegalArgumentException(role + " role is not defined in IUDX"); } diff --git a/src/main/java/iudx/data/marketplace/common/CatalogueService.java b/src/main/java/iudx/data/marketplace/common/CatalogueService.java index 27c9cce8..d5296369 100644 --- a/src/main/java/iudx/data/marketplace/common/CatalogueService.java +++ b/src/main/java/iudx/data/marketplace/common/CatalogueService.java @@ -26,7 +26,8 @@ public class CatalogueService { static WebClient catWebClient; private static String catHost; private static int catPort; - private static String catItemPath, catRelPath; + private static String catItemPath; + private static String catRelPath; public CatalogueService(Vertx vertx, JsonObject config) { catHost = config.getString(CAT_SERVER_HOST); @@ -123,7 +124,6 @@ public Future getResourceCount(String resourceId) { } public Future searchApi(JsonObject params) { - Promise promise = Promise.promise(); JsonArray keysArray = new JsonArray(); JsonArray valuesArray = new JsonArray(); @@ -137,6 +137,7 @@ public Future searchApi(JsonObject params) { LOGGER.debug(keysArray.getList().toString()); LOGGER.debug(valuesArray.getList().toString()); + Promise promise = Promise.promise(); catWebClient .get(catPort, catHost, "/iudx/cat/v1/search") @@ -145,13 +146,14 @@ public Future searchApi(JsonObject params) { .send( searchApiHandler -> { if (searchApiHandler.succeeded()) { + promise.complete(searchApiHandler.result().bodyAsJsonObject()); LOGGER.debug(searchApiHandler.result().bodyAsJsonObject()); } else { + promise.fail(searchApiHandler.cause()); LOGGER.error(searchApiHandler.cause()); } }); - promise.complete(); return promise.future(); } } diff --git a/src/main/java/iudx/data/marketplace/common/Util.java b/src/main/java/iudx/data/marketplace/common/Util.java index b7f9c4af..be127e7b 100644 --- a/src/main/java/iudx/data/marketplace/common/Util.java +++ b/src/main/java/iudx/data/marketplace/common/Util.java @@ -78,24 +78,23 @@ public JsonObject getUserJsonFromRowEntry(JsonObject row, Role role) { * @return creates a product json object with a given structure */ public JsonObject getProductInfo(JsonObject row) { - JsonObject productJson = - new JsonObject() - .put( - "product", - new JsonObject() + JsonObject productJson = new JsonObject().put("product", new JsonObject() .put("productId", row.getString("productId")) .put("productVariantId", row.getString("productVariantId")) .put("resources", row.getJsonArray("resources")) .put("productVariantName", row.getString("productVariantName")) .put("price", row.getFloat("price")) .put("expiryInMonths", row.getInteger("expiryInMonths"))); + removeRedundantKeys(row); + return productJson; + } + private void removeRedundantKeys(JsonObject row) { row.remove("productId"); row.remove("productVariantId"); row.remove("resources"); row.remove("price"); row.remove("expiryInMonths"); row.remove("productVariantName"); - return productJson; } } diff --git a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java index 03327a64..51c5a652 100644 --- a/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java +++ b/src/main/java/iudx/data/marketplace/consumer/ConsumerService.java @@ -32,7 +32,7 @@ static ConsumerService createProxy(Vertx vertx, String address) { * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler - * @return ConsumerService which ia service + * @return ConsumerService which is a service */ @Fluent ConsumerService listResources( @@ -44,7 +44,7 @@ ConsumerService listResources( * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler - * @return ConsumerService which ia service + * @return ConsumerService which is a service */ @Fluent ConsumerService listProviders( @@ -56,7 +56,7 @@ ConsumerService listProviders( * @param consumer as User object * @param request which is a JsonObject * @param handler which is a Request Handler - * @return ConsumerService which ia service + * @return ConsumerService which is a service */ @Fluent ConsumerService listProducts( @@ -65,10 +65,10 @@ ConsumerService listProducts( /** * The createOrder method creates an order for the consumer against a product variant * - * @param request + * @param request to Create order as Json object containing product variant ID * @param user Consumer User - * @param handler - * @return + * @param handler which is a Request Handler + * @return ConsumerService which is a service */ @Fluent ConsumerService createOrder( @@ -96,7 +96,7 @@ ConsumerService listProductVariants( * @param user Consumer user * @param request query param if any * @param handler Asynchronous JsonObject handler that contains the list of purchases - * @return + * @return ConsumerService which is a service */ @Fluent ConsumerService listPurchase( diff --git a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java index 1cff6c50..fda17d14 100644 --- a/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/DeletePolicy.java @@ -54,7 +54,6 @@ private String getFailureResponse(JsonObject response, String detail) { public Future executeUpdateQuery(String query, UUID policyUuid, User user) { LOG.debug("inside executeUpdateQuery"); Promise promise = Promise.promise(); -// Tuple tuple = Tuple.of(policyUuid); JsonObject param = new JsonObject().put("$1", policyUuid.toString()); postgresService.executePreparedQuery( diff --git a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java index c62d4925..34845b54 100644 --- a/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java +++ b/src/main/java/iudx/data/marketplace/policies/VerifyPolicy.java @@ -71,7 +71,6 @@ public Future initiateVerifyPolicy(JsonObject request) { private Future checkExistingPoliciesForId( UUID itemId, UUID ownerId, String userEmailId) { -// Tuple selectTuples = Tuple.of(itemId, ownerId, Status.ACTIVE, userEmailId); String query; JsonObject params = diff --git a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java index 9857c374..c8076675 100644 --- a/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/ProductServiceImpl.java @@ -1,7 +1,6 @@ package iudx.data.marketplace.product; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.*; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.*; import static iudx.data.marketplace.apiserver.util.Constants.RESULTS; import static iudx.data.marketplace.common.Constants.*; import static iudx.data.marketplace.product.util.Constants.*; diff --git a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java index e2ece2a2..1e038481 100644 --- a/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java +++ b/src/main/java/iudx/data/marketplace/product/util/QueryBuilder.java @@ -19,8 +19,11 @@ public class QueryBuilder { public static final Logger LOGGER = LogManager.getLogger(QueryBuilder.class); - private String productTable, resourceTable, productResourceRelationTable, productVariantTable; - private Supplier supplier; + private final String productTable; + private final String resourceTable; + private final String productResourceRelationTable; + private final String productVariantTable; + private final Supplier supplier; public QueryBuilder(JsonArray tables) { this.productTable = tables.getString(0); @@ -38,38 +41,32 @@ public List buildCreateProductQueries(JsonObject request, JsonArray reso // Product Table entry queries.add( - new StringBuilder( - INSERT_PRODUCT_QUERY - .replace("$0", productTable) - .replace("$1", productId) - .replace("$2", providerId) - .replace("$3", providerName) - .replace("$4", Status.ACTIVE.toString())) - .toString()); + INSERT_PRODUCT_QUERY + .replace("$0", productTable) + .replace("$1", productId) + .replace("$2", providerId) + .replace("$3", providerName) + .replace("$4", Status.ACTIVE.toString())); // Resource Table entry resourceDetails.forEach( resource -> { queries.add( - new StringBuilder( - INSERT_RESOURCE_QUERY - .replace("$0", resourceTable) - .replace("$1", ((JsonObject) resource).getString(RESOURCE_ID)) - .replace("$2", ((JsonObject) resource).getString(RESOURCE_NAME)) - .replace("$3", providerId) - .replace("$4", providerName) - .replace("$5", request.getString(RESOURCE_SERVER)) - .replace("$6", ((JsonObject) resource).getString("accessPolicy"))) - .toString()); + INSERT_RESOURCE_QUERY + .replace("$0", resourceTable) + .replace("$1", ((JsonObject) resource).getString(RESOURCE_ID)) + .replace("$2", ((JsonObject) resource).getString(RESOURCE_NAME)) + .replace("$3", providerId) + .replace("$4", providerName) + .replace("$5", request.getString(RESOURCE_SERVER)) + .replace("$6", ((JsonObject) resource).getString("accessPolicy"))); // Product-Resource relationship table entry queries.add( - new StringBuilder( - INSERT_P_R_REL_QUERY - .replace("$0", productResourceRelationTable) - .replace("$1", productId) - .replace("$2", ((JsonObject) resource).getString(RESOURCE_ID))) - .toString()); + INSERT_P_R_REL_QUERY + .replace("$0", productResourceRelationTable) + .replace("$1", productId) + .replace("$2", ((JsonObject) resource).getString(RESOURCE_ID))); }); LOGGER.debug("Queries : " + queries); @@ -146,6 +143,19 @@ public String updateProductVariantStatusQuery(String productId, String variant) return query.toString(); } + public String updateProductVariantStatusQuery(String productVariantId) { + StringBuilder query = + new StringBuilder( + UPDATE_PV_STATUS_QUERY + .replace("$0", productVariantTable) + .replace("$1", productVariantId) + .replace("$3", Status.ACTIVE.toString()) + .replace("$4", Status.INACTIVE.toString())); + + LOGGER.debug("Query : " + query); + return query.toString(); + } + public String checkProductVariantExistence(String productId, String variantName) { StringBuilder query = new StringBuilder(CHECK_IF_PV_EXISTS.replace("$1", productId).replace("$2", variantName)); @@ -159,18 +169,7 @@ public String checkIfProductExists(String productId, String providerId) { return query.toString(); } - public String updateProductVariantStatusQuery(String productVariantId) { - StringBuilder query = - new StringBuilder( - UPDATE_PV_STATUS_QUERY - .replace("$0", productVariantTable) - .replace("$1", productVariantId) - .replace("$3", Status.ACTIVE.toString()) - .replace("$4", Status.INACTIVE.toString())); - LOGGER.debug("Query : " + query); - return query.toString(); - } public String selectProductVariant(String productId, String variantName) { StringBuilder query = diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java index 80e775b8..17961645 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantService.java @@ -84,7 +84,7 @@ ProductVariantService listProductVariants( * @param user Provider user * @param request query param if any * @param handler Asynchronous JsonObject handler that contains the list of purchases - * @return + * @return ProductVariantService which is a service */ @Fluent ProductVariantService listPurchase( diff --git a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java index 610d0e68..764098c8 100644 --- a/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/product/variant/ProductVariantServiceImpl.java @@ -106,7 +106,8 @@ public ProductVariantService createProductVariant( handler.handle(Future.failedFuture(failureMessage)); return; } - int i, j; + int i; + int j; for (i = 0; i < resources.size(); i++) { for (j = 0; j < resResources.size(); j++) { String reqId = resources.getJsonObject(i).getString(ID); @@ -163,8 +164,7 @@ private Future checkIfProductVariantExists(String productId, String var if (handler.succeeded()) { if (handler.result().getInteger("totalHits") != 0) { promise.complete(true); - } - else { + } else { promise.complete(false); } } else { diff --git a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java index 239370c6..eeb7f272 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java +++ b/src/main/java/iudx/data/marketplace/razorpay/RazorPayServiceImpl.java @@ -1,7 +1,7 @@ package iudx.data.marketplace.razorpay; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.ACCOUNT_TYPE; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.ACCOUNT_TYPE; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.FAILURE_MESSAGE; import static iudx.data.marketplace.product.util.Constants.*; import static iudx.data.marketplace.razorpay.Constants.*; diff --git a/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java b/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java index 1113d4de..24193f24 100644 --- a/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java +++ b/src/main/java/iudx/data/marketplace/razorpay/util/ErrorMessageBuilder.java @@ -1,6 +1,6 @@ package iudx.data.marketplace.razorpay.util; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.FAILURE_MESSAGE; import iudx.data.marketplace.common.ResponseUrn; import java.util.Map; diff --git a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestCreateLinkedAccount.java b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestCreateLinkedAccount.java index dfa55b22..5fb2f220 100644 --- a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestCreateLinkedAccount.java +++ b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestCreateLinkedAccount.java @@ -6,6 +6,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; +import iudx.data.marketplace.apiserver.provider.linkedaccount.CreateLinkedAccount; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.common.HttpStatusCode; @@ -24,7 +25,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -import static iudx.data.marketplace.apiserver.provider.linkedAccount.util.Constants.FAILURE_MESSAGE; +import static iudx.data.marketplace.apiserver.provider.linkedaccount.util.Constants.FAILURE_MESSAGE; import static iudx.data.marketplace.apiserver.util.Constants.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; diff --git a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestFetchLinkedAccount.java b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestFetchLinkedAccount.java index e66c33b5..72b1696c 100644 --- a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestFetchLinkedAccount.java +++ b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestFetchLinkedAccount.java @@ -7,6 +7,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; +import iudx.data.marketplace.apiserver.provider.linkedaccount.FetchLinkedAccount; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.common.HttpStatusCode; import iudx.data.marketplace.common.RespBuilder; diff --git a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestUpdateLinkedAccount.java b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestUpdateLinkedAccount.java index d365ee23..6e07d08d 100644 --- a/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestUpdateLinkedAccount.java +++ b/src/test/java/iudx/data/marketplace/apiserver/provider/linkedAccount/TestUpdateLinkedAccount.java @@ -7,6 +7,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; +import iudx.data.marketplace.apiserver.provider.linkedaccount.UpdateLinkedAccount; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.common.HttpStatusCode; diff --git a/src/test/java/iudx/data/marketplace/policy/TestCreatePolicy.java b/src/test/java/iudx/data/marketplace/policy/TestCreatePolicy.java index de6001f1..c105b065 100644 --- a/src/test/java/iudx/data/marketplace/policy/TestCreatePolicy.java +++ b/src/test/java/iudx/data/marketplace/policy/TestCreatePolicy.java @@ -7,8 +7,6 @@ import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; -import iudx.data.marketplace.apiserver.provider.linkedAccount.CreateLinkedAccount; -import iudx.data.marketplace.apiserver.provider.linkedAccount.TestCreateLinkedAccount; import iudx.data.marketplace.auditing.AuditingService; import iudx.data.marketplace.common.Api; import iudx.data.marketplace.policies.CreatePolicy; From ad845059e8cc3a6e18ce7f40ea83f3fb8978f588 Mon Sep 17 00:00:00 2001 From: shreelakshmijoshi Date: Wed, 13 Nov 2024 20:01:06 +0530 Subject: [PATCH 15/15] Refactor: minor change --- .../java/iudx/data/marketplace/apiserver/ConsumerApis.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java index 4e5c22d2..37fda18a 100644 --- a/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java +++ b/src/main/java/iudx/data/marketplace/apiserver/ConsumerApis.java @@ -278,15 +278,13 @@ private void handleSuccessResponse( .setStatusCode(statusCode) .end(result.toString()); break; - case 204: + default: //204 routingContext .response() .putHeader(CONTENT_TYPE, APPLICATION_JSON) .setStatusCode(statusCode) .end(); break; - default: - break; } }