diff --git a/Jenkinsfile b/Jenkinsfile index 1cf7aed..f4b4cd1 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -38,8 +38,20 @@ pipeline { } post{ always { - recordIssues enabledForFailure: true, tool: checkStyle(pattern: 'target/checkstyle-result.xml') - recordIssues enabledForFailure: true, tool: pmdParser(pattern: 'target/pmd.xml') + recordIssues( + enabledForFailure: true, + blameDisabled: true, + forensicsDisabled: true, + qualityGates: [[threshold:0, type: 'TOTAL', unstable: false]], + tool: checkStyle(pattern: 'target/checkstyle-result.xml') + ) + recordIssues( + enabledForFailure: true, + blameDisabled: true, + forensicsDisabled: true, + qualityGates: [[threshold:0, type: 'TOTAL', unstable: false]], + tool: pmdParser(pattern: 'target/pmd.xml') + ) } failure{ script{ diff --git a/src/main/java/iudx/gis/server/apiserver/ApiServerVerticle.java b/src/main/java/iudx/gis/server/apiserver/ApiServerVerticle.java index 69ad570..417db15 100644 --- a/src/main/java/iudx/gis/server/apiserver/ApiServerVerticle.java +++ b/src/main/java/iudx/gis/server/apiserver/ApiServerVerticle.java @@ -8,8 +8,6 @@ import static iudx.gis.server.common.Constants.PG_SERVICE_ADDRESS; import io.vertx.core.AbstractVerticle; -import io.vertx.core.Future; -import io.vertx.core.Promise; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; @@ -37,9 +35,6 @@ import iudx.gis.server.common.Api; import iudx.gis.server.database.postgres.PostgresService; import iudx.gis.server.metering.MeteringService; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoUnit; import java.util.HashSet; import java.util.Set; import org.apache.logging.log4j.LogManager; @@ -60,21 +55,16 @@ public class ApiServerVerticle extends AbstractVerticle { validHeaders.add("Content-Type"); } + public String dxApiBasePath; + public String adminBasePath; private HttpServer server; private Router router; private int port; - private boolean isSSL; + private boolean isssl; private String keystore; private String keystorePassword; - private CatalogueService catalogueService; - private MeteringService meteringService; // private DatabaseService database; private PostgresService postgresService; - private AuthenticationService authenticator; - public String dxApiBasePath; - public String adminBasePath; - private String dxCatalogueBasePath; - private String dxAuthBasePath; @Override public void start() throws Exception { @@ -96,9 +86,8 @@ public void start() throws Exception { dxApiBasePath = config().getString("dxApiBasePath"); adminBasePath = config().getString("adminBasePath"); - dxCatalogueBasePath = config().getString("dxCatalogueBasePath"); - dxAuthBasePath = config().getString("dxAuthBasePath"); - Api api = Api.getInstance(dxApiBasePath,adminBasePath); + config().getString("dxCatalogueBasePath"); + config().getString("dxAuthBasePath"); router = Router.router(vertx); router @@ -121,10 +110,10 @@ public void start() throws Exception { router.route().handler(BodyHandler.create()); /* Read ssl configuration. */ - isSSL = config().getBoolean("ssl"); + isssl = config().getBoolean("ssl"); HttpServerOptions serverOptions = new HttpServerOptions(); - if (isSSL) { + if (isssl) { /* Read the configuration and set the HTTPs server properties. */ @@ -160,9 +149,10 @@ public void start() throws Exception { server.requestHandler(router).listen(port); /* Get a handler for the Service Discovery interface. */ - authenticator = AuthenticationService.createProxy(vertx, AUTHENTICATION_SERVICE_ADDRESS); - meteringService = MeteringService.createProxy(vertx, METERING_SERVICE_ADDRESS); + AuthenticationService.createProxy(vertx, AUTHENTICATION_SERVICE_ADDRESS); + MeteringService.createProxy(vertx, METERING_SERVICE_ADDRESS); postgresService = PostgresService.createProxy(vertx, PG_SERVICE_ADDRESS); + Api api = Api.getInstance(dxApiBasePath, adminBasePath); ValidationHandler entityQueryValidationHandler = new ValidationHandler(vertx, RequestType.ENTITY_QUERY); @@ -171,7 +161,7 @@ public void start() throws Exception { router .get(api.getEntitiesEndpoint()) .handler(entityQueryValidationHandler) - .handler(AuthHandler.create(vertx,config())) + .handler(AuthHandler.create(vertx, config())) .handler(this::handleEntitiesQuery) .failureHandler(validationsFailureHandler); @@ -184,21 +174,21 @@ public void start() throws Exception { router .post(api.getAdminPath()) .handler(adminCrudPathValidationHandler) - .handler(AuthHandler.create(vertx,config())) + .handler(AuthHandler.create(vertx, config())) .handler(this::handlePostAdminPath) .failureHandler(validationsFailureHandler); router .put(api.getAdminPath()) .handler(adminCrudPathValidationHandler) - .handler(AuthHandler.create(vertx,config())) + .handler(AuthHandler.create(vertx, config())) .handler(this::handlePutAdminPath) .failureHandler(validationsFailureHandler); router .delete(api.getAdminPath()) .handler(adminCrudPathIdValidationHandler) - .handler(AuthHandler.create(vertx,config())) + .handler(AuthHandler.create(vertx, config())) .handler(this::handleDeleteAdminPath) .failureHandler(validationsFailureHandler); router @@ -231,19 +221,20 @@ public void start() throws Exception { .end(generateResponse(HttpStatusCode.NOT_FOUND, YET_NOT_IMPLEMENTED)); }); - catalogueService = new CatalogueService(vertx, config()); + new CatalogueService(vertx, config()); /* Print the deployed endpoints */ printDeployedEndpoints(router); - } + private void printDeployedEndpoints(Router router) { - for(Route route:router.getRoutes()) { - if(route.getPath() != null) { + for (Route route : router.getRoutes()) { + if (route.getPath() != null) { LOGGER.info("API Endpoints deployed : " + route.methods() + " : " + route.getPath()); } } } + private void handleDeleteAdminPath(RoutingContext routingContext) { LOGGER.trace("Info:handleDeleteAdminPath method started.;"); HttpServerResponse response = routingContext.response(); @@ -252,27 +243,31 @@ private void handleDeleteAdminPath(RoutingContext routingContext) { String adminDetailsQuery = PgsqlQueryBuilder.getAdminDetailsQuery(resourceId); String deleteAdminDetailsQuery = PgsqlQueryBuilder.deleteAdminDetailsQuery(resourceId); - postgresService.executeQuery(adminDetailsQuery, selectHandler -> { - if (selectHandler.succeeded()) { - JsonObject result = selectHandler.result(); - JsonArray rows = result.getJsonArray("result"); - if (rows.size() < 1) { - handleResponse(response, HttpStatusCode.NOT_FOUND, ResponseUrn.RESOURCE_NOT_FOUND); - } else { - postgresService.executeQuery(deleteAdminDetailsQuery, deleteHandler -> { - if (deleteHandler.succeeded()) { - handleResponse(response, HttpStatusCode.SUCCESS, ResponseUrn.SUCCESS); - routingContext.data().put(RESPONSE_SIZE, 0); - //Future.future(fu -> updateAuditTable(routingContext)); + postgresService.executeQuery( + adminDetailsQuery, + selectHandler -> { + if (selectHandler.succeeded()) { + JsonObject result = selectHandler.result(); + JsonArray rows = result.getJsonArray("result"); + if (rows.size() < 1) { + handleResponse(response, HttpStatusCode.NOT_FOUND, ResponseUrn.RESOURCE_NOT_FOUND); } else { - LOGGER.info("insert failed :{}", deleteHandler.cause().getMessage()); + postgresService.executeQuery( + deleteAdminDetailsQuery, + deleteHandler -> { + if (deleteHandler.succeeded()) { + handleResponse(response, HttpStatusCode.SUCCESS, ResponseUrn.SUCCESS); + routingContext.data().put(RESPONSE_SIZE, 0); + // Future.future(fu -> updateAuditTable(routingContext)); + } else { + LOGGER.info("insert failed :{}", deleteHandler.cause().getMessage()); + } + }); } - }); - } - } else { - LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); - } - }); + } else { + LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); + } + }); } private void handlePutAdminPath(RoutingContext routingContext) { @@ -286,28 +281,31 @@ private void handlePutAdminPath(RoutingContext routingContext) { String adminDetailsQuery = PgsqlQueryBuilder.getAdminDetailsQuery(resourceId); String updateAdminDetailsQuery = PgsqlQueryBuilder.updateAdminDetailsQuery(requestBody); - - postgresService.executeQuery(adminDetailsQuery, selectHandler -> { - if (selectHandler.succeeded()) { - JsonObject result = selectHandler.result(); - JsonArray rows = result.getJsonArray("result"); - if (rows.size() < 1) { - handleResponse(response, HttpStatusCode.NOT_FOUND, ResponseUrn.RESOURCE_NOT_FOUND); - } else { - postgresService.executeQuery(updateAdminDetailsQuery, updateHandler -> { - if (updateHandler.succeeded()) { - handleResponse(response, HttpStatusCode.SUCCESS, ResponseUrn.SUCCESS); - routingContext.data().put(RESPONSE_SIZE, 0); - //Future.future(fu -> updateAuditTable(routingContext)); + postgresService.executeQuery( + adminDetailsQuery, + selectHandler -> { + if (selectHandler.succeeded()) { + JsonObject result = selectHandler.result(); + JsonArray rows = result.getJsonArray("result"); + if (rows.size() < 1) { + handleResponse(response, HttpStatusCode.NOT_FOUND, ResponseUrn.RESOURCE_NOT_FOUND); } else { - LOGGER.info("insert failed :{}", updateHandler.cause().getMessage()); + postgresService.executeQuery( + updateAdminDetailsQuery, + updateHandler -> { + if (updateHandler.succeeded()) { + handleResponse(response, HttpStatusCode.SUCCESS, ResponseUrn.SUCCESS); + routingContext.data().put(RESPONSE_SIZE, 0); + // Future.future(fu -> updateAuditTable(routingContext)); + } else { + LOGGER.info("insert failed :{}", updateHandler.cause().getMessage()); + } + }); } - }); - } - } else { - LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); - } - }); + } else { + LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); + } + }); } private void handlePostAdminPath(RoutingContext routingContext) { @@ -320,34 +318,37 @@ private void handlePostAdminPath(RoutingContext routingContext) { String adminDetailsQuery = PgsqlQueryBuilder.getAdminDetailsQuery(resourceId); String insertAdminDetailsQuery = PgsqlQueryBuilder.insertAdminDetailsQuery(requestBody); - - postgresService.executeQuery(adminDetailsQuery, selectHandler -> { - if (selectHandler.succeeded()) { - JsonObject result = selectHandler.result(); - JsonArray rows = result.getJsonArray("result"); - if (rows.size() > 0) { - handleResponse(response, HttpStatusCode.CONFLICT, ResponseUrn.RESOURCE_ALREADY_EXISTS); - } else { - postgresService.executeQuery(insertAdminDetailsQuery, insertHandler -> { - if (insertHandler.succeeded()) { - handleResponse(response, HttpStatusCode.CREATED, ResponseUrn.CREATED); - routingContext.data().put(RESPONSE_SIZE, 0); - //Future.future(fu -> updateAuditTable(routingContext)); + postgresService.executeQuery( + adminDetailsQuery, + selectHandler -> { + if (selectHandler.succeeded()) { + JsonObject result = selectHandler.result(); + JsonArray rows = result.getJsonArray("result"); + if (rows.size() > 0) { + handleResponse( + response, HttpStatusCode.CONFLICT, ResponseUrn.RESOURCE_ALREADY_EXISTS); } else { - LOGGER.info("insert failed :{}", insertHandler.cause().getMessage()); + postgresService.executeQuery( + insertAdminDetailsQuery, + insertHandler -> { + if (insertHandler.succeeded()) { + handleResponse(response, HttpStatusCode.CREATED, ResponseUrn.CREATED); + routingContext.data().put(RESPONSE_SIZE, 0); + // Future.future(fu -> updateAuditTable(routingContext)); + } else { + LOGGER.info("insert failed :{}", insertHandler.cause().getMessage()); + } + }); } - }); - } - } else { - LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); - } - }); + } else { + LOGGER.info("select failed :{}", selectHandler.cause().getMessage()); + } + }); } private void handleEntitiesQuery(RoutingContext routingContext) { LOGGER.trace("Info:handleEntitiesQuery method started.;"); /* Handles HTTP request from client */ - JsonObject authInfo = (JsonObject) routingContext.data().get("authInfo"); HttpServerRequest request = routingContext.request(); /* Handles HTTP response from server to client */ HttpServerResponse response = routingContext.response(); @@ -363,7 +364,7 @@ private void handleEntitiesQuery(RoutingContext routingContext) { * Execute a search query in DB * * @param json valid json query - * @param response + * @param response HttpServerResponse */ private void executeSearchQuery( RoutingContext context, JsonObject json, HttpServerResponse response) { @@ -371,17 +372,19 @@ private void executeSearchQuery( String id = json.getString("id"); String query = PgsqlQueryBuilder.getAdminDetailsQuery(id); - postgresService.executeQuery(query, handler -> { - if (handler.succeeded()) { - LOGGER.debug("Success: Search Success"); - handleSuccessResponse(response, ResponseType.Ok.getCode(), handler.result()); - context.data().put(RESPONSE_SIZE, response.bytesWritten()); - //Future.future(fu -> updateAuditTable(context)); - } else if (handler.failed()) { - LOGGER.error("Fail: Search Fail"); - processBackendResponse(response, handler.cause().getMessage()); - } - }); + postgresService.executeQuery( + query, + handler -> { + if (handler.succeeded()) { + LOGGER.debug("Success: Search Success"); + handleSuccessResponse(response, ResponseType.Ok.getCode(), handler.result()); + context.data().put(RESPONSE_SIZE, response.bytesWritten()); + // Future.future(fu -> updateAuditTable(context)); + } else if (handler.failed()) { + LOGGER.error("Fail: Search Fail"); + processBackendResponse(response, handler.cause().getMessage()); + } + }); } private void handleSuccessResponse( @@ -441,37 +444,4 @@ private String generateResponse(HttpStatusCode statusCode, ResponseUrn urn, Stri .put(JSON_DETAIL, message) .toString(); } - - - private Future updateAuditTable(RoutingContext context) { - Promise promise = Promise.promise(); - JsonObject authInfo = (JsonObject) context.data().get("authInfo"); - - ZonedDateTime zst = ZonedDateTime.now(ZoneId.of("Asia/Kolkata")); - long time = zst.toInstant().toEpochMilli(); - String isoTime = zst.truncatedTo(ChronoUnit.SECONDS).toString(); - - JsonObject request = new JsonObject(); - request.put(EPOCH_TIME, time); - request.put(ISO_TIME, isoTime); - request.put(USER_ID, authInfo.getValue(USER_ID)); - request.put(IID,authInfo.getValue(IID)); - request.put(ID, authInfo.getValue(ID)); - request.put(API, authInfo.getValue(API_ENDPOINT)); - request.put(RESPONSE_SIZE, context.data().get(RESPONSE_SIZE)); - - meteringService.insertMeteringValuesInRMQ( - request, - handler -> { - if (handler.succeeded()) { - LOGGER.debug("inserted into rmq"); - promise.complete(); - } else { - LOGGER.error("failed to insert into rmq "+handler.result()); - promise.complete(); - } - }); - - return promise.future(); - } } diff --git a/src/main/java/iudx/gis/server/apiserver/handlers/AuthHandler.java b/src/main/java/iudx/gis/server/apiserver/handlers/AuthHandler.java index ef3905f..57e1e06 100644 --- a/src/main/java/iudx/gis/server/apiserver/handlers/AuthHandler.java +++ b/src/main/java/iudx/gis/server/apiserver/handlers/AuthHandler.java @@ -21,16 +21,16 @@ public class AuthHandler implements Handler { private static final String AUTH_SERVICE_ADDRESS = "iudx.gis.authentication.service"; private static final Logger LOGGER = LogManager.getLogger(AuthHandler.class); static AuthenticationService authenticator; - private HttpServerRequest request; private static String dxApiBasePath; private static String adminBasePath; private static Api api; + private HttpServerRequest request; public static AuthHandler create(Vertx vertx, JsonObject config) { authenticator = AuthenticationService.createProxy(vertx, AUTH_SERVICE_ADDRESS); dxApiBasePath = config.getString("dxApiBasePath"); adminBasePath = config.getString("adminBasePath"); - api = Api.getInstance(dxApiBasePath,adminBasePath); + api = Api.getInstance(dxApiBasePath, adminBasePath); return new AuthHandler(); } @@ -50,7 +50,9 @@ public void handle(RoutingContext context) { final String path = getNormalizedPath(request.path()); final String method = context.request().method().toString(); - if (token == null) token = "public"; + if (token == null) { + token = "public"; + } String paramId = getId4rmRequest(); @@ -108,12 +110,14 @@ public void processAuthFailure(RoutingContext ctx, String result) { public String getNormalizedPath(String url) { LOGGER.debug("URL : {}", url); String path = null; - if (url.matches(api.getEntitiesEndpoint())) path = api.getEntitiesEndpoint(); - else if (url.matches(api.getAdminPath())) path = api.getAdminPath(); + if (url.matches(api.getEntitiesEndpoint())) { + path = api.getEntitiesEndpoint(); + } else if (url.matches(api.getAdminPath())) { + path = api.getAdminPath(); + } return path; } - private String getId4rmRequest() { return request.getParam(ID); } diff --git a/src/main/java/iudx/gis/server/apiserver/handlers/ValidationFailureHandler.java b/src/main/java/iudx/gis/server/apiserver/handlers/ValidationFailureHandler.java index 44b8e9f..d21d269 100644 --- a/src/main/java/iudx/gis/server/apiserver/handlers/ValidationFailureHandler.java +++ b/src/main/java/iudx/gis/server/apiserver/handlers/ValidationFailureHandler.java @@ -8,7 +8,6 @@ import static iudx.gis.server.apiserver.util.Constants.MSG_BAD_QUERY; import io.vertx.core.Handler; -import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import iudx.gis.server.apiserver.exceptions.DxRuntimeException; @@ -31,14 +30,16 @@ public void handle(RoutingContext context) { LOGGER.error(exception.getUrn().getUrn() + " : " + exception.getMessage()); HttpStatusCode code = HttpStatusCode.getByValue(exception.getStatusCode()); - JsonObject response = new RestResponse.Builder() - .withType(exception.getUrn().getUrn()) - .withTitle(code.getDescription()) - .withMessage(exception.getLocalizedMessage()) - .build() - .toJson(); + JsonObject response = + new RestResponse.Builder() + .withType(exception.getUrn().getUrn()) + .withTitle(code.getDescription()) + .withMessage(exception.getLocalizedMessage()) + .build() + .toJson(); - context.response() + context + .response() .putHeader(CONTENT_TYPE, APPLICATION_JSON) .setStatusCode(exception.getStatusCode()) .end(response.toString()); @@ -46,13 +47,13 @@ public void handle(RoutingContext context) { if (failure instanceof RuntimeException) { - context.response() + context + .response() .putHeader(CONTENT_TYPE, APPLICATION_JSON) .setStatusCode(HttpStatus.SC_BAD_REQUEST) - .end( validationFailureResponse().toString()); + .end(validationFailureResponse().toString()); } context.next(); - return; } private JsonObject validationFailureResponse() { diff --git a/src/main/java/iudx/gis/server/apiserver/handlers/ValidationHandler.java b/src/main/java/iudx/gis/server/apiserver/handlers/ValidationHandler.java index 164c6e8..476b41b 100644 --- a/src/main/java/iudx/gis/server/apiserver/handlers/ValidationHandler.java +++ b/src/main/java/iudx/gis/server/apiserver/handlers/ValidationHandler.java @@ -8,13 +8,12 @@ import iudx.gis.server.apiserver.util.RequestType; import iudx.gis.server.apiserver.validation.ValidatorsHandlersFactory; import iudx.gis.server.apiserver.validation.types.Validator; -import org.apache.http.HttpStatus; -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 { @@ -22,7 +21,6 @@ public class ValidationHandler implements Handler { private Vertx vertx; private RequestType type; - public ValidationHandler(Vertx vertx, RequestType type) { this.vertx = vertx; this.type = type; @@ -42,10 +40,8 @@ public void handle(RoutingContext context) { for (Validator validator : Optional.ofNullable(validations).orElse(Collections.emptyList())) { LOGGER.debug("validator :" + validator.getClass().getName()); - validator.isValid(); + validator.isValid(); } context.next(); - return; } - } diff --git a/src/main/java/iudx/gis/server/apiserver/query/PgsqlQueryBuilder.java b/src/main/java/iudx/gis/server/apiserver/query/PgsqlQueryBuilder.java index 137a0b5..a10d5fc 100644 --- a/src/main/java/iudx/gis/server/apiserver/query/PgsqlQueryBuilder.java +++ b/src/main/java/iudx/gis/server/apiserver/query/PgsqlQueryBuilder.java @@ -9,8 +9,9 @@ import static iudx.gis.server.database.util.Constants.SERVER_URL; import static iudx.gis.server.database.util.Constants.TOKEN_URL; import static iudx.gis.server.database.util.Constants.USERNAME; -import java.util.Optional; + import io.vertx.core.json.JsonObject; +import java.util.Optional; public class PgsqlQueryBuilder { @@ -27,10 +28,12 @@ public static String insertAdminDetailsQuery(JsonObject queryParams) { Optional accessInfo = Optional.ofNullable(queryParams.getJsonObject(ACCESS_INFO)); - String insertQuery = INSERT_ADMIN_DETAILS_QUERY.replace("$1", resourceId) - .replace("$2", serverUrl) - .replace("$3", serverPort.toString()) - .replace("$4", isSecure.toString()); + String insertQuery = + INSERT_ADMIN_DETAILS_QUERY + .replace("$1", resourceId) + .replace("$2", serverUrl) + .replace("$3", serverPort.toString()) + .replace("$4", isSecure.toString()); if (accessInfo.isPresent() && !accessInfo.get().isEmpty()) { JsonObject accessObject = accessInfo.get(); @@ -55,10 +58,12 @@ public static String updateAdminDetailsQuery(JsonObject queryParams) { Optional accessInfo = Optional.ofNullable(queryParams.getJsonObject(ACCESS_INFO)); - String updateQuery=UPDATE_ADMIN_DETAILS_QUERY.replace("$1", serverUrl) - .replace("$2", serverPort.toString()) - .replace("$3", isSecure.toString()) - .replace("$6", resourceId); + String updateQuery = + UPDATE_ADMIN_DETAILS_QUERY + .replace("$1", serverUrl) + .replace("$2", serverPort.toString()) + .replace("$3", isSecure.toString()) + .replace("$6", resourceId); if (accessInfo.isPresent() && !accessInfo.get().isEmpty()) { JsonObject accessObject = accessInfo.get(); @@ -66,16 +71,15 @@ public static String updateAdminDetailsQuery(JsonObject queryParams) { String password = accessObject.getString(PASSWORD); String tokenUrl = accessObject.getString(TOKEN_URL); updateQuery = - updateQuery.replace("$4", username).replace("$5", password).replace("$7", tokenUrl);; + updateQuery.replace("$4", username).replace("$5", password).replace("$7", tokenUrl); } else { updateQuery = updateQuery.replace("$4", "").replace("$5", "").replace("$7", ""); } - + return updateQuery; } - + public static String deleteAdminDetailsQuery(String resourceId) { return DELETE_ADMIN_DETAILS_QUERY.replace("$1", resourceId); } - } diff --git a/src/main/java/iudx/gis/server/apiserver/response/ResponseType.java b/src/main/java/iudx/gis/server/apiserver/response/ResponseType.java index b65d89d..1615fc3 100644 --- a/src/main/java/iudx/gis/server/apiserver/response/ResponseType.java +++ b/src/main/java/iudx/gis/server/apiserver/response/ResponseType.java @@ -1,6 +1,5 @@ package iudx.gis.server.apiserver.response; -import java.util.stream.Stream; public enum ResponseType { Ok(200, "Ok"), diff --git a/src/main/java/iudx/gis/server/apiserver/response/ResponseUrn.java b/src/main/java/iudx/gis/server/apiserver/response/ResponseUrn.java index f702964..a0a9365 100644 --- a/src/main/java/iudx/gis/server/apiserver/response/ResponseUrn.java +++ b/src/main/java/iudx/gis/server/apiserver/response/ResponseUrn.java @@ -8,7 +8,7 @@ public enum ResponseUrn { INVALID_ATTR_PARAM("urn:dx:rs:invalidAttributeParam", "Invalid attribute param"), INVALID_ATTR_VALUE("urn:dx:rs:invalidAttributeValue", "Invalid attribute value"), INVALID_OPERATION("urn:dx:rs:invalidOperation", "Invalid operation"), - BAD_REQUEST_URN("urn:dx:rs:badRequest","bad request parameter"), + BAD_REQUEST_URN("urn:dx:rs:badRequest", "bad request parameter"), UNAUTHORIZED_ENDPOINT("urn:dx:rs:unauthorizedEndpoint", "Access to endpoint is not available"), UNAUTHORIZED_RESOURCE("urn:dx:rs:unauthorizedResource", "Access to resource is not available"), EXPIRED_TOKEN("urn:dx:rs:expiredAuthorizationToken", "Token has expired"), @@ -17,15 +17,23 @@ public enum ResponseUrn { RESOURCE_ALREADY_EXISTS("urn:dx:rs:resourceAlreadyExists", "Document of given ID already exists"), - INVALID_PAYLOAD_FORMAT("urn:dx:rs:invalidPayloadFormat", "Invalid json format in post request [schema mismatch]"), + INVALID_PAYLOAD_FORMAT( + "urn:dx:rs:invalidPayloadFormat", "Invalid json format in post request [schema mismatch]"), RESOURCE_NOT_FOUND("urn:dx:rs:resourceNotFound", "Document of given id does not exist"), METHOD_NOT_FOUND("urn:dx:rs:MethodNotAllowed", "Method not allowed for given endpoint"), - UNSUPPORTED_MEDIA_TYPE("urn:dx:rs:UnsupportedMediaType", "Requested/Presented media type not supported"), + UNSUPPORTED_MEDIA_TYPE( + "urn:dx:rs:UnsupportedMediaType", "Requested/Presented media type not supported"), - RESPONSE_PAYLOAD_EXCEED("urn:dx:rs:responsePayloadLimitExceeded", "Search operations exceeds the default response payload limit"), - REQUEST_PAYLOAD_EXCEED("urn:dx:rs:requestPayloadLimitExceeded", "Operation exceeds the default request payload limit"), - REQUEST_OFFSET_EXCEED("urn:dx:rs:requestOffsetLimitExceeded", "Operation exceeds the default value of offset"), - REQUEST_LIMIT_EXCEED("urn:dx:rs:requestLimitExceeded", "Operation exceeds the default value of limit"), + RESPONSE_PAYLOAD_EXCEED( + "urn:dx:rs:responsePayloadLimitExceeded", + "Search operations exceeds the default response payload limit"), + REQUEST_PAYLOAD_EXCEED( + "urn:dx:rs:requestPayloadLimitExceeded", + "Operation exceeds the default request payload limit"), + REQUEST_OFFSET_EXCEED( + "urn:dx:rs:requestOffsetLimitExceeded", "Operation exceeds the default value of offset"), + REQUEST_LIMIT_EXCEED( + "urn:dx:rs:requestLimitExceeded", "Operation exceeds the default value of limit"), BACKING_SERVICE_FORMAT("urn:dx:rs:backend", "format error from backing service [cat,auth etc.]"), @@ -39,6 +47,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); /* If backend services don't respond with URN */ + } + public String getUrn() { return urn; } @@ -47,13 +62,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); /* If backend services don't respond with URN */ - } - public String toString() { return "[" + urn + " : " + message + " ]"; } diff --git a/src/main/java/iudx/gis/server/apiserver/service/CatalogueService.java b/src/main/java/iudx/gis/server/apiserver/service/CatalogueService.java index 974896a..105856b 100644 --- a/src/main/java/iudx/gis/server/apiserver/service/CatalogueService.java +++ b/src/main/java/iudx/gis/server/apiserver/service/CatalogueService.java @@ -1,5 +1,8 @@ package iudx.gis.server.apiserver.service; +import static iudx.gis.server.authenticator.Constants.CAT_ITEM_PATH; +import static iudx.gis.server.authenticator.Constants.CAT_SEARCH_PATH; + import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import io.vertx.core.Future; @@ -13,36 +16,28 @@ import io.vertx.ext.web.client.WebClientOptions; import io.vertx.ext.web.client.predicate.ResponsePredicate; import iudx.gis.server.authenticator.Constants; +import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static iudx.gis.server.authenticator.Constants.CAT_ITEM_PATH; -import static iudx.gis.server.authenticator.Constants.CAT_SEARCH_PATH; - public class CatalogueService { private static final Logger LOGGER = LogManager.getLogger(CatalogueService.class); public static WebClient catWebClient; - private long cacheGroupTimerId; - private long cacheResTimerId; private static String catHost; private static int catPort; private static String catSearchPath; private static String catItemPath; + private final Cache groupCache = + CacheBuilder.newBuilder() + .maximumSize(1000) + .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES) + .build(); + /*private final Cache idCache = CacheBuilder.newBuilder().maximumSize(1000) + .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES).build();*/ private String catBasePath; - private Vertx vertx; - - private final Cache idCache = CacheBuilder.newBuilder().maximumSize(1000) - .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES).build(); - - private final Cache groupCache = CacheBuilder.newBuilder().maximumSize(1000) - .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES).build(); public CatalogueService(Vertx vertx, JsonObject config) { - this.vertx = vertx; catHost = config.getString("catServerHost"); catPort = config.getInteger("catServerPort"); catBasePath = config.getString("dxCatalogueBasePath"); @@ -51,64 +46,80 @@ public CatalogueService(Vertx vertx, JsonObject config) { WebClientOptions options = new WebClientOptions().setTrustAll(true).setVerifyHost(false).setSsl(true); - if (catWebClient==null) { + if (catWebClient == null) { catWebClient = WebClient.create(vertx, options); } - //populateGroupCache(catWebClient).onComplete(handler -> populateResourceCache(catWebClient)); + // populateGroupCache(catWebClient).onComplete(handler -> populateResourceCache(catWebClient)); populateGroupCache(catWebClient); - cacheGroupTimerId = vertx.setPeriodic(TimeUnit.DAYS.toMillis(1), handler -> { - populateGroupCache(catWebClient); - }); + vertx.setPeriodic( + TimeUnit.DAYS.toMillis(1), + handler -> { + populateGroupCache(catWebClient); + }); - cacheResTimerId = vertx.setPeriodic(TimeUnit.DAYS.toMillis(1), handler -> { - populateResourceCache(catWebClient); - }); + vertx.setPeriodic( + TimeUnit.DAYS.toMillis(1), + handler -> { + populateResourceCache(catWebClient); + }); } public Future populateGroupCache(WebClient client) { Promise promise = Promise.promise(); - catWebClient.get(catPort, catHost, catSearchPath).addQueryParam("property", "[type]") + catWebClient + .get(catPort, catHost, catSearchPath) + .addQueryParam("property", "[type]") .addQueryParam("value", "[[iudx:ResourceGroup]]") - .addQueryParam("filter", "[accessPolicy,id]").expect(ResponsePredicate.JSON) - .send(handler -> { - if (handler.succeeded()) { - JsonArray response = handler.result().bodyAsJsonObject().getJsonArray("results"); - response.forEach(json -> { - JsonObject res = (JsonObject) json; - String id = res.getString("id"); - String[] idArray = id.split("/"); - groupCache.put(id, res.getString("accessPolicy", "SECURE")); + .addQueryParam("filter", "[accessPolicy,id]") + .expect(ResponsePredicate.JSON) + .send( + handler -> { + if (handler.succeeded()) { + JsonArray response = handler.result().bodyAsJsonObject().getJsonArray("results"); + response.forEach( + json -> { + JsonObject res = (JsonObject) json; + String id = res.getString("id"); + String[] idArray = id.split("/"); + groupCache.put(id, res.getString("accessPolicy", "SECURE")); + }); + LOGGER.debug("Cache has been populated!"); + LOGGER.debug(groupCache.size()); + promise.complete(true); + } else if (handler.failed()) { + promise.fail(handler.cause()); + } }); - LOGGER.debug("Cache has been populated!"); - LOGGER.debug(groupCache.size()); - promise.complete(true); - } else if (handler.failed()) { - promise.fail(handler.cause()); - } - }); return promise.future(); } public Future populateResourceCache(WebClient client) { Promise promise = Promise.promise(); - catWebClient.get(catPort, catHost, catSearchPath).addQueryParam("property", "[type]") - .addQueryParam("value", "[[iudx:Resource]]").addQueryParam("filter", "[accessPolicy,id]") - .expect(ResponsePredicate.JSON).send(handler -> { - if (handler.succeeded()) { - JsonArray response = handler.result().bodyAsJsonObject().getJsonArray("results"); - response.forEach(json -> { - JsonObject res = (JsonObject) json; - String id = res.getString("id"); - String groupId = id.substring(0, id.lastIndexOf("/")); - //idCache.put(id, res.getString("accessPolicy", groupCache.getIfPresent(groupId))); + catWebClient + .get(catPort, catHost, catSearchPath) + .addQueryParam("property", "[type]") + .addQueryParam("value", "[[iudx:Resource]]") + .addQueryParam("filter", "[accessPolicy,id]") + .expect(ResponsePredicate.JSON) + .send( + handler -> { + if (handler.succeeded()) { + JsonArray response = handler.result().bodyAsJsonObject().getJsonArray("results"); + response.forEach( + json -> { + // JsonObject res = (JsonObject) json; + // String id = res.getString("id"); + // String groupId = id.substring(0, id.lastIndexOf("/")); + // idCache.put(id, res.getString("accessPolicy", + // groupCache.getIfPresent(groupId))); + }); + promise.complete(true); + } else if (handler.failed()) { + promise.fail(handler.cause()); + } }); - promise.complete(true); - } else if (handler.failed()) { - promise.fail(handler.cause()); - } - }); return promise.future(); } @@ -162,30 +173,35 @@ private List toList(JsonArray arr) { return (List) arr.getList(); } }*/ - + public Future isItemExist(String id) { LOGGER.trace("isItemExist() started"); Promise promise = Promise.promise(); - catWebClient.get(catPort, catHost, catItemPath).addQueryParam("id", id) - .expect(ResponsePredicate.JSON).send(responseHandler -> { - if (responseHandler.succeeded()) { - HttpResponse response = responseHandler.result(); - JsonObject responseBody = response.bodyAsJsonObject(); - if (responseBody.getString("type").equalsIgnoreCase("urn:dx:cat:Success") - && responseBody.getInteger("totalHits") > 0) { - promise.complete(responseHandler.succeeded()); - /*if(responseBody.getJsonArray("results").getJsonObject(0).getJsonArray("type").contains("iudx:Resource")) { - promise.complete(true); + catWebClient + .get(catPort, catHost, catItemPath) + .addQueryParam("id", id) + .expect(ResponsePredicate.JSON) + .send( + responseHandler -> { + if (responseHandler.succeeded()) { + HttpResponse response = responseHandler.result(); + JsonObject responseBody = response.bodyAsJsonObject(); + if (responseBody.getString("type").equalsIgnoreCase("urn:dx:cat:Success") + && responseBody.getInteger("totalHits") > 0) { + promise.complete(responseHandler.succeeded()); + /*if(responseBody.getJsonArray("results").getJsonObject(0) + .getJsonArray("type").contains("iudx:Resource")) { + promise.complete(true); + } else { + promise.fail(responseHandler.cause()); + }*/ + } else { + promise.fail(responseHandler.cause()); + } } else { - promise.fail(responseHandler.cause()); - }*/ - } else { - promise.fail(responseHandler.cause()); - } - } else { - promise.fail(responseHandler.cause()); - } - }); + promise.fail(responseHandler.cause()); + } + }); return promise.future(); - } + } } diff --git a/src/main/java/iudx/gis/server/apiserver/util/HttpStatusCode.java b/src/main/java/iudx/gis/server/apiserver/util/HttpStatusCode.java index 0993468..514685b 100644 --- a/src/main/java/iudx/gis/server/apiserver/util/HttpStatusCode.java +++ b/src/main/java/iudx/gis/server/apiserver/util/HttpStatusCode.java @@ -21,7 +21,8 @@ public enum HttpStatusCode { NOT_FOUND(404, "Not Found", "urn:dx:rs:notFound"), METHOD_NOT_ALLOWED(405, "Method Not Allowed", "urn:dx:rs:methodNotAllowed"), NOT_ACCEPTABLE(406, "Not Acceptable", "urn:dx:rs:notAcceptable"), - PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "urn:dx:rs:proxyAuthenticationRequired"), + PROXY_AUTHENTICATION_REQUIRED( + 407, "Proxy Authentication Required", "urn:dx:rs:proxyAuthenticationRequired"), REQUEST_TIMEOUT(408, "Request Timeout", "urn:dx:rs:requestTimeout"), CONFLICT(409, "Conflict", "urn:dx:rs:conflict"), GONE(410, "Gone", "urn:dx:rs:gone"), @@ -40,8 +41,10 @@ public enum HttpStatusCode { UPGRADE_REQUIRED(426, "Upgrade Required", "urn:dx:rs:upgradeRequired"), PRECONDITION_REQUIRED(428, "Precondition Required", "urn:dx:rs:preconditionRequired"), TOO_MANY_REQUESTS(429, "Too Many Requests", "urn:dx:rs:tooManyRequests"), - REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "urn:dx:rs:requestHeaderFieldsTooLarge"), - UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons", "urn:dx:rs:unavailableForLegalReasons"), + REQUEST_HEADER_FIELDS_TOO_LARGE( + 431, "Request Header Fields Too Large", "urn:dx:rs:requestHeaderFieldsTooLarge"), + UNAVAILABLE_FOR_LEGAL_REASONS( + 451, "Unavailable For Legal Reasons", "urn:dx:rs:unavailableForLegalReasons"), // 5xx: Server Error INTERNAL_SERVER_ERROR(500, "Internal Server Error", "urn:dx:rs:internalServerError"), @@ -49,12 +52,14 @@ public enum HttpStatusCode { BAD_GATEWAY(502, "Bad Gateway", "urn:dx:rs:badGateway"), SERVICE_UNAVAILABLE(503, "Service Unavailable", "urn:dx:rs:serviceUnavailable"), GATEWAY_TIMEOUT(504, "Gateway Timeout", "urn:dx:rs:gatewayTimeout"), - HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported", "urn:dx:rs:httpVersionNotSupported"), + HTTP_VERSION_NOT_SUPPORTED( + 505, "HTTP Version Not Supported", "urn:dx:rs:httpVersionNotSupported"), VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "urn:dx:rs:variantAlsoNegotiates"), INSUFFICIENT_STORAGE(507, "Insufficient Storage", "urn:dx:rs:insufficientStorage"), LOOP_DETECTED(508, "Loop Detected", "urn:dx:rs:loopDetected"), NOT_EXTENDED(510, "Not Extended", "urn:dx:rs:notExtended"), - NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "urn:dx:rs:networkAuthenticationRequired"); + NETWORK_AUTHENTICATION_REQUIRED( + 511, "Network Authentication Required", "urn:dx:rs:networkAuthenticationRequired"); private final int value; private final String description; @@ -66,6 +71,15 @@ 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; } @@ -82,12 +96,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/gis/server/apiserver/util/RequestType.java b/src/main/java/iudx/gis/server/apiserver/util/RequestType.java index 1e27cf4..3344cd1 100644 --- a/src/main/java/iudx/gis/server/apiserver/util/RequestType.java +++ b/src/main/java/iudx/gis/server/apiserver/util/RequestType.java @@ -1,18 +1,18 @@ package iudx.gis.server.apiserver.util; public enum RequestType { - ENTITY_PATH("entity_path"), - ENTITY_QUERY("entity_query"), - ADMIN_CRUD_PATH("admin_crud_schema.json"), - ADMIN_CRUD_PATH_DELETE("admin_crud_path_delete"); + ENTITY_PATH("entity_path"), + ENTITY_QUERY("entity_query"), + ADMIN_CRUD_PATH("admin_crud_schema.json"), + ADMIN_CRUD_PATH_DELETE("admin_crud_path_delete"); - private String filename; + private String filename; - public String getFilename() { - return this.filename; - } + RequestType(String fileName) { + this.filename = fileName; + } - private RequestType(String fileName) { - this.filename = fileName; - } + public String getFilename() { + return this.filename; + } } diff --git a/src/main/java/iudx/gis/server/apiserver/validation/ValidatorsHandlersFactory.java b/src/main/java/iudx/gis/server/apiserver/validation/ValidatorsHandlersFactory.java index 74509db..97179a5 100644 --- a/src/main/java/iudx/gis/server/apiserver/validation/ValidatorsHandlersFactory.java +++ b/src/main/java/iudx/gis/server/apiserver/validation/ValidatorsHandlersFactory.java @@ -1,10 +1,11 @@ package iudx.gis.server.apiserver.validation; +import static iudx.gis.server.apiserver.util.Constants.NGSILDQUERY_ID; + import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; -import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import io.vertx.json.schema.Schema; import io.vertx.json.schema.SchemaParser; @@ -15,9 +16,6 @@ import iudx.gis.server.apiserver.validation.types.JsonSchemaTypeValidator; import iudx.gis.server.apiserver.validation.types.StringTypeValidator; import iudx.gis.server.apiserver.validation.types.Validator; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -25,16 +23,20 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - -import static iudx.gis.server.apiserver.util.Constants.NGSILDQUERY_ID; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ValidatorsHandlersFactory { private static final Logger LOGGER = LogManager.getLogger(ValidatorsHandlersFactory.class); private static Map jsonSchemaMap = new HashMap<>(); - public List build(final Vertx vertx, RequestType type, final MultiMap parameters, - final MultiMap headers, final JsonObject body) { + public List build( + final Vertx vertx, + RequestType type, + final MultiMap parameters, + final MultiMap headers, + final JsonObject body) { List validator = new ArrayList<>(); LOGGER.debug("getValidation4Context() started for :" + type); switch (type) { @@ -60,7 +62,8 @@ private void getAdminCrudPathDeleteValidations(MultiMap parameters, List validator) { + private void getAdminCrudPathValidations( + Vertx vertx, JsonObject body, List validator) { validator.addAll(getRequestSchemaValidator(vertx, body, RequestType.ADMIN_CRUD_PATH)); } @@ -76,7 +79,8 @@ private void getEntityPathValidations(MultiMap parameters, List valid validator.add(new StringTypeValidator(parameters.get("resourceName"), true)); } - private List getRequestSchemaValidator(Vertx vertx, JsonObject body, RequestType requestType) { + private List getRequestSchemaValidator( + Vertx vertx, JsonObject body, RequestType requestType) { List validators = new ArrayList<>(); SchemaRouter schemaRouter = SchemaRouter.create(vertx, new SchemaRouterOptions()); SchemaParser schemaParser = SchemaParser.createOpenAPI3SchemaParser(schemaRouter); @@ -88,7 +92,8 @@ private List getRequestSchemaValidator(Vertx vertx, JsonObject body, validators.add(new JsonSchemaTypeValidator(body, schema)); } catch (Exception ex) { LOGGER.error(ex); -// throw new DxRuntimeException(HttpStatusCode.BAD_REQUEST.getValue(), SCHEMA_READ_ERROR); + // throw new DxRuntimeException(HttpStatusCode.BAD_REQUEST.getValue(), + // SCHEMA_READ_ERROR); } return validators; } @@ -98,13 +103,13 @@ private String loadJson(String filename) { if (jsonSchemaMap.containsKey(filename)) { jsonStr = jsonSchemaMap.get(filename); } else { - try (InputStream inputStream = - getClass().getClassLoader().getResourceAsStream(filename)) { + try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename)) { jsonStr = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); jsonSchemaMap.put(filename, jsonStr); } catch (IOException e) { LOGGER.error(e); -// throw new DxRuntimeException(HttpStatusCode.BAD_REQUEST.getValue(), SCHEMA_READ_ERROR); + // throw new DxRuntimeException(HttpStatusCode.BAD_REQUEST.getValue(), + // SCHEMA_READ_ERROR); } } return jsonStr; diff --git a/src/main/java/iudx/gis/server/apiserver/validation/types/IdTypeValidator.java b/src/main/java/iudx/gis/server/apiserver/validation/types/IdTypeValidator.java index 6334657..e6de8b3 100644 --- a/src/main/java/iudx/gis/server/apiserver/validation/types/IdTypeValidator.java +++ b/src/main/java/iudx/gis/server/apiserver/validation/types/IdTypeValidator.java @@ -1,21 +1,20 @@ package iudx.gis.server.apiserver.validation.types; +import static iudx.gis.server.apiserver.util.Constants.*; + import iudx.gis.server.apiserver.exceptions.DxRuntimeException; import iudx.gis.server.apiserver.response.ResponseUrn; +import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.regex.Pattern; - -import static iudx.gis.server.apiserver.util.Constants.*; - public class IdTypeValidator implements Validator { private static final Logger LOGGER = LogManager.getLogger(IdTypeValidator.class); - + private static final Pattern regexIDPattern = + Pattern.compile( + "^[a-zA-Z0-9.]{4,100}/{1}[a-zA-Z0-9.]{4,100}/{1}[a-zA-Z.]{4,100}/{1}[a-zA-Z-_.]" + + "{4,100}/{1}[a-zA-Z0-9-_.]{4,100}$"); private Integer maxLength = VALIDATION_ID_MAX_LEN; - private static final Pattern regexIDPattern = Pattern.compile( - "^[a-zA-Z0-9.]{4,100}/{1}[a-zA-Z0-9.]{4,100}/{1}[a-zA-Z.]{4,100}/{1}[a-zA-Z-_.]{4,100}/{1}[a-zA-Z0-9-_.]{4,100}$"); - private String value; private boolean required; @@ -24,11 +23,10 @@ public IdTypeValidator(String value, boolean required) { this.required = required; } - public boolean isvalidIUDXId(String value) { + public boolean isValidIudxId(String value) { return regexIDPattern.matcher(value).matches(); } - @Override public boolean isValid() { LOGGER.debug("value : " + value + "required : " + required); @@ -43,19 +41,18 @@ public boolean isValid() { } if (value.isBlank()) { errorMessage = "Validation error : blank value for passed"; - throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, - failureMessage(value)); + throw new DxRuntimeException( + failureCode(), ResponseUrn.INVALID_ATTR_VALUE, failureMessage(value)); } } if (value != null && value.length() > maxLength) { errorMessage = "Validation error : Value exceed max character limit"; - throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, - failureMessage(value)); + throw new DxRuntimeException( + failureCode(), ResponseUrn.INVALID_ATTR_VALUE, failureMessage(value)); } - if (!isvalidIUDXId(value)) { + if (!isValidIudxId(value)) { errorMessage = "Validation error : Invalid id"; throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, errorMessage); - } return true; } diff --git a/src/main/java/iudx/gis/server/apiserver/validation/types/JsonSchemaTypeValidator.java b/src/main/java/iudx/gis/server/apiserver/validation/types/JsonSchemaTypeValidator.java index 621c41f..807438b 100644 --- a/src/main/java/iudx/gis/server/apiserver/validation/types/JsonSchemaTypeValidator.java +++ b/src/main/java/iudx/gis/server/apiserver/validation/types/JsonSchemaTypeValidator.java @@ -1,14 +1,13 @@ package iudx.gis.server.apiserver.validation.types; import static iudx.gis.server.apiserver.response.ResponseUrn.*; -import io.vertx.json.schema.NoSyncValidationException; -import io.vertx.json.schema.ValidationException; + +import io.vertx.core.json.JsonObject; +import io.vertx.json.schema.Schema; import iudx.gis.server.apiserver.exceptions.DxRuntimeException; import iudx.gis.server.apiserver.util.HttpStatusCode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import io.vertx.core.json.JsonObject; -import io.vertx.json.schema.Schema; public final class JsonSchemaTypeValidator implements Validator { diff --git a/src/main/java/iudx/gis/server/apiserver/validation/types/StringTypeValidator.java b/src/main/java/iudx/gis/server/apiserver/validation/types/StringTypeValidator.java index b704070..86cdd2e 100644 --- a/src/main/java/iudx/gis/server/apiserver/validation/types/StringTypeValidator.java +++ b/src/main/java/iudx/gis/server/apiserver/validation/types/StringTypeValidator.java @@ -19,23 +19,20 @@ public StringTypeValidator(String value, boolean required) { @Override public boolean isValid() { - String errorMessage = ""; + LOGGER.debug("value : " + value + "required : " + required); if (required && (value == null || value.isBlank())) { - errorMessage = "Validation error : null or blank value for required mandatory field"; throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, failureMessage()); } else { if (value == null) { return true; } if (value.isBlank()) { - errorMessage = "Validation error : blank value for passed"; throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, failureMessage()); } } if (value != null && value.length() > 100) { - errorMessage = "Validation error : length >100 not allowed"; throw new DxRuntimeException(failureCode(), ResponseUrn.INVALID_ATTR_VALUE, failureMessage()); } return true; diff --git a/src/main/java/iudx/gis/server/authenticator/AuthenticationVerticle.java b/src/main/java/iudx/gis/server/authenticator/AuthenticationVerticle.java index 5c114df..fa4fa2c 100644 --- a/src/main/java/iudx/gis/server/authenticator/AuthenticationVerticle.java +++ b/src/main/java/iudx/gis/server/authenticator/AuthenticationVerticle.java @@ -88,13 +88,14 @@ public void start() throws Exception { LOGGER.warn( "JWT ignore expiration set to true, do not set IgnoreExpiration in production!!"); } - dxApiBasePath = config().getString("dxApiBasePath"); - adminBasePath = config().getString("adminBasePath"); - api = Api.getInstance(dxApiBasePath,adminBasePath); + dxApiBasePath = config().getString("dxApiBasePath"); + adminBasePath = config().getString("adminBasePath"); + api = Api.getInstance(dxApiBasePath, adminBasePath); - JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); + JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions); cacheService = CacheService.createProxy(vertx, CACHE_SERVICE_ADDRESS); - jwtAuthenticationService = new JwtAuthenticationServiceImpl(vertx, jwtAuth, config(), api, cacheService); + jwtAuthenticationService = + new JwtAuthenticationServiceImpl(vertx, jwtAuth, config(), api, cacheService); /* Publish the Authentication service with the Event Bus against an address. */ consumer = diff --git a/src/main/java/iudx/gis/server/authenticator/JwtAuthenticationServiceImpl.java b/src/main/java/iudx/gis/server/authenticator/JwtAuthenticationServiceImpl.java index df2f060..3886d01 100644 --- a/src/main/java/iudx/gis/server/authenticator/JwtAuthenticationServiceImpl.java +++ b/src/main/java/iudx/gis/server/authenticator/JwtAuthenticationServiceImpl.java @@ -1,5 +1,7 @@ package iudx.gis.server.authenticator; +import static iudx.gis.server.authenticator.Constants.*; + import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import io.vertx.core.AsyncResult; @@ -23,20 +25,17 @@ import iudx.gis.server.authenticator.authorization.Method; import iudx.gis.server.authenticator.model.JwtData; import iudx.gis.server.cache.CacheService; -import iudx.gis.server.cache.cacheImpl.CacheType; +import iudx.gis.server.cache.cacheimpl.CacheType; +import iudx.gis.server.common.Api; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.concurrent.TimeUnit; - -import iudx.gis.server.common.Api; import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static iudx.gis.server.authenticator.Constants.*; - public class JwtAuthenticationServiceImpl implements AuthenticationService { private static final Logger LOGGER = LogManager.getLogger(JwtAuthenticationServiceImpl.class); @@ -56,13 +55,13 @@ public class JwtAuthenticationServiceImpl implements AuthenticationService { public Cache resourceIdCache = CacheBuilder.newBuilder() .maximumSize(1000) - .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES) + .expireAfterAccess(CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES) .build(); // resourceGroupCache will contain ACL info about all resource group in a resource server Cache resourceGroupCache = CacheBuilder.newBuilder() .maximumSize(1000) - .expireAfterAccess(Constants.CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES) + .expireAfterAccess(CACHE_TIMEOUT_AMOUNT, TimeUnit.MINUTES) .build(); public JwtAuthenticationServiceImpl( @@ -113,7 +112,7 @@ public AuthenticationService tokenIntrospect( } }) .compose(revokeClientTokenHandler -> isValidIid(result.jwtData)) - .compose(IdHandler -> isValidRole(result.jwtData)) + .compose(idHandler -> isValidRole(result.jwtData)) .onSuccess(successHandler -> handler.handle(Future.succeededFuture(successHandler))) .onFailure( failureHandler -> handler.handle(Future.failedFuture(failureHandler.getMessage()))); @@ -187,10 +186,10 @@ private Future isOpenResource(String id) { LOGGER.trace("isOpenResource() started"); Promise promise = Promise.promise(); - String ACL = resourceIdCache.getIfPresent(id); - if (ACL != null) { + String acl = resourceIdCache.getIfPresent(id); + if (acl != null) { LOGGER.debug("Cache Hit"); - promise.complete(ACL); + promise.complete(acl); } else { // cache miss LOGGER.debug("Cache miss calling cat server"); @@ -204,8 +203,8 @@ private Future isOpenResource(String id) { : String.join("/", Arrays.copyOfRange(idComponents, 0, 4)); // 1. check group accessPolicy. // 2. check resource exist, if exist set accessPolicy to group accessPolicy. else fail - Future groupACLFuture = getGroupAccessPolicy(groupId); - groupACLFuture + Future groupAclFuture = getGroupAccessPolicy(groupId); + groupAclFuture .compose( groupACLResult -> { String groupPolicy = groupACLResult; @@ -246,7 +245,7 @@ public Future validateAccess( AuthorizationRequest authRequest = new AuthorizationRequest(method, apiEndpoint); IudxRole role = IudxRole.fromRole(jwtData.getRole()); - AuthorizationStrategy authStrategy = AuthorizationContextFactory.create(role,api); + AuthorizationStrategy authStrategy = AuthorizationContextFactory.create(role, api); LOGGER.debug("strategy : " + authStrategy.getClass().getSimpleName()); JwtAuthorization jwtAuthStrategy = new JwtAuthorization(authStrategy); LOGGER.debug("endPoint : " + authInfo.getString("apiEndpoint")); @@ -257,9 +256,9 @@ public Future validateAccess( jsonResponse.put(JSON_IID, jwtId); jsonResponse.put( JSON_EXPIRY, - (LocalDateTime.ofInstant( + LocalDateTime.ofInstant( Instant.ofEpochSecond(Long.parseLong(jwtData.getExp().toString())), - ZoneId.systemDefault())) + ZoneId.systemDefault()) .toString()); promise.complete(jsonResponse); } else { @@ -276,10 +275,8 @@ public Future validateAccess( } private boolean checkOpenEndPoints(String endPoint) { - for(String item : OPEN_ENDPOINTS) - { - if(endPoint.contains(item)) - { + for (String item : OPEN_ENDPOINTS) { + if (endPoint.contains(item)) { return true; } } @@ -353,7 +350,7 @@ public Future isValidId(JwtData jwtData, String id) { return promise.future(); } - public Future isResourceExist(String id, String groupACL) { + public Future isResourceExist(String id, String groupAcl) { LOGGER.trace("isResourceExist() started"); Promise promise = Promise.promise(); String resourceExist = resourceIdCache.getIfPresent(id); @@ -385,7 +382,7 @@ public Future isResourceExist(String id, String groupACL) { promise.fail("Not Found"); } else { LOGGER.debug("is Exist response : " + responseBody); - resourceIdCache.put(id, groupACL); + resourceIdCache.put(id, groupAcl); promise.complete(true); } }); @@ -410,8 +407,8 @@ Future isRevokedClientToken(JwtData jwtData) { LocalDateTime revokedAt = LocalDateTime.parse(timestamp); LocalDateTime jwtIssuedAt = - (LocalDateTime.ofInstant( - Instant.ofEpochSecond(jwtData.getIat()), ZoneId.systemDefault())); + LocalDateTime.ofInstant( + Instant.ofEpochSecond(jwtData.getIat()), ZoneId.systemDefault()); if (jwtIssuedAt.isBefore(revokedAt)) { LOGGER.error("Privileges for client are revoked."); @@ -432,10 +429,10 @@ Future isRevokedClientToken(JwtData jwtData) { public Future getGroupAccessPolicy(String groupId) { LOGGER.trace("getGroupAccessPolicy() started"); Promise promise = Promise.promise(); - String groupACL = resourceGroupCache.getIfPresent(groupId); - if (groupACL != null) { + String groupAcl = resourceGroupCache.getIfPresent(groupId); + if (groupAcl != null) { LOGGER.debug("Info : cache Hit"); - promise.complete(groupACL); + promise.complete(groupAcl); } else { LOGGER.debug("Info : cache miss"); catWebClient @@ -461,16 +458,16 @@ public Future getGroupAccessPolicy(String groupId) { promise.fail("Resource not found"); return; } - String resourceACL = "SECURE"; + String resourceAcl = "SECURE"; try { - resourceACL = + resourceAcl = responseBody .getJsonArray("results") .getJsonObject(0) .getString("accessPolicy"); - resourceGroupCache.put(groupId, resourceACL); + resourceGroupCache.put(groupId, resourceAcl); LOGGER.debug("Info: Group ID valid : Catalogue item Found"); - promise.complete(resourceACL); + promise.complete(resourceAcl); } catch (Exception ignored) { LOGGER.error(ignored.getMessage()); LOGGER.error("Info: Group ID invalid : Empty response in results from Catalogue"); diff --git a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationContextFactory.java b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationContextFactory.java index c436463..113e3ac 100644 --- a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationContextFactory.java +++ b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationContextFactory.java @@ -4,20 +4,17 @@ public class AuthorizationContextFactory { - -// private final static AuthorizationStrategy consumerAuth = new ConsumerAuthStrategy(); + // private final static AuthorizationStrategy consumerAuth = new ConsumerAuthStrategy(); public static AuthorizationStrategy create(IudxRole role, Api api) { - if(role==null){ + if (role == null) { throw new IllegalArgumentException(role + "invalid role."); } switch (role) { - case CONSUMER: { + case CONSUMER: return ConsumerAuthStrategy.getInstance(api); - } default: throw new IllegalArgumentException(role + "invalid role."); } } - } diff --git a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationRequest.java b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationRequest.java index fab33b7..e4a669a 100644 --- a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationRequest.java +++ b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationRequest.java @@ -2,7 +2,6 @@ public final class AuthorizationRequest { - private final Method method; private final String api; @@ -30,19 +29,22 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } AuthorizationRequest other = (AuthorizationRequest) obj; - if (!api.equals(other.api)) + if (!api.equals(other.api)) { return false; - if (method != other.method) + } + if (method != other.method) { return false; + } return true; } - - } diff --git a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationStrategy.java b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationStrategy.java index 7ecdffd..68f1e60 100644 --- a/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationStrategy.java +++ b/src/main/java/iudx/gis/server/authenticator/authorization/AuthorizationStrategy.java @@ -4,6 +4,5 @@ public interface AuthorizationStrategy { - boolean isAuthorized(AuthorizationRequest authRequest,JwtData jwtData); - + boolean isAuthorized(AuthorizationRequest authRequest, JwtData jwtData); } diff --git a/src/main/java/iudx/gis/server/authenticator/authorization/ConsumerAuthStrategy.java b/src/main/java/iudx/gis/server/authenticator/authorization/ConsumerAuthStrategy.java index b5972fa..c0e48c5 100644 --- a/src/main/java/iudx/gis/server/authenticator/authorization/ConsumerAuthStrategy.java +++ b/src/main/java/iudx/gis/server/authenticator/authorization/ConsumerAuthStrategy.java @@ -4,12 +4,11 @@ import io.vertx.core.json.JsonArray; import iudx.gis.server.authenticator.model.JwtData; +import iudx.gis.server.common.Api; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import iudx.gis.server.common.Api; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,19 +19,16 @@ public class ConsumerAuthStrategy implements AuthorizationStrategy { static Map> consumerAuthorizationRules = new HashMap<>(); static Api api; private static volatile ConsumerAuthStrategy instance; - private ConsumerAuthStrategy(Api apis) - { + + private ConsumerAuthStrategy(Api apis) { api = apis; buildPermissions(api); } public static ConsumerAuthStrategy getInstance(Api apis) { - if (instance == null) - { - synchronized (ConsumerAuthStrategy.class) - { - if (instance == null) - { + if (instance == null) { + synchronized (ConsumerAuthStrategy.class) { + if (instance == null) { instance = new ConsumerAuthStrategy(apis); } } diff --git a/src/main/java/iudx/gis/server/authenticator/authorization/JwtAuthorization.java b/src/main/java/iudx/gis/server/authenticator/authorization/JwtAuthorization.java index 50e0b10..063ac6a 100644 --- a/src/main/java/iudx/gis/server/authenticator/authorization/JwtAuthorization.java +++ b/src/main/java/iudx/gis/server/authenticator/authorization/JwtAuthorization.java @@ -1,13 +1,8 @@ package iudx.gis.server.authenticator.authorization; import iudx.gis.server.authenticator.model.JwtData; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; public final class JwtAuthorization { - - private static final Logger LOGGER = LogManager.getLogger(JwtAuthorization.class); - private final AuthorizationStrategy authStrategy; public JwtAuthorization(final AuthorizationStrategy authStrategy) { diff --git a/src/main/java/iudx/gis/server/authenticator/model/JwtData.java b/src/main/java/iudx/gis/server/authenticator/model/JwtData.java index 02fe5c4..4bff023 100644 --- a/src/main/java/iudx/gis/server/authenticator/model/JwtData.java +++ b/src/main/java/iudx/gis/server/authenticator/model/JwtData.java @@ -6,7 +6,7 @@ @DataObject(generateConverter = true, publicConverter = false) public final class JwtData { - private String access_token; + private String accessToken; private String sub; private String iss; private String aud; @@ -16,26 +16,27 @@ public final class JwtData { private String role; private JsonObject cons; - public JsonObject toJson() { - JsonObject json = new JsonObject(); - JwtDataConverter.toJson(this, json); - return json; - } - public JwtData() { super(); } public JwtData(JsonObject json) { JwtDataConverter.fromJson(json, this); + setAccessToken(json.getString("access_token")); + } + + public JsonObject toJson() { + JsonObject json = new JsonObject(); + JwtDataConverter.toJson(this, json); + return json; } - public String getAccess_token() { - return access_token; + public String getAccessToken() { + return accessToken; } - public void setAccess_token(String access_token) { - this.access_token = access_token; + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; } public String getSub() { @@ -104,12 +105,24 @@ public void setIat(Integer iat) { @Override public String toString() { - return "JwtData [access_token=" + access_token + ", sub=" + sub + ", iss=" + iss + ", aud=" + aud + ", exp=" + exp - + ", iat=" + iat + ", iid=" + iid + ", role=" + role + ", cons=" + cons + "]"; + return "JwtData [access_token=" + + accessToken + + ", sub=" + + sub + + ", iss=" + + iss + + ", aud=" + + aud + + ", exp=" + + exp + + ", iat=" + + iat + + ", iid=" + + iid + + ", role=" + + role + + ", cons=" + + cons + + "]"; } - - - - - } diff --git a/src/main/java/iudx/gis/server/cache/CacheService.java b/src/main/java/iudx/gis/server/cache/CacheService.java index 788d62b..4da29f5 100644 --- a/src/main/java/iudx/gis/server/cache/CacheService.java +++ b/src/main/java/iudx/gis/server/cache/CacheService.java @@ -30,7 +30,7 @@ static CacheService createProxy(Vertx vertx, String address) { * } * * - * in case of success method returns a value abstracted in json object else handler will fail. + *

in case of success method returns a value abstracted in json object else handler will fail. * *

    * {
@@ -40,7 +40,7 @@ static CacheService createProxy(Vertx vertx, String address) {
    *
    * @param request valid json request
    * @param handler handler
-   * @return
+   * @return CacheService
    */
   @Fluent
   CacheService get(JsonObject request, Handler> handler);
@@ -58,7 +58,7 @@ static CacheService createProxy(Vertx vertx, String address) {
    * }
    * 
* - * in case of success a json object will be returned else handler will fail. + *

in case of success a json object will be returned else handler will fail. * *

    * {
@@ -66,13 +66,13 @@ static CacheService createProxy(Vertx vertx, String address) {
    * }
    * 
* - * @param request - * @param handler + * @param request JsonObject + * @param handler handler * @return in case of success a json object will be returned else handler will fail. *
-   * {
-   *    "key":"value"
-   * }
+   *     {
+   *        "key":"value"
+   *     }
    *         
*/ @Fluent @@ -92,9 +92,9 @@ static CacheService createProxy(Vertx vertx, String address) { * } * * - * @param request - * @param handler - * @return + * @param request JsonObject + * @param handler handler + * @return CacheService */ @Fluent CacheService refresh(JsonObject request, Handler> handler); diff --git a/src/main/java/iudx/gis/server/cache/CacheServiceImpl.java b/src/main/java/iudx/gis/server/cache/CacheServiceImpl.java index 04c22fc..478eb07 100644 --- a/src/main/java/iudx/gis/server/cache/CacheServiceImpl.java +++ b/src/main/java/iudx/gis/server/cache/CacheServiceImpl.java @@ -5,9 +5,9 @@ import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; -import iudx.gis.server.cache.cacheImpl.CacheType; -import iudx.gis.server.cache.cacheImpl.IudxCache; -import iudx.gis.server.cache.cacheImpl.RevokedClientCache; +import iudx.gis.server.cache.cacheimpl.CacheType; +import iudx.gis.server.cache.cacheimpl.IudxCache; +import iudx.gis.server.cache.cacheimpl.RevokedClientCache; import iudx.gis.server.database.postgres.PostgresService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -114,14 +114,10 @@ private IudxCache getCache(JsonObject json) { IudxCache cache = null; switch (cacheType) { case REVOKED_CLIENT: - { - cache = revokedClientCache; - break; - } + cache = revokedClientCache; + break; default: - { - throw new IllegalArgumentException("No cache type specified"); - } + throw new IllegalArgumentException("No cache type specified"); } return cache; } diff --git a/src/main/java/iudx/gis/server/cache/CacheVerticle.java b/src/main/java/iudx/gis/server/cache/CacheVerticle.java index 2b23267..39812c1 100644 --- a/src/main/java/iudx/gis/server/cache/CacheVerticle.java +++ b/src/main/java/iudx/gis/server/cache/CacheVerticle.java @@ -4,22 +4,15 @@ import static iudx.gis.server.common.Constants.PG_SERVICE_ADDRESS; import io.vertx.core.AbstractVerticle; -import io.vertx.core.eventbus.MessageConsumer; -import io.vertx.core.json.JsonObject; import io.vertx.serviceproxy.ServiceBinder; import iudx.gis.server.database.postgres.PostgresService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CacheVerticle extends AbstractVerticle { - private static final Logger LOGGER = LogManager.getLogger(CacheVerticle.class); - private static final String SERVICE_ADDRESS = CACHE_SERVICE_ADDRESS; - - private MessageConsumer consumer; private ServiceBinder binder; - private CacheService cacheService; private PostgresService pgService; @@ -31,7 +24,7 @@ public void start() throws Exception { cacheService = new CacheServiceImpl(vertx, pgService); binder = new ServiceBinder(vertx); - consumer = binder.setAddress(SERVICE_ADDRESS).register(CacheService.class, cacheService); + binder.setAddress(SERVICE_ADDRESS).register(CacheService.class, cacheService); LOGGER.info("Cache Verticle deployed."); } diff --git a/src/main/java/iudx/gis/server/cache/cacheImpl/CacheType.java b/src/main/java/iudx/gis/server/cache/cacheimpl/CacheType.java similarity index 77% rename from src/main/java/iudx/gis/server/cache/cacheImpl/CacheType.java rename to src/main/java/iudx/gis/server/cache/cacheimpl/CacheType.java index ff10242..a45b403 100644 --- a/src/main/java/iudx/gis/server/cache/cacheImpl/CacheType.java +++ b/src/main/java/iudx/gis/server/cache/cacheimpl/CacheType.java @@ -1,4 +1,4 @@ -package iudx.gis.server.cache.cacheImpl; +package iudx.gis.server.cache.cacheimpl; public enum CacheType { REVOKED_CLIENT("revoked_client"); diff --git a/src/main/java/iudx/gis/server/cache/cacheImpl/IudxCache.java b/src/main/java/iudx/gis/server/cache/cacheimpl/IudxCache.java similarity index 74% rename from src/main/java/iudx/gis/server/cache/cacheImpl/IudxCache.java rename to src/main/java/iudx/gis/server/cache/cacheimpl/IudxCache.java index e93cc13..2e19140 100644 --- a/src/main/java/iudx/gis/server/cache/cacheImpl/IudxCache.java +++ b/src/main/java/iudx/gis/server/cache/cacheimpl/IudxCache.java @@ -1,4 +1,4 @@ -package iudx.gis.server.cache.cacheImpl; +package iudx.gis.server.cache.cacheimpl; public interface IudxCache { diff --git a/src/main/java/iudx/gis/server/cache/cacheImpl/RevokedClientCache.java b/src/main/java/iudx/gis/server/cache/cacheimpl/RevokedClientCache.java similarity index 97% rename from src/main/java/iudx/gis/server/cache/cacheImpl/RevokedClientCache.java rename to src/main/java/iudx/gis/server/cache/cacheimpl/RevokedClientCache.java index 7887ea1..6927b79 100644 --- a/src/main/java/iudx/gis/server/cache/cacheImpl/RevokedClientCache.java +++ b/src/main/java/iudx/gis/server/cache/cacheimpl/RevokedClientCache.java @@ -1,4 +1,4 @@ -package iudx.gis.server.cache.cacheImpl; +package iudx.gis.server.cache.cacheimpl; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; diff --git a/src/main/java/iudx/gis/server/common/Api.java b/src/main/java/iudx/gis/server/common/Api.java index adf7d7f..a76c37a 100644 --- a/src/main/java/iudx/gis/server/common/Api.java +++ b/src/main/java/iudx/gis/server/common/Api.java @@ -4,52 +4,45 @@ public class Api { - private final String dxApiBasePath; - private final String adminBasePath; - private static volatile Api apiInstance; - - private Api(String dxApiBasePath,String adminBasePath) { - this.dxApiBasePath = dxApiBasePath; - this.adminBasePath = adminBasePath; - buildEndpoints(); - } - - public static Api getInstance(String dxApiBasePath, String adminBasePath) - { - if (apiInstance == null) - { - synchronized (Api.class) - { - if (apiInstance == null) - { - apiInstance = new Api(dxApiBasePath,adminBasePath); - } - } + private static volatile Api apiInstance; + private final String dxApiBasePath; + private final String adminBasePath; + private StringBuilder entitiesEndpoint; + private StringBuilder entitiesRegex; + private StringBuilder adminPath; + + private Api(String dxApiBasePath, String adminBasePath) { + this.dxApiBasePath = dxApiBasePath; + this.adminBasePath = adminBasePath; + buildEndpoints(); + } + + public static Api getInstance(String dxApiBasePath, String adminBasePath) { + if (apiInstance == null) { + synchronized (Api.class) { + if (apiInstance == null) { + apiInstance = new Api(dxApiBasePath, adminBasePath); } - return apiInstance; - } - private StringBuilder entitiesEndpoint; - private StringBuilder entitiesRegex; - private StringBuilder adminPath; - - - public void buildEndpoints() { - entitiesEndpoint = new StringBuilder(dxApiBasePath).append(NGSILD_ENTITIES_URL); - entitiesRegex = new StringBuilder(dxApiBasePath).append(ENTITITES_URL_REGEX); - adminPath = new StringBuilder(adminBasePath).append(ADMIN_PATH); - } - - - public String getEntitiesEndpoint() { - return entitiesEndpoint.toString(); - } - - public String getEntitiesRegex() { - return entitiesRegex.toString(); - } - - public String getAdminPath() - { - return adminPath.toString(); + } } + return apiInstance; + } + + public void buildEndpoints() { + entitiesEndpoint = new StringBuilder(dxApiBasePath).append(NGSILD_ENTITIES_URL); + entitiesRegex = new StringBuilder(dxApiBasePath).append(ENTITITES_URL_REGEX); + adminPath = new StringBuilder(adminBasePath).append(ADMIN_PATH); + } + + public String getEntitiesEndpoint() { + return entitiesEndpoint.toString(); + } + + public String getEntitiesRegex() { + return entitiesRegex.toString(); + } + + public String getAdminPath() { + return adminPath.toString(); + } } diff --git a/src/main/java/iudx/gis/server/common/Constants.java b/src/main/java/iudx/gis/server/common/Constants.java index dda2ac7..5ab6f2f 100644 --- a/src/main/java/iudx/gis/server/common/Constants.java +++ b/src/main/java/iudx/gis/server/common/Constants.java @@ -2,34 +2,32 @@ public class Constants { - /** service proxy addresses **/ + /** service proxy addresses * */ public static final String PG_SERVICE_ADDRESS = "iudx.gis.pgsql.service"; + public static final String CACHE_SERVICE_ADDRESS = "iudx.gis.cache.service"; public static final String AUTHENTICATION_SERVICE_ADDRESS = "iudx.gis.authentication.service"; public static final String DATABASE_SERVICE_ADDRESS = "iudx.gis.database.service"; public static final String DATABROKER_SERVICE_ADDRESS = "iudx.gis.broker.service"; - public static final String METERING_SERVICE_ADDRESS="iudx.gis.metering.service"; - - // postgres queries - public static String SELECT_REVOKE_TOKEN_SQL = "SELECT * FROM revoked_tokens"; - - //RMQ - public static final String GIS_INVALID_SUB="gis-invalid-sub"; - - //queries + public static final String METERING_SERVICE_ADDRESS = "iudx.gis.metering.service"; + // RMQ + public static final String GIS_INVALID_SUB = "gis-invalid-sub"; + // queries public static final String TABLE_NAME = "gis"; public static final String SELECT_ADMIN_DETAILS_QUERY = "SELECT * FROM " + TABLE_NAME + " WHERE iudx_resource_id = '$1'"; - public static final String INSERT_ADMIN_DETAILS_QUERY = - "INSERT INTO " + TABLE_NAME + "(iudx_resource_id, url, port, isOpen, username, password,tokenurl) " + - "VALUES ('$1', '$2', '$3', '$4', '$5', '$6','$7')"; - + "INSERT INTO " + + TABLE_NAME + + "(iudx_resource_id, url, port, isOpen, username, password,tokenurl) " + + "VALUES ('$1', '$2', '$3', '$4', '$5', '$6','$7')"; public static final String UPDATE_ADMIN_DETAILS_QUERY = - "UPDATE " + TABLE_NAME + " SET url='$1', port='$2', isOpen='$3', username='$4', password='$5', tokenurl='$7' " + - "WHERE iudx_resource_id='$6'"; - + "UPDATE " + + TABLE_NAME + + " SET url='$1', port='$2', isOpen='$3', username='$4', password='$5', tokenurl='$7' " + + "WHERE iudx_resource_id='$6'"; public static final String DELETE_ADMIN_DETAILS_QUERY = "DELETE FROM " + TABLE_NAME + " WHERE iudx_resource_id = '$1'"; - + // postgres queries + public static String SELECT_REVOKE_TOKEN_SQL = "SELECT * FROM revoked_tokens"; } diff --git a/src/main/java/iudx/gis/server/common/VHosts.java b/src/main/java/iudx/gis/server/common/VirtualHosts.java similarity index 75% rename from src/main/java/iudx/gis/server/common/VHosts.java rename to src/main/java/iudx/gis/server/common/VirtualHosts.java index 2df54fc..0ce8f60 100644 --- a/src/main/java/iudx/gis/server/common/VHosts.java +++ b/src/main/java/iudx/gis/server/common/VirtualHosts.java @@ -1,13 +1,13 @@ package iudx.gis.server.common; -public enum VHosts { +public enum VirtualHosts { IUDX_PROD("prodVhost"), IUDX_INTERNAL("internalVhost"), IUDX_EXTERNAL("externalVhost"); public String value; - VHosts(String value) { + VirtualHosts(String value) { this.value = value; } } diff --git a/src/main/java/iudx/gis/server/configuration/Configuration.java b/src/main/java/iudx/gis/server/configuration/Configuration.java index f264842..d363238 100644 --- a/src/main/java/iudx/gis/server/configuration/Configuration.java +++ b/src/main/java/iudx/gis/server/configuration/Configuration.java @@ -1,27 +1,25 @@ package iudx.gis.server.configuration; -import java.io.File; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.FileSystem; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; +import java.io.File; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class Configuration { - private static FileSystem fileSystem; private static final Logger LOGGER = LogManager.getLogger(Configuration.class); private static final String CONFIG_PATH = "./configs/config-test.json"; + private static FileSystem fileSystem; /** * This is to read the config.json file from fileSystem to load configuration. * - * @param moduleIndex - * @param vertx + * @param moduleIndex Integer + * @param vertx Vertx * @return module JsonObject */ public JsonObject configLoader(int moduleIndex, Vertx vertx) { @@ -43,5 +41,4 @@ public JsonObject configLoader(int moduleIndex, Vertx vertx) { return moduleConf; } - } diff --git a/src/main/java/iudx/gis/server/database/postgres/PostgresService.java b/src/main/java/iudx/gis/server/database/postgres/PostgresService.java index aeb94c4..63e5a8b 100644 --- a/src/main/java/iudx/gis/server/database/postgres/PostgresService.java +++ b/src/main/java/iudx/gis/server/database/postgres/PostgresService.java @@ -9,7 +9,6 @@ import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; - @VertxGen @ProxyGen public interface PostgresService { diff --git a/src/main/java/iudx/gis/server/database/postgres/PostgresServiceImpl.java b/src/main/java/iudx/gis/server/database/postgres/PostgresServiceImpl.java index a9da148..82e4a4a 100644 --- a/src/main/java/iudx/gis/server/database/postgres/PostgresServiceImpl.java +++ b/src/main/java/iudx/gis/server/database/postgres/PostgresServiceImpl.java @@ -7,10 +7,8 @@ import io.vertx.core.json.JsonObject; import io.vertx.pgclient.PgPool; import io.vertx.sqlclient.Row; -import io.vertx.sqlclient.Tuple; import iudx.gis.server.common.Response; import iudx.gis.server.common.ResponseUrn; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; diff --git a/src/main/java/iudx/gis/server/database/postgres/PostgresVerticle.java b/src/main/java/iudx/gis/server/database/postgres/PostgresVerticle.java index c4fcba8..2634944 100644 --- a/src/main/java/iudx/gis/server/database/postgres/PostgresVerticle.java +++ b/src/main/java/iudx/gis/server/database/postgres/PostgresVerticle.java @@ -1,8 +1,7 @@ package iudx.gis.server.database.postgres; import static iudx.gis.server.common.Constants.PG_SERVICE_ADDRESS; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -10,6 +9,8 @@ import io.vertx.pgclient.PgPool; import io.vertx.serviceproxy.ServiceBinder; import io.vertx.sqlclient.PoolOptions; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class PostgresVerticle extends AbstractVerticle { @@ -21,7 +22,7 @@ public class PostgresVerticle extends AbstractVerticle { private PgConnectOptions connectOptions; private PoolOptions poolOptions; private PgPool pool; - private String databaseIP; + private String databaseIp; private int databasePort; private String databaseName; private String databaseUserName; @@ -33,7 +34,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"); @@ -42,7 +43,7 @@ public void start() throws Exception { this.connectOptions = new PgConnectOptions() .setPort(databasePort) - .setHost(databaseIP) + .setHost(databaseIp) .setDatabase(databaseName) .setUser(databaseUserName) .setPassword(databasePassword) @@ -57,7 +58,6 @@ public void start() throws Exception { pgService = new PostgresServiceImpl(this.pool); - consumer = binder.setAddress(PG_SERVICE_ADDRESS).register(PostgresService.class, pgService); LOGGER.info("Postgres verticle started."); } @@ -66,5 +66,4 @@ public void start() throws Exception { public void stop() { binder.unregister(consumer); } - } diff --git a/src/main/java/iudx/gis/server/database/util/Constants.java b/src/main/java/iudx/gis/server/database/util/Constants.java index 37eb7d1..7db8a55 100644 --- a/src/main/java/iudx/gis/server/database/util/Constants.java +++ b/src/main/java/iudx/gis/server/database/util/Constants.java @@ -6,7 +6,7 @@ public class Constants { public static final String TITLE = "title"; public static final String SUCCESS = "Success"; public static final String ERROR_MESSAGE = "errorMessage"; - public static final String DETAIL="detail"; + public static final String DETAIL = "detail"; public static final String ID = "id"; public static final String SERVER_URL = "server-url"; @@ -17,7 +17,4 @@ public class Constants { public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String TOKEN_URL = "tokenURL"; - - - } diff --git a/src/main/java/iudx/gis/server/database/util/Util.java b/src/main/java/iudx/gis/server/database/util/Util.java index a65a64a..71292d1 100644 --- a/src/main/java/iudx/gis/server/database/util/Util.java +++ b/src/main/java/iudx/gis/server/database/util/Util.java @@ -1,9 +1,9 @@ package iudx.gis.server.database.util; +import static iudx.gis.server.database.util.Constants.*; + import io.vertx.core.json.JsonObject; -import iudx.gis.server.apiserver.response.ResponseUrn; import iudx.gis.server.apiserver.util.HttpStatusCode; -import static iudx.gis.server.database.util.Constants.*; public class Util { public static JsonObject getResponse(HttpStatusCode code, String urn, String error) { diff --git a/src/main/java/iudx/gis/server/databroker/DataBrokerService.java b/src/main/java/iudx/gis/server/databroker/DataBrokerService.java index cc7e354..a03e0ee 100644 --- a/src/main/java/iudx/gis/server/databroker/DataBrokerService.java +++ b/src/main/java/iudx/gis/server/databroker/DataBrokerService.java @@ -12,13 +12,15 @@ @VertxGen @ProxyGen public interface DataBrokerService { - @Fluent - DataBrokerService publishMessage(JsonObject body, String toExchange, - String routingKey, - Handler> handler); @GenIgnore static DataBrokerService createProxy(Vertx vertx, String address) { return new DataBrokerServiceVertxEBProxy(vertx, address); } -} \ No newline at end of file + @Fluent + DataBrokerService publishMessage( + JsonObject body, + String toExchange, + String routingKey, + Handler> handler); +} diff --git a/src/main/java/iudx/gis/server/databroker/DataBrokerServiceImpl.java b/src/main/java/iudx/gis/server/databroker/DataBrokerServiceImpl.java index 0ef9638..abae1cd 100644 --- a/src/main/java/iudx/gis/server/databroker/DataBrokerServiceImpl.java +++ b/src/main/java/iudx/gis/server/databroker/DataBrokerServiceImpl.java @@ -31,8 +31,11 @@ public DataBrokerService publishMessage( Buffer buffer = Buffer.buffer(body.toString()); - if (!client.isConnected()) rabbitMqClientStartFuture = client.start(); - else rabbitMqClientStartFuture = Future.succeededFuture(); + if (!client.isConnected()) { + rabbitMqClientStartFuture = client.start(); + } else { + rabbitMqClientStartFuture = Future.succeededFuture(); + } rabbitMqClientStartFuture .compose(rabbitStartupFuture -> client.basicPublish(toExchange, routingKey, buffer)) diff --git a/src/main/java/iudx/gis/server/databroker/DataBrokerVerticle.java b/src/main/java/iudx/gis/server/databroker/DataBrokerVerticle.java index 9fd9fbe..321d5d6 100644 --- a/src/main/java/iudx/gis/server/databroker/DataBrokerVerticle.java +++ b/src/main/java/iudx/gis/server/databroker/DataBrokerVerticle.java @@ -3,13 +3,10 @@ import static iudx.gis.server.common.Constants.DATABROKER_SERVICE_ADDRESS; import io.vertx.core.AbstractVerticle; -import io.vertx.core.eventbus.MessageConsumer; -import io.vertx.core.json.JsonObject; import io.vertx.rabbitmq.RabbitMQClient; import io.vertx.rabbitmq.RabbitMQOptions; import io.vertx.serviceproxy.ServiceBinder; -import iudx.gis.server.cache.CacheService; -import iudx.gis.server.common.VHosts; +import iudx.gis.server.common.VirtualHosts; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,7 +17,7 @@ public class DataBrokerVerticle extends AbstractVerticle { private RabbitMQOptions config; private RabbitMQClient client; private DataBrokerService databroker; - private String dataBrokerIP; + private String dataBrokerIp; private int dataBrokerPort; private String dataBrokerUserName; private String dataBrokerPassword; @@ -33,12 +30,11 @@ public class DataBrokerVerticle extends AbstractVerticle { private String virtualHost; private ServiceBinder binder; - private MessageConsumer consumer; @Override public void start() throws Exception { - dataBrokerIP = config().getString("dataBrokerIP"); + dataBrokerIp = config().getString("dataBrokerIP"); dataBrokerPort = config().getInteger("dataBrokerPort"); dataBrokerUserName = config().getString("dataBrokerUserName"); dataBrokerPassword = config().getString("dataBrokerPassword"); @@ -48,14 +44,14 @@ public void start() throws Exception { requestedChannelMax = config().getInteger("requestedChannelMax"); networkRecoveryInterval = config().getInteger("networkRecoveryInterval"); automaticRecoveryEnabled = config().getBoolean("automaticRecoveryEnabled"); - virtualHost = config().getString(VHosts.IUDX_INTERNAL.value); + virtualHost = config().getString(VirtualHosts.IUDX_INTERNAL.value); /* Configure the RabbitMQ Data Broker client with input from config files. */ config = new RabbitMQOptions(); config.setUser(dataBrokerUserName); config.setPassword(dataBrokerPassword); - config.setHost(dataBrokerIP); + config.setHost(dataBrokerIp); config.setPort(dataBrokerPort); config.setConnectionTimeout(connectionTimeout); config.setRequestedHeartbeat(requestedHeartbeat); @@ -68,8 +64,7 @@ public void start() throws Exception { client = RabbitMQClient.create(vertx, config); databroker = new DataBrokerServiceImpl(client); binder = new ServiceBinder(vertx); - consumer = - binder.setAddress(DATABROKER_SERVICE_ADDRESS).register(DataBrokerService.class, databroker); + binder.setAddress(DATABROKER_SERVICE_ADDRESS).register(DataBrokerService.class, databroker); LOGGER.info("Data-broker verticle started."); } diff --git a/src/main/java/iudx/gis/server/databroker/package-info.java b/src/main/java/iudx/gis/server/databroker/package-info.java index ac47a52..5333834 100644 --- a/src/main/java/iudx/gis/server/databroker/package-info.java +++ b/src/main/java/iudx/gis/server/databroker/package-info.java @@ -2,4 +2,4 @@ name = "iudx-gis-databroker-service") package iudx.gis.server.databroker; -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/gis/server/deploy/Deployer.java b/src/main/java/iudx/gis/server/deploy/Deployer.java index 3774aae..92011e7 100644 --- a/src/main/java/iudx/gis/server/deploy/Deployer.java +++ b/src/main/java/iudx/gis/server/deploy/Deployer.java @@ -1,18 +1,5 @@ package iudx.gis.server.deploy; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.LoggerContext; import com.hazelcast.config.Config; import com.hazelcast.config.DiscoveryStrategyConfig; import com.hazelcast.zookeeper.ZookeeperDiscoveryProperties; @@ -33,8 +20,8 @@ import io.vertx.core.cli.TypedOption; import io.vertx.core.eventbus.EventBusOptions; import io.vertx.core.http.HttpServerOptions; -import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; import io.vertx.core.metrics.MetricsOptions; import io.vertx.core.spi.cluster.ClusterManager; import io.vertx.micrometer.Label; @@ -42,17 +29,32 @@ import io.vertx.micrometer.VertxPrometheusOptions; import io.vertx.micrometer.backends.BackendRegistries; import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; /** - * Deploys clustered vert.x instance of the server. As a JAR, the application - * requires 3 runtime arguments: + * Deploys clustered vert.x instance of the server. As a JAR, the application requires 3 runtime + * arguments: + * *
    - *
  • --config/-c : path to the config file
  • - *
  • --hostname/-i : the hostname for clustering
  • - *
  • --modules/-m : comma separated list of module names to deploy
  • + *
  • --config/-c : path to the config file + *
  • --hostname/-i : the hostname for clustering + *
  • --modules/-m : comma separated list of module names to deploy *
* - * e.g. java -jar ./fatjar.jar --host $(hostname) -c configs/config.json -m iudx.gis.server.authenticator.AuthenticationVerticle + *

e.g. java -jar ./fatjar.jar --host $(hostname) -c configs/config.json -m + * iudx.gis.server.authenticator.AuthenticationVerticle * ,iudx.gis.server.database.DatabaseVerticle */ public class Deployer { @@ -75,10 +77,9 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { JsonObject moduleConfiguration = getConfigForModule(i, configs); String moduleName = moduleConfiguration.getString("id"); int numInstances = moduleConfiguration.getInteger("verticleInstances"); - vertx.deployVerticle(moduleName, - new DeploymentOptions() - .setInstances(numInstances) - .setConfig(moduleConfiguration), + vertx.deployVerticle( + moduleName, + new DeploymentOptions().setInstances(numInstances).setConfig(moduleConfiguration), ar -> { if (ar.succeeded()) { LOGGER.info("Deployed " + moduleName); @@ -88,11 +89,7 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { } }); } - private static JsonObject getConfigForModule(int moduleIndex,JsonObject configurations) { - JsonObject commonConfigs=configurations.getJsonObject("commonConfig"); - JsonObject config = configurations.getJsonArray("modules").getJsonObject(moduleIndex); - return config.mergeIn(commonConfigs, true); - } + /** * Recursively deploy modules/verticles (if they exist) present in the `modules` list. * @@ -109,21 +106,26 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, List JsonArray configuredModules = configs.getJsonArray("modules"); String moduleName = modules.get(0); - JsonObject config = configuredModules.stream().map(obj -> (JsonObject) obj) - .filter(obj -> obj.getString("id").equals(moduleName)).findFirst().orElse(new JsonObject()); + JsonObject config = + 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"); return; } - //get common configs and add this to config object - JsonObject commonConfigs=configs.getJsonObject("commonConfig"); + // get common configs and add this to config object + JsonObject commonConfigs = configs.getJsonObject("commonConfig"); config.mergeIn(commonConfigs, true); - int numInstances = config.getInteger("verticleInstances"); - vertx.deployVerticle(moduleName, - new DeploymentOptions().setInstances(numInstances).setConfig(config), ar -> { + vertx.deployVerticle( + moduleName, + new DeploymentOptions().setInstances(numInstances).setConfig(config), + ar -> { if (ar.succeeded()) { LOGGER.info("Deployed " + moduleName); modules.remove(0); @@ -134,9 +136,14 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, List }); } - public static ClusterManager getClusterManager(String host, - List zookeepers, - String clusterID) { + private static JsonObject getConfigForModule(int moduleIndex, JsonObject configurations) { + JsonObject commonConfigs = configurations.getJsonObject("commonConfig"); + JsonObject config = configurations.getJsonArray("modules").getJsonObject(moduleIndex); + return config.mergeIn(commonConfigs, true); + } + + public static ClusterManager getClusterManager( + String host, List zookeepers, String clusterId) { Config config = new Config(); config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); config.getNetworkConfig().setPublicAddress(host); @@ -144,10 +151,11 @@ public static ClusterManager getClusterManager(String host, config.setProperty("hazelcast.logging.type", "log4j2"); DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(new ZookeeperDiscoveryStrategyFactory()); - discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.ZOOKEEPER_URL.key(), - String.join(",", zookeepers)); - discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.GROUP.key(), clusterID); - config.getNetworkConfig() + discoveryStrategyConfig.addProperty( + ZookeeperDiscoveryProperties.ZOOKEEPER_URL.key(), String.join(",", zookeepers)); + discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.GROUP.key(), clusterId); + config + .getNetworkConfig() .getJoin() .getDiscoveryConfig() .addDiscoveryStrategyConfig(discoveryStrategyConfig); @@ -163,12 +171,12 @@ public static MetricsOptions getMetricsOptions() { .setStartEmbeddedServer(true) .setEmbeddedServerOptions(new HttpServerOptions().setPort(9000))) // .setPublishQuantiles(true)) - .setLabels(EnumSet.of(Label.EB_ADDRESS, Label.EB_FAILURE, Label.HTTP_CODE, - Label.HTTP_METHOD)) + .setLabels( + EnumSet.of(Label.EB_ADDRESS, Label.EB_FAILURE, Label.HTTP_CODE, Label.HTTP_METHOD)) .setEnabled(true); } - public static void setJVMmetrics() { + public static void setJvmMetrics() { MeterRegistry registry = BackendRegistries.getDefaultNow(); LOGGER.debug(registry); new ClassLoaderMetrics().bindTo(registry); @@ -176,7 +184,6 @@ public static void setJVMmetrics() { new JvmGcMetrics().bindTo(registry); new ProcessorMetrics().bindTo(registry); new JvmThreadMetrics().bindTo(registry); - } public static void deploy(String configPath, String host, List modules) { @@ -196,99 +203,126 @@ public static void deploy(String configPath, String host, List modules) String clusterId = configuration.getString("clusterId"); mgr = getClusterManager(host, zookeepers, clusterId); EventBusOptions ebOptions = new EventBusOptions().setClusterPublicHost(host); - VertxOptions options = new VertxOptions().setClusterManager(mgr).setEventBusOptions(ebOptions) - .setMetricsOptions(getMetricsOptions()); + VertxOptions options = + new VertxOptions() + .setClusterManager(mgr) + .setEventBusOptions(ebOptions) + .setMetricsOptions(getMetricsOptions()); LOGGER.debug("metrics-options" + options.getMetricsOptions()); - Vertx.clusteredVertx(options, res -> { - if (res.succeeded()) { - vertx = res.result(); - LOGGER.debug(vertx.isMetricsEnabled()); - setJVMmetrics(); - if (modules.isEmpty()) { - recursiveDeploy(vertx, configuration, 0); - } else { - recursiveDeploy(vertx, configuration, modules); - } - } else { - LOGGER.fatal("Could not join cluster"); - } - }); - + Vertx.clusteredVertx( + options, + res -> { + if (res.succeeded()) { + vertx = res.result(); + LOGGER.debug(vertx.isMetricsEnabled()); + setJvmMetrics(); + if (modules.isEmpty()) { + recursiveDeploy(vertx, configuration, 0); + } else { + recursiveDeploy(vertx, configuration, modules); + } + } else { + LOGGER.fatal("Could not join cluster"); + } + }); } public static void gracefulShutdown() { - Set deployIDSet = vertx.deploymentIDs(); - Logger LOGGER = LogManager.getLogger(Deployer.class); - LOGGER.info("Shutting down the application"); - CountDownLatch latch_verticles = new CountDownLatch(deployIDSet.size()); - CountDownLatch latch_cluster = new CountDownLatch(1); - CountDownLatch latch_vertx = new CountDownLatch(1); - LOGGER.debug("number of verticles being undeployed are:" + deployIDSet.size()); + Set deployIdSet = vertx.deploymentIDs(); + Logger logger = LogManager.getLogger(Deployer.class); + logger.info("Shutting down the application"); + CountDownLatch latchVerticles = new CountDownLatch(deployIdSet.size()); + CountDownLatch latchCluster = new CountDownLatch(1); + CountDownLatch latchVertx = new CountDownLatch(1); + logger.debug("number of verticles being undeployed are:" + deployIdSet.size()); // shutdown verticles - for (String deploymentID : deployIDSet) { - vertx.undeploy(deploymentID, handler -> { - if (handler.succeeded()) { - LOGGER.debug(deploymentID + " verticle successfully Undeployed"); - latch_verticles.countDown(); - } else { - LOGGER.warn(deploymentID + "Undeploy failed!"); - } - - }); + for (String deploymentId : deployIdSet) { + vertx.undeploy( + deploymentId, + handler -> { + if (handler.succeeded()) { + logger.debug(deploymentId + " verticle successfully Undeployed"); + latchVerticles.countDown(); + } else { + logger.warn(deploymentId + "Undeploy failed!"); + } + }); } try { - latch_verticles.await(5, TimeUnit.SECONDS); - LOGGER.info("All the verticles undeployed"); + latchVerticles.await(5, TimeUnit.SECONDS); + logger.info("All the verticles undeployed"); Promise promise = Promise.promise(); // leave cluster mgr.leave(promise); - LOGGER.info("vertx left cluster succesfully"); + logger.info("vertx left cluster succesfully"); } catch (Exception e) { e.printStackTrace(); } try { - latch_cluster.await(5, TimeUnit.SECONDS); + latchCluster.await(5, TimeUnit.SECONDS); // shutdown vertx - vertx.close(handler -> { - if (handler.succeeded()) { - LOGGER.info("vertx closed succesfully"); - latch_vertx.countDown(); - } else { - LOGGER.warn("Vertx didn't close properly, reason:" + handler.cause()); - } - }); + vertx.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(); } try { - latch_vertx.await(5, TimeUnit.SECONDS); + latchVertx.await(5, TimeUnit.SECONDS); // then shut down log4j if (LogManager.getContext() instanceof LoggerContext) { - LOGGER.debug("Shutting down log4j2"); + logger.debug("Shutting down log4j2"); LogManager.shutdown((LoggerContext) LogManager.getContext()); - } else - LOGGER.warn("Unable to shutdown log4j2"); + } else { + logger.warn("Unable to shutdown log4j2"); + } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { - CLI cli = CLI.create("IUDX GIS Server") - .setSummary("A CLI to deploy the GIS 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("host").setShortName("i").setRequired(true) - .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("IUDX GIS Server") + .setSummary("A CLI to deploy the GIS 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("host") + .setShortName("i") + .setRequired(true) + .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); @@ -311,4 +345,3 @@ public static void main(String[] args) { } } } - diff --git a/src/main/java/iudx/gis/server/deploy/DeployerDev.java b/src/main/java/iudx/gis/server/deploy/DeployerDev.java index 1f0dd0b..4dd1faf 100644 --- a/src/main/java/iudx/gis/server/deploy/DeployerDev.java +++ b/src/main/java/iudx/gis/server/deploy/DeployerDev.java @@ -8,13 +8,12 @@ import io.vertx.core.cli.Option; import io.vertx.core.eventbus.EventBusOptions; import io.vertx.core.json.JsonObject; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Deploys non-clustered vert.x instance of the server. As a JAR, the application requires 1 runtime @@ -24,16 +23,17 @@ *

  • --config/-c : path to the config file * * - * e.g. java -jar ./fatjar.jar -c configs/config.json + *

    e.g. java -jar ./fatjar.jar -c configs/config.json */ public class DeployerDev { private static final Logger LOGGER = LogManager.getLogger(DeployerDev.class); - private static JsonObject getConfigForModule(int moduleIndex,JsonObject configurations) { - JsonObject commonConfigs=configurations.getJsonObject("commonConfig"); + private static JsonObject getConfigForModule(int moduleIndex, JsonObject configurations) { + JsonObject commonConfigs = configurations.getJsonObject("commonConfig"); JsonObject config = configurations.getJsonArray("modules").getJsonObject(moduleIndex); return config.mergeIn(commonConfigs, true); } + public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { if (i >= configs.getJsonArray("modules").size()) { LOGGER.info("Deployed all"); @@ -42,8 +42,10 @@ public static void recursiveDeploy(Vertx vertx, JsonObject configs, int i) { JsonObject moduleConfiguration = getConfigForModule(i, configs); String moduleName = moduleConfiguration.getString("id"); int numInstances = moduleConfiguration.getInteger("verticleInstances"); - vertx.deployVerticle(moduleName, - new DeploymentOptions().setInstances(numInstances).setConfig(moduleConfiguration), ar -> { + vertx.deployVerticle( + moduleName, + new DeploymentOptions().setInstances(numInstances).setConfig(moduleConfiguration), + ar -> { if (ar.succeeded()) { LOGGER.info("Deployed " + moduleName); recursiveDeploy(vertx, configs, i + 1); @@ -74,11 +76,21 @@ public static void deploy(String configPath) { } public static void main(String[] args) { - CLI cli = CLI.create("IUDX GIS Interface").setSummary("A CLI to deploy the resource 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")); + CLI cli = + CLI.create("IUDX GIS Interface") + .setSummary("A CLI to deploy the resource 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")); StringBuilder usageString = new StringBuilder(); cli.usage(usageString); diff --git a/src/main/java/iudx/gis/server/metering/MeteringService.java b/src/main/java/iudx/gis/server/metering/MeteringService.java index e8a673e..d85f069 100644 --- a/src/main/java/iudx/gis/server/metering/MeteringService.java +++ b/src/main/java/iudx/gis/server/metering/MeteringService.java @@ -17,7 +17,8 @@ public interface MeteringService { static MeteringService createProxy(Vertx vertx, String address) { return new MeteringServiceVertxEBProxy(vertx, address); } + @Fluent - MeteringService insertMeteringValuesInRMQ( + MeteringService insertMeteringValuesInRmq( JsonObject request, Handler> handler); } diff --git a/src/main/java/iudx/gis/server/metering/MeteringServiceImpl.java b/src/main/java/iudx/gis/server/metering/MeteringServiceImpl.java index beba7b8..9ca6960 100644 --- a/src/main/java/iudx/gis/server/metering/MeteringServiceImpl.java +++ b/src/main/java/iudx/gis/server/metering/MeteringServiceImpl.java @@ -29,10 +29,10 @@ public MeteringServiceImpl(DataBrokerService dataBrokerService, JsonObject confi } @Override - public MeteringService insertMeteringValuesInRMQ( + public MeteringService insertMeteringValuesInRmq( JsonObject request, Handler> handler) { - JsonObject writeMessage = queryBuilder.buildMessageForRMQ(request,config); + JsonObject writeMessage = queryBuilder.buildMessageForRmq(request, config); dataBrokerService.publishMessage( writeMessage, diff --git a/src/main/java/iudx/gis/server/metering/MeteringVerticle.java b/src/main/java/iudx/gis/server/metering/MeteringVerticle.java index 91686d6..67e120a 100644 --- a/src/main/java/iudx/gis/server/metering/MeteringVerticle.java +++ b/src/main/java/iudx/gis/server/metering/MeteringVerticle.java @@ -1,6 +1,7 @@ package iudx.gis.server.metering; import static iudx.gis.server.common.Constants.*; + import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; @@ -18,13 +19,12 @@ public class MeteringVerticle extends AbstractVerticle { private DataBrokerService dataBrokerService; private JsonObject config; - @Override public void start() { config = config(); - dataBrokerService = DataBrokerService.createProxy(vertx,DATABROKER_SERVICE_ADDRESS); - metering = new MeteringServiceImpl(dataBrokerService,config); + dataBrokerService = DataBrokerService.createProxy(vertx, DATABROKER_SERVICE_ADDRESS); + metering = new MeteringServiceImpl(dataBrokerService, config); binder = new ServiceBinder(vertx); consumer = binder.setAddress(METERING_SERVICE_ADDRESS).register(MeteringService.class, metering); diff --git a/src/main/java/iudx/gis/server/metering/package-info.java b/src/main/java/iudx/gis/server/metering/package-info.java index f9ddb83..00ad016 100644 --- a/src/main/java/iudx/gis/server/metering/package-info.java +++ b/src/main/java/iudx/gis/server/metering/package-info.java @@ -1,7 +1,4 @@ -@ModuleGen( - groupPackage = "iudx.gis.server.metering", - name = "iudx-gis-server-metering-service") +@ModuleGen(groupPackage = "iudx.gis.server.metering", name = "iudx-gis-server-metering-service") package iudx.gis.server.metering; import io.vertx.codegen.annotations.ModuleGen; - diff --git a/src/main/java/iudx/gis/server/metering/util/Constants.java b/src/main/java/iudx/gis/server/metering/util/Constants.java index 293628c..d087118 100644 --- a/src/main/java/iudx/gis/server/metering/util/Constants.java +++ b/src/main/java/iudx/gis/server/metering/util/Constants.java @@ -10,7 +10,7 @@ public class Constants { public static final String DETAIL = "detail"; public static final String TITLE = "title"; public static final String RESULTS = "results"; - public static final String PRIMARY_KEY= "primaryKey"; + public static final String PRIMARY_KEY = "primaryKey"; public static final String PROVIDER_ID = "providerID"; public static final String ORIGIN = "origin"; public static final String ORIGIN_SERVER = "gis-server"; @@ -30,6 +30,7 @@ public class Constants { public static final String API = "api"; public static final String USER_ID = "userid"; public static final String WRITE_QUERY = - "INSERT INTO $0 (id,api,userid,epochtime,resourceid,isotime,providerid,size) VALUES ('$1','$2','$3',$4,'$5','$6','$7',$8)"; + "INSERT INTO $0 (id,api,userid,epochtime,resourceid,isotime,providerid,size) " + + "VALUES ('$1','$2','$3',$4,'$5','$6','$7',$8)"; public static final String MESSAGE = "message"; } diff --git a/src/main/java/iudx/gis/server/metering/util/QueryBuilder.java b/src/main/java/iudx/gis/server/metering/util/QueryBuilder.java index 13e3571..7dffaf6 100644 --- a/src/main/java/iudx/gis/server/metering/util/QueryBuilder.java +++ b/src/main/java/iudx/gis/server/metering/util/QueryBuilder.java @@ -1,7 +1,6 @@ package iudx.gis.server.metering.util; import static iudx.gis.server.metering.util.Constants.ADMIN; -import static iudx.gis.server.metering.util.Constants.ADMIN_BASE_PATH; import static iudx.gis.server.metering.util.Constants.API; import static iudx.gis.server.metering.util.Constants.ID; import static iudx.gis.server.metering.util.Constants.IID; @@ -9,12 +8,10 @@ import static iudx.gis.server.metering.util.Constants.ORIGIN_SERVER; import static iudx.gis.server.metering.util.Constants.PRIMARY_KEY; import static iudx.gis.server.metering.util.Constants.PROVIDER_ID; -import static iudx.gis.server.metering.util.Constants.USER_ID; import io.vertx.core.json.JsonObject; -import java.util.UUID; - import iudx.gis.server.common.Api; +import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -23,23 +20,24 @@ public class QueryBuilder { private static final Logger LOGGER = LogManager.getLogger(QueryBuilder.class); private static String adminBasePath; - public JsonObject buildMessageForRMQ(JsonObject request, JsonObject config) { - String primaryKey = UUID.randomUUID().toString().replace("-", ""); + public JsonObject buildMessageForRmq(JsonObject request, JsonObject config) { + String api = request.getString(API); adminBasePath = config.getString("adminBasePath"); - Api apiEndpoint = Api.getInstance(config.getString("dxApiBasePath"),adminBasePath); + Api apiEndpoint = Api.getInstance(config.getString("dxApiBasePath"), adminBasePath); String resourceId = api.equals(apiEndpoint.getAdminPath()) ? request.getString(IID) : request.getString(ID); - String providerID = + String providerId = api.equals(apiEndpoint.getAdminPath()) ? ADMIN : resourceId.substring(0, resourceId.indexOf('/', resourceId.indexOf('/') + 1)); + String primaryKey = UUID.randomUUID().toString().replace("-", ""); request.remove(IID); - request.put(ID,resourceId); + request.put(ID, resourceId); request.put(PRIMARY_KEY, primaryKey); - request.put(PROVIDER_ID, providerID); + request.put(PROVIDER_ID, providerId); request.put(ORIGIN, ORIGIN_SERVER); LOGGER.trace("Info: Request " + request); diff --git a/src/main/java/iudx/gis/server/metering/util/ResponseBuilder.java b/src/main/java/iudx/gis/server/metering/util/ResponseBuilder.java index b1173f6..b803849 100644 --- a/src/main/java/iudx/gis/server/metering/util/ResponseBuilder.java +++ b/src/main/java/iudx/gis/server/metering/util/ResponseBuilder.java @@ -12,12 +12,10 @@ import iudx.gis.server.apiserver.response.ResponseUrn; public class ResponseBuilder { - private final String status; private final JsonObject response; /** Initialise the object with Success or Failure. */ - public ResponseBuilder(String status) { - this.status = status; + public ResponseBuilder() { response = new JsonObject(); } diff --git a/src/test/java/iudx/gis/server/cache/CacheServiceTest.java b/src/test/java/iudx/gis/server/cache/CacheServiceTest.java index d808264..ac75d61 100644 --- a/src/test/java/iudx/gis/server/cache/CacheServiceTest.java +++ b/src/test/java/iudx/gis/server/cache/CacheServiceTest.java @@ -14,7 +14,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; -import iudx.gis.server.cache.cacheImpl.CacheType; +import iudx.gis.server.cache.cacheimpl.CacheType; import iudx.gis.server.database.postgres.PostgresService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/test/java/iudx/gis/server/cache/cacheImpl/RevokedClientCacheTest.java b/src/test/java/iudx/gis/server/cache/cacheimpl/RevokedClientCacheTest.java similarity index 86% rename from src/test/java/iudx/gis/server/cache/cacheImpl/RevokedClientCacheTest.java rename to src/test/java/iudx/gis/server/cache/cacheimpl/RevokedClientCacheTest.java index 8a62c85..2b2d757 100644 --- a/src/test/java/iudx/gis/server/cache/cacheImpl/RevokedClientCacheTest.java +++ b/src/test/java/iudx/gis/server/cache/cacheimpl/RevokedClientCacheTest.java @@ -1,30 +1,19 @@ -package iudx.gis.server.cache.cacheImpl; +package iudx.gis.server.cache.cacheimpl; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; import io.vertx.core.Vertx; -import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; -import io.vertx.junit5.VertxTestContext; -import iudx.gis.server.common.Constants; import iudx.gis.server.database.postgres.PostgresService; -import org.checkerframework.checker.signature.qual.DotSeparatedIdentifiers; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.Answer; import java.util.concurrent.TimeUnit; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; @ExtendWith({VertxExtension.class, MockitoExtension.class}) public class RevokedClientCacheTest { diff --git a/src/test/java/iudx/gis/server/metering/util/ResponseBuilderTest.java b/src/test/java/iudx/gis/server/metering/util/ResponseBuilderTest.java index 60f74f1..b691388 100644 --- a/src/test/java/iudx/gis/server/metering/util/ResponseBuilderTest.java +++ b/src/test/java/iudx/gis/server/metering/util/ResponseBuilderTest.java @@ -12,7 +12,7 @@ class ResponseBuilderTest { ResponseBuilder responseBuilder; @Test public void test(VertxTestContext vertxTestContext){ - responseBuilder=new ResponseBuilder("200"); + responseBuilder=new ResponseBuilder(); JsonArray jsonArray= new JsonArray().add(123); assertNotNull(responseBuilder.setCount(200));