From 861ad8ebfc2b7a5a8e9e706c19d1d09d2d0d87c8 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 4 Sep 2023 13:52:19 +0530 Subject: [PATCH 01/28] fixed file storage errors --- docker-compose.yml | 1 + .../registry/config/MinioClientConfig.java | 2 ++ .../registry/controller/FileStorageController.java | 2 ++ .../controller/RegistryEntityController.java | 12 ++++++++++-- .../sunbirdrc/registry/helper/RegistryHelper.java | 13 +++++++++++-- .../registry/service/FileStorageService.java | 2 ++ .../registry/service/impl/RegistryServiceImpl.java | 6 ------ .../registry/service/impl/SignatureServiceImpl.java | 12 ++++++++++-- java/registry/src/main/resources/application.yml | 1 + 9 files changed, 39 insertions(+), 12 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 4c520d8cf..6a70e820b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -63,6 +63,7 @@ services: - certificate_health_check_url=http://certificate-api:8078/health - template_base_url=http://registry:8081/api/v1/templates/ #Looks for certificate templates for pdf copy of the signed certificate - sunbird_keycloak_user_set_password=true + - filestorage_enabled=false - filestorage_connection_url=http://file-storage:9000 - filestorage_access_key=admin - filestorage_secret_key=12345678 diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java index 2da1c2252..b70ce573b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java @@ -6,10 +6,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration +@ConditionalOnProperty(name = "filestorage.enabled", havingValue = "true", matchIfMissing = true) public class MinioClientConfig { private static final Logger logger = LoggerFactory.getLogger(MinioClientConfig.class); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java index a937650be..fe359090a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java @@ -3,6 +3,7 @@ import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.model.dto.DocumentsResponse; import dev.sunbirdrc.registry.service.FileStorageService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -15,6 +16,7 @@ // TODO: Get should be viewed by both attestor and reviewer @Controller +@ConditionalOnBean(FileStorageService.class) public class FileStorageController { private final FileStorageService fileStorageService; private final RegistryHelper registryHelper; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 5b29c2af9..d00a7c06e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -15,6 +15,7 @@ import dev.sunbirdrc.registry.exception.ErrorMessages; import dev.sunbirdrc.registry.exception.RecordNotFoundException; import dev.sunbirdrc.registry.exception.UnAuthorizedException; +import dev.sunbirdrc.registry.exception.UnreachableException; import dev.sunbirdrc.registry.middleware.MiddlewareHaltException; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; @@ -59,7 +60,9 @@ public class RegistryEntityController extends AbstractController { @Autowired private ICertificateService certificateService; - @Autowired + @Value("${filestorage.enabled}") + private boolean fileStorageEnabled; + @Autowired(required = false) private FileStorageService fileStorageService; @Autowired @@ -540,7 +543,7 @@ public ResponseEntity getEntityType(@PathVariable String entityName, } - private String getTemplateUrlFromRequest(HttpServletRequest request, String entityName) { + private String getTemplateUrlFromRequest(HttpServletRequest request, String entityName) throws UnreachableException { if (externalTemplatesEnabled && !StringUtils.isEmpty(request.getHeader(Template))) { return request.getHeader(Template); } @@ -549,10 +552,15 @@ private String getTemplateUrlFromRequest(HttpServletRequest request, String enti if (!StringUtils.isEmpty(templateUri)) { try { if (templateUri.startsWith(MINIO_URI_PREFIX)) { + if (!fileStorageEnabled) { + throw new UnreachableException("File Storage Service is not enabled"); + } return fileStorageService.getSignedUrl(templateUri.substring(MINIO_URI_PREFIX.length())); } else if (templateUri.startsWith(HTTP_URI_PREFIX) || templateUri.startsWith(HTTPS_URI_PREFIX)) { return templateUri; } + } catch (UnreachableException e) { + throw e; } catch (Exception e) { logger.error("Exception while parsing certificate templates DID urls", e); return null; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 51327ae9b..fd52a444d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -23,6 +23,7 @@ import dev.sunbirdrc.registry.entities.RevokedCredential; import dev.sunbirdrc.registry.exception.SignatureException; import dev.sunbirdrc.registry.exception.UnAuthorizedException; +import dev.sunbirdrc.registry.exception.UnreachableException; import dev.sunbirdrc.registry.middleware.MiddlewareHaltException; import dev.sunbirdrc.registry.middleware.service.ConditionResolverService; import dev.sunbirdrc.registry.middleware.util.JSONUtil; @@ -136,7 +137,9 @@ public class RegistryHelper { @Autowired private ObjectMapper objectMapper; - @Autowired + @Value("${filestorage.enabled}") + private boolean fileStorageEnabled; + @Autowired(required = false) private FileStorageService fileStorageService; @Value("${database.uuidPropertyName}") @@ -431,8 +434,11 @@ public String triggerAttestation(AttestationRequest attestationRequest, Attestat } - private void updateGetFileUrl(JsonNode additionalInput) { + private void updateGetFileUrl(JsonNode additionalInput) throws UnreachableException { if(additionalInput!= null && additionalInput.has(FILE_URL)) { + if (!fileStorageEnabled) { + throw new UnreachableException("File Storage Service is not enabled"); + } ArrayNode fileUrls = (ArrayNode)(additionalInput.get(FILE_URL)); ArrayNode signedUrls = JsonNodeFactory.instance.arrayNode(); for (JsonNode fileNode : fileUrls) { @@ -656,6 +662,9 @@ private JsonNode generateInputForFunctionExecutor(String sourceEntity, JsonNode private void uploadAttestedFiles(PluginResponseMessage pluginResponseMessage, ObjectNode metaData) throws Exception { if (!CollectionUtils.isEmpty(pluginResponseMessage.getFiles())) { + if (!fileStorageEnabled) { + throw new UnreachableException("File Storage Service is not enabled"); + } ArrayNode fileUris = JsonNodeFactory.instance.arrayNode(); pluginResponseMessage.getFiles().forEach(file -> { String propertyURI = String.format("%s/%s/%s/documents/%s", pluginResponseMessage.getSourceEntity(), diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index a2541025b..03f3492aa 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java @@ -14,6 +14,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @@ -32,6 +33,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_FILE_STORAGE_SERVICE_NAME; @Service +@ConditionalOnBean(MinioClient.class) public class FileStorageService implements HealthIndicator { private static final Logger logger = LoggerFactory.getLogger(FileStorageService.class); private final MinioClient minioClient; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java index cee15e2f7..5c3180af7 100755 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java @@ -128,12 +128,6 @@ public class RegistryServiceImpl implements RegistryService { @Autowired private SchemaService schemaService; - @Autowired - private IElasticService elasticService; - - @Autowired - private FileStorageService fileStorageService; - @Autowired private List healthIndicators; public HealthCheckResponse health(Shard shard) throws Exception { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java index d522afd36..ff2b2bfb0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java @@ -44,7 +44,9 @@ public class SignatureServiceImpl implements SignatureService { @Autowired private ObjectMapper objectMapper; - @Autowired + @Value("${filestorage.enabled}") + private boolean fileStorageEnabled; + @Autowired(required = false) private FileStorageService fileStorageService; /** This method checks signature service is available or not @@ -72,6 +74,9 @@ public ComponentHealthInfo getHealthInfo() { private void replaceMinioURIWithSignedURL(Map signRequestObject) throws Exception { if (signRequestObject.containsKey(CREDENTIAL_TEMPLATE) && signRequestObject.get(CREDENTIAL_TEMPLATE) instanceof String && ((String) signRequestObject.get(CREDENTIAL_TEMPLATE)).startsWith(MINIO_URI_PREFIX)) { + if(!fileStorageEnabled) { + throw new SignatureException().new UnreachableException("File Storage is not enabled! Enable file storage to load credential template from Minio"); + } signRequestObject.put(CREDENTIAL_TEMPLATE, fileStorageService.getSignedUrl(((String) signRequestObject.get(CREDENTIAL_TEMPLATE)).substring(MINIO_URI_PREFIX.length()))); } } @@ -91,11 +96,14 @@ public Object sign(Map propertyValue) response = retryRestTemplate.postForEntity(signURL, propertyValue); result = objectMapper.readTree(response.getBody()); logger.info("Successfully generated signed credentials"); + } catch (SignatureException.UnreachableException ex) { + logger.error("SignatureException when signing: ", ex); + throw ex; } catch (RestClientException ex) { logger.error("RestClientException when signing: ", ex); throw new SignatureException().new UnreachableException(ex.getMessage()); } catch (Exception e) { - logger.error("RestClientException when signing: ", e); + logger.error("SignatureException when signing: ", e); throw new SignatureException().new CreationException(e.getMessage()); } return result; diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index aefd99c47..2774c5621 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -315,6 +315,7 @@ elastic: elastic_password: ${elastic_search_password:elastic} scheme: ${elastic_search_scheme:http} filestorage: + enabled: ${filestorage_enabled:false} url: ${filestorage_connection_url:http://localhost:9000} accesskey: ${filestorage_access_key:XXXXX} secretkey: ${filestorage_secret_key:XXXXX} From ea2eaa96135c2d7c771f0fc173bdeb8f9d6998c8 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 4 Sep 2023 14:44:51 +0530 Subject: [PATCH 02/28] added missing exception class file --- .../registry/exception/UnreachableException.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/exception/UnreachableException.java diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/exception/UnreachableException.java b/java/registry/src/main/java/dev/sunbirdrc/registry/exception/UnreachableException.java new file mode 100644 index 000000000..28e5e9a7f --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/exception/UnreachableException.java @@ -0,0 +1,9 @@ +package dev.sunbirdrc.registry.exception; + +public class UnreachableException extends CustomException { + private static final long serialVersionUID = 5384120386096139083L; + + public UnreachableException(String message) { + super("Unable to reach service: " + message); + } +} From 189c0f2d893ea3a96d36d692d477701931c7266d Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 4 Sep 2023 15:16:39 +0530 Subject: [PATCH 03/28] fixed tests failure --- .../sunbirdrc/registry/controller/FileStorageController.java | 4 ++-- .../dev/sunbirdrc/registry/service/FileStorageService.java | 4 ++-- services/digilocker-certificate-api/Dockerfile | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java index fe359090a..c8a3b1a14 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java @@ -3,7 +3,7 @@ import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.model.dto.DocumentsResponse; import dev.sunbirdrc.registry.service.FileStorageService; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -16,7 +16,7 @@ // TODO: Get should be viewed by both attestor and reviewer @Controller -@ConditionalOnBean(FileStorageService.class) +@ConditionalOnProperty(name = "filestorage.enabled", havingValue = "true", matchIfMissing = true) public class FileStorageController { private final FileStorageService fileStorageService; private final RegistryHelper registryHelper; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index 03f3492aa..2e0ed2c04 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java @@ -14,7 +14,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @@ -33,7 +33,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_FILE_STORAGE_SERVICE_NAME; @Service -@ConditionalOnBean(MinioClient.class) +@ConditionalOnProperty(name = "filestorage.enabled", havingValue = "true", matchIfMissing = true) public class FileStorageService implements HealthIndicator { private static final Logger logger = LoggerFactory.getLogger(FileStorageService.class); private final MinioClient minioClient; diff --git a/services/digilocker-certificate-api/Dockerfile b/services/digilocker-certificate-api/Dockerfile index 3c93cf8c0..a3c879637 100644 --- a/services/digilocker-certificate-api/Dockerfile +++ b/services/digilocker-certificate-api/Dockerfile @@ -1,7 +1,7 @@ ############################ # STEP 1 build executable binary ############################ -FROM golang:alpine AS builder +FROM golang:1.20-alpine3.18 AS builder RUN apk update && apk add --no-cache 'git=~2' ENV GO111MODULE=on WORKDIR $GOPATH/src/packages/digilocker-certificate-api/ From 222c5a3d50e3dd2ac9ca85a2989222a44a5c330d Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 4 Sep 2023 15:48:09 +0530 Subject: [PATCH 04/28] fixed elastic search issues --- .../dev/sunbirdrc/registry/config/GenericConfiguration.java | 3 +++ .../dev/sunbirdrc/registry/service/ElasticReadService.java | 5 ++--- .../dev/sunbirdrc/registry/service/ElasticSearchService.java | 3 ++- .../sunbirdrc/registry/service/impl/RegistryServiceImpl.java | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java index d3b143e4d..9b7b92b7b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java @@ -40,6 +40,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @@ -413,6 +414,8 @@ public TaskExecutor auditTaskExecutor() { * @return - IElasticService * @throws IOException */ + + @ConditionalOnProperty(name = "search.providerName", havingValue = "dev.sunbirdrc.registry.service.ElasticSearchService") @Bean public IElasticService elasticService() throws IOException { ElasticServiceImpl elasticService = new ElasticServiceImpl(); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java index a1ed5bc0b..1e77fa9d5 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java @@ -1,15 +1,13 @@ package dev.sunbirdrc.registry.service; import java.io.IOException; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; @@ -31,6 +29,7 @@ * */ @Component +@ConditionalOnProperty(name = "search.providerName", havingValue = "dev.sunbirdrc.registry.service.ElasticSearchService") public class ElasticReadService implements IReadService { private static Logger logger = LoggerFactory.getLogger(ElasticReadService.class); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java index 726c66d9d..2b0041f40 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java @@ -1,13 +1,13 @@ package dev.sunbirdrc.registry.service; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; @@ -29,6 +29,7 @@ * */ @Component +@ConditionalOnProperty(name = "search.providerName", havingValue = "dev.sunbirdrc.registry.service.ElasticSearchService") public class ElasticSearchService implements ISearchService { private static Logger logger = LoggerFactory.getLogger(ElasticSearchService.class); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java index 5c3180af7..ca8290664 100755 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java @@ -43,6 +43,7 @@ import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; import static dev.sunbirdrc.registry.Constants.Schema; import static dev.sunbirdrc.registry.exception.ErrorMessages.INVALID_ID_MESSAGE; @@ -141,7 +142,7 @@ public HealthCheckResponse health(Shard shard) throws Exception { }); healthCheck = new HealthCheckResponse(Constants.SUNBIRDRC_REGISTRY_API, overallHealthStatus.get(), checks); - logger.info("Heath Check : ", checks.toArray().toString()); + logger.info("Heath Check : {}", checks.stream().map(ComponentHealthInfo::getName).collect(Collectors.toList())); return healthCheck; } From 16799e5a1bca6f60bea049f3dbd5d3da856030fd Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 4 Sep 2023 18:48:41 +0530 Subject: [PATCH 05/28] fixed signing and certificate service logs --- .../controller/RegistryEntityController.java | 18 +++++++++++- .../controller/RegistryUtilsController.java | 29 +++++++++++++++---- .../registry/helper/RegistryHelper.java | 5 +++- .../registry/service/SignatureHelper.java | 17 +++++++++++ .../service/impl/CertificateServiceImpl.java | 2 ++ .../service/impl/RegistryServiceImpl.java | 4 +-- .../service/impl/SignatureServiceImpl.java | 2 ++ 7 files changed, 68 insertions(+), 9 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index d00a7c06e..ae143af8d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -50,6 +50,7 @@ import static dev.sunbirdrc.registry.Constants.*; import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; +import static dev.sunbirdrc.registry.service.SignatureHelper.SignatureNotEnabledResponse; @RestController public class RegistryEntityController extends AbstractController { @@ -57,7 +58,9 @@ public class RegistryEntityController extends AbstractController { private static final String TRANSACTION_ID = "transactionId"; private static Logger logger = LoggerFactory.getLogger(RegistryEntityController.class); - @Autowired + @Value("${signature.enabled}") + private boolean signatureEnabled; + @Autowired(required = false) private ICertificateService certificateService; @Value("${filestorage.enabled}") @@ -506,6 +509,9 @@ public ResponseEntity getEntityType(@PathVariable String entityName, @RequestHeader(required = false) String viewTemplateId) { ResponseParams responseParams = new ResponseParams(); Response response ; + if (!signatureEnabled) { + return SignatureNotEnabledResponse(null, responseParams); + } if (registryHelper.doesEntityOperationRequireAuthorization(entityName) && securityEnabled) { try { @@ -793,6 +799,10 @@ public ResponseEntity updateAttestationProperty( responseParams.setStatus(Response.Status.SUCCESSFUL); responseParams.setResultList(Collections.singletonList("response")); return new ResponseEntity<>(responseParams, HttpStatus.OK); + } catch (UnreachableException ex) { + responseParams.setErrmsg(ex.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(responseParams, HttpStatus.SERVICE_UNAVAILABLE); } catch (Exception exception) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(exception.getMessage()); @@ -806,6 +816,9 @@ public ResponseEntity updateAttestationProperty( public ResponseEntity getSignedEntityByToken(@PathVariable String entityName, HttpServletRequest request) { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); + if (!signatureEnabled) { + return SignatureNotEnabledResponse(response, responseParams); + } try { checkEntityNameInDefinitionManager(entityName); JsonNode result = registryHelper.getRequestedUserDetails(request, entityName); @@ -836,6 +849,9 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity public ResponseEntity getAttestationCertificate(HttpServletRequest request, @PathVariable String entityName, @PathVariable String entityId, @PathVariable String attestationName, @PathVariable String attestationId) { ResponseParams responseParams = new ResponseParams(); + if (!signatureEnabled) { + return SignatureNotEnabledResponse(null, responseParams); + } try { checkEntityNameInDefinitionManager(entityName); String readerUserId = getUserId(entityName, request); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java index 4df846a47..3e179b743 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java @@ -13,6 +13,7 @@ import dev.sunbirdrc.pojos.SunbirdRCInstrumentation; import dev.sunbirdrc.pojos.Response; import dev.sunbirdrc.pojos.ResponseParams; +import dev.sunbirdrc.registry.exception.UnreachableException; import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; @@ -49,7 +50,9 @@ public class RegistryUtilsController { private Type mapType = new TypeToken>() { }.getType(); - @Autowired + @Value("${signature.enabled}") + private boolean signatureEnabled; + @Autowired(required = false) private SignatureService signatureService; @Autowired @@ -80,7 +83,9 @@ public class RegistryUtilsController { public ResponseEntity generateSignature(HttpServletRequest requestModel) { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.SIGN, "OK", responseParams); - + if (!signatureEnabled) { + return getSignatureNotEnabledResponse(response, responseParams); + } try { watch.start("RegistryUtilsController.generateSignature"); Map requestBodyMap = apiMessage.getRequest().getRequestMap(); @@ -111,7 +116,9 @@ public ResponseEntity generateSignature(HttpServletRequest requestMode public ResponseEntity verifySignature(HttpServletRequest request) { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.VERIFY, "OK", responseParams); - + if (!signatureEnabled) { + return getSignatureNotEnabledResponse(response, responseParams); + } try { watch.start("RegistryUtilsController.verifySignature"); Map map = apiMessage.getRequest().getRequestMap(); @@ -181,7 +188,9 @@ public ResponseEntity verifySignature(HttpServletRequest request) { public ResponseEntity getKey( @PathVariable("id") String keyId) { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.KEYS, "OK", responseParams); - + if (!signatureEnabled) { + return getSignatureNotEnabledResponse(response, responseParams); + } try { watch.start("RegistryUtilsController.getKey"); String result = signatureService.getKey(keyId); @@ -206,6 +215,9 @@ public ResponseEntity health() { Response response = new Response(Response.API_ID.HEALTH, "OK", responseParams); try { + if (!signatureEnabled) { + throw new UnreachableException("Signature service not enabled!"); + } boolean healthCheckResult = signatureService.getHealthInfo().isHealthy(); HealthCheckResponse healthCheck = new HealthCheckResponse(Constants.SUNBIRD_SIGNATURE_SERVICE_NAME, healthCheckResult, null); @@ -219,7 +231,7 @@ public ResponseEntity health() { false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg("Error during health check"); + responseParams.setErrmsg("Error during health check: " + e.getMessage()); } return new ResponseEntity<>(response, HttpStatus.OK); } @@ -286,4 +298,11 @@ public ResponseEntity fetchAudit() { return new ResponseEntity<>(response, HttpStatus.OK); } + + private ResponseEntity getSignatureNotEnabledResponse(Response response, ResponseParams responseParams) { + responseParams.setErrmsg("Signature service not enabled!"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + response.setResponseCode("SERVICE_UNAVAILABLE"); + return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE); + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index fd52a444d..6ef75ad1f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -170,7 +170,7 @@ public class RegistryHelper { @Autowired private EntityTypeHandler entityTypeHandler; - @Autowired + @Autowired(required = false) private SignatureService signatureService; @Autowired @@ -576,6 +576,9 @@ public void updateState(PluginResponseMessage pluginResponseMessage) throws Exce // checking size greater than 1, bcz empty template contains osid field if (credentialTemplate != null) { JsonNode response = objectMapper.readTree(pluginResponseMessage.getResponse()); + if (!signatureEnabled) { + throw new UnreachableException("Signature service not enabled!"); + } Object signedData = getSignedDoc(response, credentialTemplate); metaData.put( ATTESTED_DATA, diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java index 4bae26ecd..9cdcbd6b5 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java @@ -5,10 +5,15 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import dev.sunbirdrc.pojos.Response; +import dev.sunbirdrc.pojos.ResponseParams; import dev.sunbirdrc.registry.exception.SignatureException; import dev.sunbirdrc.registry.middleware.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import java.time.Instant; @@ -16,6 +21,7 @@ import java.util.Map; @Component +@ConditionalOnProperty(name = "signature.enabled", havingValue = "true") public class SignatureHelper { @Autowired private SignatureService signatureService; @@ -149,4 +155,15 @@ public String removeEntitySignature(String entityNodeType, ObjectNode node) { } return entitySignatureUUID; } + + public static ResponseEntity SignatureNotEnabledResponse(Response response, ResponseParams responseParams) { + responseParams.setErrmsg("Signature service not enabled!"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + if (response != null) { + response.setResponseCode("SERVICE_UNAVAILABLE"); + } else { + response = new Response(Response.API_ID.GET, "SERVICE_UNAVAILABLE", responseParams); + } + return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE); + } } \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index 09ba766f7..6c7c0bf7c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -8,6 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; @@ -25,6 +26,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_CERTIFICATE_SERVICE_NAME; @Component +@ConditionalOnProperty(name = "signature.enabled", havingValue = "true") public class CertificateServiceImpl implements ICertificateService { private final String templateBaseUrl; private final String certificateUrl; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java index ca8290664..e34a416b2 100755 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java @@ -59,14 +59,14 @@ public class RegistryServiceImpl implements RegistryService { private EntityTypeHandler entityTypeHandler; @Autowired private EncryptionService encryptionService; - @Autowired + @Autowired(required = false) private SignatureService signatureService; @Autowired private IDefinitionsManager definitionsManager; @Autowired private EncryptionHelper encryptionHelper; - @Autowired + @Autowired(required = false) private SignatureHelper signatureHelper; @Autowired private EntityTransformer entityTransformer; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java index ff2b2bfb0..e141ef943 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java @@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -26,6 +27,7 @@ import static dev.sunbirdrc.registry.Constants.MINIO_URI_PREFIX; @Component +@ConditionalOnProperty(name = "signature.enabled", havingValue = "true") public class SignatureServiceImpl implements SignatureService { private static Logger logger = LoggerFactory.getLogger(SignatureService.class); From fa87187ed7fcd2b660aa9a332430d6959ec84a4e Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Tue, 5 Sep 2023 20:00:50 +0530 Subject: [PATCH 06/28] fixed errors for audit, notification, encryption, swagger, Api Message, keycloak --- docker-compose.yml | 3 ++- .../sunbirdrc/keycloak/KeycloakAdminUtil.java | 4 ++++ .../java/dev/sunbirdrc/pojos/APIMessage.java | 12 ++++++---- .../registry/config/GenericConfiguration.java | 9 +++++++- .../controller/RegistrySwaggerController.java | 18 +++++++++++++++ .../sunbirdrc/registry/dao/VertexReader.java | 2 +- .../registry/helper/RegistryHelper.java | 23 +++++++++++-------- .../registry/service/DecryptionHelper.java | 2 ++ .../registry/service/EncryptionHelper.java | 2 ++ .../registry/service/NotificationHelper.java | 3 +++ .../registry/service/impl/AuditDBImpl.java | 5 ++-- .../registry/service/impl/AuditFileImpl.java | 3 ++- .../service/impl/EncryptionServiceImpl.java | 4 +++- .../service/impl/RegistryServiceImpl.java | 20 ++++++++-------- .../src/main/resources/application.yml | 9 ++++++-- 15 files changed, 85 insertions(+), 34 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 6a70e820b..fc051f857 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -40,6 +40,7 @@ services: - connectionInfo_uri=jdbc:postgresql://db:5432/registry - connectionInfo_username=postgres - connectionInfo_password=postgres + - encryption_enabled=${ENCRYPTION_ENABLED-false} - event_enabled=${EVENT_ENABLED-false} - event_topic=events - event_providerName=dev.sunbirdrc.registry.service.impl.KafkaEventService @@ -214,7 +215,7 @@ services: zookeeper: condition: service_started ports: - - "9092:9092" + - "9094:9094" environment: KAFKA_BROKER_ID: "1" KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" diff --git a/java/middleware/registry-middleware/keycloak/src/main/java/dev/sunbirdrc/keycloak/KeycloakAdminUtil.java b/java/middleware/registry-middleware/keycloak/src/main/java/dev/sunbirdrc/keycloak/KeycloakAdminUtil.java index da0a3e2ae..9705aa932 100644 --- a/java/middleware/registry-middleware/keycloak/src/main/java/dev/sunbirdrc/keycloak/KeycloakAdminUtil.java +++ b/java/middleware/registry-middleware/keycloak/src/main/java/dev/sunbirdrc/keycloak/KeycloakAdminUtil.java @@ -19,6 +19,7 @@ import org.springframework.stereotype.Component; import java.util.*; +import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import static dev.sunbirdrc.registry.middleware.util.Constants.CONNECTION_FAILURE; @@ -130,6 +131,9 @@ private String createOrUpdateRealmGroup(String entityName) { private RoleRepresentation createOrGetRealmRole(String entityName) { RolesResource rolesResource = keycloak.realm(realm).roles(); try { + return rolesResource.get(entityName).toRepresentation(); + } catch (NotFoundException ex) { + logger.error("Role {} not found. Creating role {}", entityName, entityName); RoleRepresentation roleRepresentation = new RoleRepresentation(); roleRepresentation.setName(entityName); rolesResource.create(roleRepresentation); diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java index 4df2e7ae3..0d2fe21b3 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java @@ -38,11 +38,13 @@ public APIMessage(HttpServletRequest servletRequest) { request = new Request(); requestWrapper = new RequestWrapper(servletRequest); String body = requestWrapper.getBody(); - try { - request = new ObjectMapper().readValue(body, Request.class); - } catch (IOException jpe) { - logger.error("Can't read request body", jpe); - request = null; + if(body != null && !body.isEmpty()) { + try { + request = new ObjectMapper().readValue(body, Request.class); + } catch (IOException jpe) { + logger.error("Can't read request body", jpe); + request = null; + } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java index 9b7b92b7b..8400379c5 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java @@ -62,6 +62,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import java.util.HashSet; + +import static dev.sunbirdrc.registry.Constants.ATTESTATION_POLICY; @Configuration @EnableRetry @@ -427,11 +431,14 @@ public IElasticService elasticService() throws IOException { elasticService.setUserName(username); elasticService.setPassword(password); elasticService.setScheme(scheme); - elasticService.init(iDefinitionsManager.getAllKnownDefinitions()); + Set indices = new HashSet<>(iDefinitionsManager.getAllKnownDefinitions()); + indices.add(ATTESTATION_POLICY); + elasticService.init(indices); } return elasticService; } + @ConditionalOnProperty(name = "notification.service.enabled", havingValue = "true") @Bean public NotificationService notificationService() { return new NotificationService(notificationServiceConnInfo, notificationServiceHealthUrl, notificationServiceEnabled); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java index 599d4896e..b3b8820ee 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import dev.sunbirdrc.registry.helper.RegistryHelper; +import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.util.IDefinitionsManager; import dev.sunbirdrc.registry.util.RefResolver; import io.swagger.models.*; @@ -16,6 +17,7 @@ import io.swagger.util.Json; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -29,12 +31,19 @@ import static dev.sunbirdrc.registry.Constants.TITLE; @RestController +@ConditionalOnProperty(name = "api-swagger.enabled", havingValue = "true") public class RegistrySwaggerController { private final IDefinitionsManager definitionsManager; private final RefResolver refResolver; private final ObjectMapper objectMapper; @Value("${registry.schema.url}") private String schemaUrl; + @Value("${api-swagger.title}") + private String swaggerTitle; + @Value("${api-swagger.description}") + private String swaggerDescription; + @Value("${api-swagger.version}") + private String swaggerVersion; private RegistryHelper registryHelper; @@ -81,6 +90,7 @@ private ObjectNode generateAPIMethods(Set entities, HttpServletRequest r doc.set("definitions", definitions); doc.set("host", getHost(request)); doc.set("schemes", JsonNodeFactory.instance.arrayNode().add(request.getScheme())); + doc.set("info", getApiInfo()); for (String entityName : entities) { if (Character.isUpperCase(entityName.charAt(0))) { populateEntityActions(paths, entityName); @@ -261,4 +271,12 @@ private void addResponseType(ObjectNode path, Operation operation, String operat } }); } + + private JsonNode getApiInfo() throws IOException { + Info info = new Info() + .title(swaggerTitle) + .version(swaggerVersion) + .description(swaggerDescription); + return JSONUtil.convertObjectJsonNode(info); + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/VertexReader.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/VertexReader.java index e1329c47c..b919356b1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/VertexReader.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/VertexReader.java @@ -478,7 +478,7 @@ public JsonNode readInternal(Vertex rootVertex) throws Exception { printUuidNodeMap(); - logger.info("Finished loading information. Start creating the response"); + logger.debug("Finished loading information. Start creating the response"); ObjectNode entityNode = JsonNodeFactory.instance.objectNode(); // For the entity Node, now go and replace the array values with actual diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 6ef75ad1f..d05d30ab1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -92,7 +92,7 @@ public class RegistryHelper { @Value("${notification.service.enabled}") boolean notificationEnabled; @Value("${invite.required_validation_enabled}") boolean skipRequiredValidationForInvite = true; @Value("${invite.signature_enabled}") boolean skipSignatureForInvite = true; - @Autowired + @Autowired(required = false) private NotificationHelper notificationHelper; @Autowired private ShardManager shardManager; @@ -128,7 +128,9 @@ public class RegistryHelper { @Autowired private DBConnectionInfoMgr dbConnectionInfoMgr; - @Autowired + @Value("${encryption.enabled}") + private boolean encryptionEnabled; + @Autowired(required = false) private DecryptionHelper decryptionHelper; @Autowired @@ -203,13 +205,13 @@ public JsonNode removeFormatAttr(JsonNode requestBody) { */ public String addEntity(JsonNode inputJson, String userId) throws Exception { String entityId = addEntityHandler(inputJson, userId, false, false); - notificationHelper.sendNotification(inputJson, CREATE); + if(notificationEnabled) notificationHelper.sendNotification(inputJson, CREATE); return entityId; } public String inviteEntity(JsonNode inputJson, String userId) throws Exception { String entityId = addEntityHandler(inputJson, userId, skipRequiredValidationForInvite, skipSignatureForInvite); - notificationHelper.sendNotification(inputJson, INVITE); + if(notificationEnabled) notificationHelper.sendNotification(inputJson, INVITE); return entityId; } @@ -298,6 +300,9 @@ public JsonNode readEntity(String userId, String entityType, String label, boole if (viewTemplate != null) { ViewTransformer vTransformer = new ViewTransformer(); if (viewTemplateDecryptPrivateFields) { + if (!encryptionEnabled) { + throw new UnreachableException("Encryption should be enabled to decrypt private fields"); + } resultNode = includePrivateFields ? decryptionHelper.getDecryptedJson(resultNode) : resultNode; } resultNode = vTransformer.transform(viewTemplate, resultNode); @@ -378,7 +383,7 @@ public String updateProperty(JsonNode inputJson, String userId) throws Exception RecordIdentifier recordId = RecordIdentifier.parse(label); logger.info("Update Api: shard id: " + recordId.getShardLabel() + " for uuid: " + recordId.getUuid()); registryService.updateEntity(shard, userId, recordId.getUuid(), jsonString, false); - notificationHelper.sendNotification(inputJson, UPDATE); + if(notificationEnabled) notificationHelper.sendNotification(inputJson, UPDATE); return "SUCCESS"; } @@ -389,7 +394,7 @@ public void updateEntityAndState(JsonNode existingNode, JsonNode updatedNode, St updatedNode = entityStateHelper.applyWorkflowTransitions(existingNode, updatedNode, attestationPolicies); } updateEntity(updatedNode, userId); - notificationHelper.sendNotification(updatedNode, UPDATE); + if(notificationEnabled) notificationHelper.sendNotification(updatedNode, UPDATE); } public void addEntityProperty(String entityName, String entityId, JsonNode inputJson, HttpServletRequest request) throws Exception { @@ -913,7 +918,7 @@ public String authorizeManageEntity(HttpServletRequest request, String entityNam List managingRoles = getManageRoles(entityName); if (managingRoles.size() > 0) { - if (managingRoles.contains(ROLE_ANONYMOUS)) { + if (!securityEnabled || managingRoles.contains(ROLE_ANONYMOUS)) { return ROLE_ANONYMOUS; } Set userRoles = getUserRolesFromRequest(request); @@ -1036,7 +1041,7 @@ public Vertex deleteEntity(String entityName, String entityId, String userId) th Vertex vertex = registryService.deleteEntityById(shard, entityName, userId, recordId.getUuid()); VertexReader vertexReader = new VertexReader(shard.getDatabaseProvider(), vertex.graph(), configurator, uuidPropertyName, definitionsManager); JsonNode deletedNode = JsonNodeFactory.instance.objectNode().set(entityName, vertexReader.constructObject(vertex)); - notificationHelper.sendNotification(deletedNode, DELETE); + if(notificationEnabled) notificationHelper.sendNotification(deletedNode, DELETE); return vertex; } @@ -1156,7 +1161,7 @@ public void deleteAttestationPolicy(String entityName, AttestationPolicy attesta } public boolean doesEntityOperationRequireAuthorization(String entity) { - return !getManageRoles(entity).contains("anonymous") && (doesEntityContainOwnershipAttributes(entity) || getManageRoles(entity).size() > 0); + return securityEnabled && !getManageRoles(entity).contains("anonymous") && (doesEntityContainOwnershipAttributes(entity) || getManageRoles(entity).size() > 0); } boolean hasAttestationPropertiesChanged(JsonNode updatedNode, JsonNode existingNode, AttestationPolicy attestationPolicy, String entityName) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/DecryptionHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/DecryptionHelper.java index 5589299ac..8d99c5bfe 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/DecryptionHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/DecryptionHelper.java @@ -3,11 +3,13 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.registry.exception.EncryptionException; import dev.sunbirdrc.registry.util.PrivateField; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import java.util.Map; @Component +@ConditionalOnProperty(name = "encryption.enabled", havingValue = "true") public class DecryptionHelper extends PrivateField { public JsonNode getDecryptedJson(JsonNode rootNode) throws EncryptionException { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/EncryptionHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/EncryptionHelper.java index 906828307..361eb46e7 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/EncryptionHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/EncryptionHelper.java @@ -3,11 +3,13 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.registry.exception.EncryptionException; import dev.sunbirdrc.registry.util.PrivateField; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import java.util.Map; @Component +@ConditionalOnProperty(name = "encryption.enabled", havingValue = "true") public class EncryptionHelper extends PrivateField { protected Map performOperation(Map plainMap) throws EncryptionException { return encryptionService.encrypt(plainMap); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java index 36fafa781..d50973c26 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java @@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; import java.io.IOException; @@ -26,6 +27,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.MOBILE; @Service +@ConditionalOnProperty(name = "notification.service.enabled", havingValue = "true") public class NotificationHelper { private static Logger logger = LoggerFactory.getLogger(NotificationHelper.class); boolean notificationEnabled; @@ -46,6 +48,7 @@ public NotificationHelper() { } public void sendNotification(JsonNode inputJson, String operationType) throws Exception { + if (!notificationEnabled) return; String entityType = inputJson.fields().next().getKey(); List templates = getNotificationTemplate(entityType, operationType); Map objectNodeMap = (Map) JSONUtil.convertJsonNodeToMap(inputJson).get(entityType); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java index 7892c603d..6ddf2fa9d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @@ -14,16 +15,14 @@ import dev.sunbirdrc.pojos.AuditRecord; import dev.sunbirdrc.registry.exception.AuditFailedException; import dev.sunbirdrc.registry.middleware.util.Constants; -import dev.sunbirdrc.registry.model.DBConnectionInfo; import dev.sunbirdrc.registry.sink.shard.Shard; import dev.sunbirdrc.registry.sink.shard.ShardManager; -import dev.sunbirdrc.registry.util.Definition; -import dev.sunbirdrc.registry.util.IDefinitionsManager; /** * Audit service implementation for audit layer in the application */ @Component +@ConditionalOnExpression("${audit.enabled} and 'database'.equalsIgnoreCase('${audit.frame.store}')") public class AuditDBImpl extends AuditServiceImpl { private static Logger logger = LoggerFactory.getLogger(AuditDBImpl.class); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java index d8021325a..1168993ca 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java @@ -2,7 +2,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Primary; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; @@ -16,6 +16,7 @@ * Audit service implementation for audit layer in the application */ @Component +@ConditionalOnExpression("${audit.enabled} and 'file'.equalsIgnoreCase('${audit.frame.store}')") public class AuditFileImpl extends AuditServiceImpl { private static Logger logger = LoggerFactory.getLogger(AuditFileImpl.class); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java index 0bd5ade2d..cd708ea48 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java @@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -28,6 +29,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_ENCRYPTION_SERVICE_NAME; @Component +@ConditionalOnProperty(name = "encryption.enabled", havingValue = "true") public class EncryptionServiceImpl implements EncryptionService { private static Logger logger = LoggerFactory.getLogger(EncryptionServiceImpl.class); @@ -41,7 +43,7 @@ public class EncryptionServiceImpl implements EncryptionService { private String encryptionBatchUri; @Value("${decryption.batch.uri}") private String decryptionBatchUri; - @Value("${encryption.base}") + @Value("${encryption.healthCheckURL}") private String encryptionServiceHealthCheckUri; @Autowired private RetryRestTemplate retryRestTemplate; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java index e34a416b2..8652ab8c8 100755 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java @@ -57,14 +57,12 @@ public class RegistryServiceImpl implements RegistryService { @Autowired private EntityTypeHandler entityTypeHandler; - @Autowired - private EncryptionService encryptionService; @Autowired(required = false) private SignatureService signatureService; @Autowired private IDefinitionsManager definitionsManager; - @Autowired + @Autowired(required = false) private EncryptionHelper encryptionHelper; @Autowired(required = false) private SignatureHelper signatureHelper; @@ -129,20 +127,22 @@ public class RegistryServiceImpl implements RegistryService { @Autowired private SchemaService schemaService; - @Autowired + @Autowired(required = false) private List healthIndicators; public HealthCheckResponse health(Shard shard) throws Exception { HealthCheckResponse healthCheck; AtomicBoolean overallHealthStatus = new AtomicBoolean(true); List checks = new ArrayList<>(); - healthIndicators.parallelStream().forEach(healthIndicator -> { - ComponentHealthInfo healthInfo = healthIndicator.getHealthInfo(); - checks.add(healthInfo); - overallHealthStatus.set(overallHealthStatus.get() & healthInfo.isHealthy()); - }); + if (healthIndicators != null) { + healthIndicators.parallelStream().forEach(healthIndicator -> { + ComponentHealthInfo healthInfo = healthIndicator.getHealthInfo(); + checks.add(healthInfo); + overallHealthStatus.set(overallHealthStatus.get() & healthInfo.isHealthy()); + }); + } healthCheck = new HealthCheckResponse(Constants.SUNBIRDRC_REGISTRY_API, overallHealthStatus.get(), checks); - logger.info("Heath Check : {}", checks.stream().map(ComponentHealthInfo::getName).collect(Collectors.toList())); + logger.info("Heath Check : {}", checks.stream().map(ComponentHealthInfo::getName).collect(Collectors.toList())); return healthCheck; } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 2774c5621..87aa6369d 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -80,7 +80,7 @@ event: providerName: ${event_providerName:dev.sunbirdrc.registry.service.impl.KafkaEventService} kafka: - bootstrapAddress: ${kafka_bootstrap_address:localhost:9092} + bootstrapAddress: ${kafka_bootstrap_address:localhost:9094} createEntityTopic: ${kafka_create_entity_topic:create_entity} postCreateEntityTopic: ${kafka_post_create_entity_topic:post_create_entity} @@ -189,7 +189,7 @@ frame: encryption: enabled: ${encryption_enabled:false} - base: ${encryption_base:http://localhost:8013} + healthCheckURL: ${encryption_health_check_url:http://localhost:8013} uri: ${encryption_uri:http://localhost:8013/encrypt} batch: uri: ${encryption_batch_uri:http://localhost:8013/encrypt/obj} @@ -321,6 +321,11 @@ filestorage: secretkey: ${filestorage_secret_key:XXXXX} bucketname: ${filestorage_bucket_key:dummy} +api-swagger: + enabled: ${swagger_enabled:true} + title: ${swagger_title:Sunbird Registry and Credential} + description: ${swagger_description:Sunbird registry and credential api (SunbirdRC)} + version: ${swagger_version:1.0.0} --- From 9f2c1eef3f01f92feb03e129d717c5ba4e8469f3 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Wed, 6 Sep 2023 11:20:45 +0530 Subject: [PATCH 07/28] fixed registry helper tests failing --- .../java/dev/sunbirdrc/registry/helper/RegistryHelperTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java/registry/src/test/java/dev/sunbirdrc/registry/helper/RegistryHelperTest.java b/java/registry/src/test/java/dev/sunbirdrc/registry/helper/RegistryHelperTest.java index 5dcd4c904..933f18f5f 100644 --- a/java/registry/src/test/java/dev/sunbirdrc/registry/helper/RegistryHelperTest.java +++ b/java/registry/src/test/java/dev/sunbirdrc/registry/helper/RegistryHelperTest.java @@ -140,6 +140,8 @@ public void initMocks() { RuleEngineService ruleEngineService = new RuleEngineService(kieContainer, keycloakAdminUtil); registryHelper.entityStateHelper = new EntityStateHelper(definitionsManager, ruleEngineService, conditionResolverService, claimRequestClient); registryHelper.setDefinitionsManager(definitionsManager); + registryHelper.setNotificationEnabled(true); + registryHelper.setSecurityEnabled(true); } @Test From 17c824a0f7bbea9a09bb2df550ad9fab6e8254d2 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Wed, 6 Sep 2023 12:47:04 +0530 Subject: [PATCH 08/28] enabling certificate and claims only when enabled --- docker-compose.yml | 4 +++- .../controller/RegistryClaimsController.java | 2 ++ .../controller/RegistryEntityController.java | 14 ++++++++------ .../sunbirdrc/registry/helper/RegistryHelper.java | 13 +++++++++++++ .../registry/service/SignatureHelper.java | 11 ----------- .../service/impl/CertificateServiceImpl.java | 2 +- .../registry/util/ClaimRequestClient.java | 2 ++ java/registry/src/main/resources/application.yml | 2 ++ 8 files changed, 31 insertions(+), 19 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index fc051f857..42d713bc1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -55,11 +55,13 @@ services: - sunbird_sso_admin_client_id=${KEYCLOAK_ADMIN_CLIENT_ID-admin-api} - sunbird_sso_client_id=${KEYCLOAK_CLIENT_ID-registry-frontend} - sunbird_sso_admin_client_secret=${KEYCLOAK_SECRET} + - claims_enabled=false - claims_url=http://claim-ms:8082 + - signature_enabled=false - sign_url=http://certificate-signer:8079/sign - verify_url=http://certificate-signer:8079/verify - sign_health_check_url=http://certificate-signer:8079/health - - signature_enabled=true + - certificate_enabled=false - pdf_url=http://certificate-api:8078/api/v1/certificatePDF - certificate_health_check_url=http://certificate-api:8078/health - template_base_url=http://registry:8081/api/v1/templates/ #Looks for certificate templates for pdf copy of the signed certificate diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index edad915bf..9e1135178 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -16,6 +16,7 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -29,6 +30,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.USER_ID; @RestController +@ConditionalOnProperty(name = "claims.enabled", havingValue = "true") public class RegistryClaimsController extends AbstractController{ private static final Logger logger = LoggerFactory.getLogger(RegistryClaimsController.class); private final ClaimRequestClient claimRequestClient; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index ae143af8d..6a9075f2c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -49,8 +49,8 @@ import java.util.*; import static dev.sunbirdrc.registry.Constants.*; +import static dev.sunbirdrc.registry.helper.RegistryHelper.ServiceNotEnabledResponse; import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; -import static dev.sunbirdrc.registry.service.SignatureHelper.SignatureNotEnabledResponse; @RestController public class RegistryEntityController extends AbstractController { @@ -60,6 +60,8 @@ public class RegistryEntityController extends AbstractController { @Value("${signature.enabled}") private boolean signatureEnabled; + @Value("${certificate.enabled}") + private boolean certificateEnabled; @Autowired(required = false) private ICertificateService certificateService; @@ -509,8 +511,8 @@ public ResponseEntity getEntityType(@PathVariable String entityName, @RequestHeader(required = false) String viewTemplateId) { ResponseParams responseParams = new ResponseParams(); Response response ; - if (!signatureEnabled) { - return SignatureNotEnabledResponse(null, responseParams); + if (!certificateEnabled) { + return ServiceNotEnabledResponse("Certificate service",null, responseParams); } if (registryHelper.doesEntityOperationRequireAuthorization(entityName) && securityEnabled) { try { @@ -817,7 +819,7 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); if (!signatureEnabled) { - return SignatureNotEnabledResponse(response, responseParams); + return ServiceNotEnabledResponse("Signature service", response, responseParams); } try { checkEntityNameInDefinitionManager(entityName); @@ -849,8 +851,8 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity public ResponseEntity getAttestationCertificate(HttpServletRequest request, @PathVariable String entityName, @PathVariable String entityId, @PathVariable String attestationName, @PathVariable String attestationId) { ResponseParams responseParams = new ResponseParams(); - if (!signatureEnabled) { - return SignatureNotEnabledResponse(null, responseParams); + if (!certificateEnabled) { + return ServiceNotEnabledResponse("Certificate service", null, responseParams); } try { checkEntityNameInDefinitionManager(entityName); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index d05d30ab1..c24b8851c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -55,6 +55,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @@ -1232,4 +1234,15 @@ public boolean checkIfCredentialIsRevoked(String signedData) throws Exception { JsonNode searchResponse = searchEntity(searchNode); return searchResponse.get(REVOKED_CREDENTIAL) != null && searchResponse.get(REVOKED_CREDENTIAL).size() > 0; } + + public static ResponseEntity ServiceNotEnabledResponse(String message, Response response, ResponseParams responseParams) { + responseParams.setErrmsg(message + " not enabled!"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + if (response != null) { + response.setResponseCode("SERVICE_UNAVAILABLE"); + } else { + response = new Response(Response.API_ID.GET, "SERVICE_UNAVAILABLE", responseParams); + } + return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE); + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java index 9cdcbd6b5..3dc85c85c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java @@ -155,15 +155,4 @@ public String removeEntitySignature(String entityNodeType, ObjectNode node) { } return entitySignatureUUID; } - - public static ResponseEntity SignatureNotEnabledResponse(Response response, ResponseParams responseParams) { - responseParams.setErrmsg("Signature service not enabled!"); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - if (response != null) { - response.setResponseCode("SERVICE_UNAVAILABLE"); - } else { - response = new Response(Response.API_ID.GET, "SERVICE_UNAVAILABLE", responseParams); - } - return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE); - } } \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index 6c7c0bf7c..f871d8a31 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -26,7 +26,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_CERTIFICATE_SERVICE_NAME; @Component -@ConditionalOnProperty(name = "signature.enabled", havingValue = "true") +@ConditionalOnProperty(name = "certificate.enabled", havingValue = "true") public class CertificateServiceImpl implements ICertificateService { private final String templateBaseUrl; private final String certificateUrl; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index b18e4b7b0..5f0102c1d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -8,6 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpEntity; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpMethod; @@ -18,6 +19,7 @@ import java.util.HashMap; @Component +@ConditionalOnProperty(name = "claims.enabled", havingValue = "true") public class ClaimRequestClient { private static Logger logger = LoggerFactory.getLogger(RegistryController.class); private final String claimRequestUrl; diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 87aa6369d..4ff75516a 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -211,6 +211,7 @@ signature: name: SignatureShape certificate: + enabled: ${certificate_enabled:true} templateBaseUrl: ${template_base_url:http://localhost:8081/api/v1/templates/} healthCheckURL: ${certificate_health_check_url:http://localhost:8078/health} apiUrl: ${pdf_url:http://localhost:8078/api/v1/certificate} @@ -246,6 +247,7 @@ keycloak-user: # email details should be configured in keycloak realm settings email-actions: ${keycloack_user_email_actions:} claims: + enabled: ${claims_enabled:true} url: ${claims_url:http://localhost:8082} authentication: enabled: ${authentication_enabled:true} From 920da2d4f096c17d6111501932568ffee523173f Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Thu, 7 Sep 2023 12:43:33 +0530 Subject: [PATCH 09/28] fixed make tests failing --- Makefile | 6 ++---- docker-compose.yml | 6 +++--- .../registry/helper/EntityStateHelper.java | 3 ++- test_environments/test1.env | 11 +++++++++++ test_environments/test2.env | 14 ++++++++++++++ 5 files changed, 32 insertions(+), 8 deletions(-) create mode 100644 test_environments/test1.env create mode 100644 test_environments/test2.env diff --git a/Makefile b/Makefile index e27716e2a..1efc42883 100644 --- a/Makefile +++ b/Makefile @@ -28,12 +28,10 @@ java/registry/target/registry.jar: $(SOURCES) cd java && ./mvnw clean install test: build - @echo "VIEW_DIR=java/apitest/src/test/resources/views" >> .env || echo "no permission to append to file" - @echo "SCHEMA_DIR=java/apitest/src/test/resources/schemas" >> .env || echo "no permission to append to file" @docker-compose down @rm -rf db-data* || echo "no permission to delete" # test with distributed definition manager and native search - @SEARCH_PROVIDER_NAME=dev.sunbirdrc.registry.service.NativeSearchService RELEASE_VERSION=latest KEYCLOAK_IMPORT_DIR=java/apitest/src/test/resources KEYCLOAK_SECRET=a52c5f4a-89fd-40b9-aea2-3f711f14c889 MANAGER_TYPE=DistributedDefinitionsManager DB_DIR=db-data-1 docker-compose up -d db keycloak registry certificate-signer certificate-api redis + @docker-compose --env-file test_environments/test1.env up -d db keycloak registry certificate-signer certificate-api redis @echo "Starting the test" && sh build/wait_for_port.sh 8080 @echo "Starting the test" && sh build/wait_for_port.sh 8081 @docker-compose ps @@ -42,7 +40,7 @@ test: build @docker-compose down @rm -rf db-data-1 || echo "no permission to delete" # test with kafka(async), events, notifications, - @NOTIFICATION_ENABLED=true NOTIFICATION_URL=http://notification-ms:8765/notification-service/v1/notification TRACK_NOTIFICATIONS=true EVENT_ENABLED=true ASYNC_ENABLED=true RELEASE_VERSION=latest KEYCLOAK_IMPORT_DIR=java/apitest/src/test/resources KEYCLOAK_SECRET=a52c5f4a-89fd-40b9-aea2-3f711f14c889 DB_DIR=db-data-2 docker-compose up -d db clickhouse redis es keycloak registry certificate-signer certificate-api kafka zookeeper notification-ms metrics + @docker-compose --env-file test_environments/test2.env up -d db clickhouse redis es keycloak registry certificate-signer certificate-api kafka zookeeper notification-ms metrics @echo "Starting the test" && sh build/wait_for_port.sh 8080 @echo "Starting the test" && sh build/wait_for_port.sh 8081 @docker-compose ps diff --git a/docker-compose.yml b/docker-compose.yml index 42d713bc1..de6b59a56 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -55,13 +55,13 @@ services: - sunbird_sso_admin_client_id=${KEYCLOAK_ADMIN_CLIENT_ID-admin-api} - sunbird_sso_client_id=${KEYCLOAK_CLIENT_ID-registry-frontend} - sunbird_sso_admin_client_secret=${KEYCLOAK_SECRET} - - claims_enabled=false + - claims_enabled=${CLAIMS_ENABLED-false} - claims_url=http://claim-ms:8082 - - signature_enabled=false + - signature_enabled=${SIGNATURE_ENABLED-false} - sign_url=http://certificate-signer:8079/sign - verify_url=http://certificate-signer:8079/verify - sign_health_check_url=http://certificate-signer:8079/health - - certificate_enabled=false + - certificate_enabled=${CERTIFICATE_ENABLED-false} - pdf_url=http://certificate-api:8078/api/v1/certificatePDF - certificate_health_check_url=http://certificate-api:8078/health - template_base_url=http://registry:8081/api/v1/templates/ #Looks for certificate templates for pdf copy of the signed certificate diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/EntityStateHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/EntityStateHelper.java index c3d171d28..c89871739 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/EntityStateHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/EntityStateHelper.java @@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import javax.validation.constraints.NotEmpty; @@ -48,7 +49,7 @@ public class EntityStateHelper { @Autowired public EntityStateHelper(IDefinitionsManager definitionsManager, RuleEngineService ruleEngineService, - ConditionResolverService conditionResolverService, ClaimRequestClient claimRequestClient) { + ConditionResolverService conditionResolverService,@Nullable ClaimRequestClient claimRequestClient) { this.definitionsManager = definitionsManager; this.ruleEngineService = ruleEngineService; this.conditionResolverService = conditionResolverService; diff --git a/test_environments/test1.env b/test_environments/test1.env new file mode 100644 index 000000000..d3d4c9204 --- /dev/null +++ b/test_environments/test1.env @@ -0,0 +1,11 @@ +# test with distributed definition manager and native search +VIEW_DIR=java/apitest/src/test/resources/views +SCHEMA_DIR=java/apitest/src/test/resources/schemas +SIGNATURE_ENABLED=true +CERTIFICATE_ENABLED=true +RELEASE_VERSION=latest +SEARCH_PROVIDER_NAME=dev.sunbirdrc.registry.service.NativeSearchService +KEYCLOAK_IMPORT_DIR=java/apitest/src/test/resources +KEYCLOAK_SECRET=a52c5f4a-89fd-40b9-aea2-3f711f14c889 +MANAGER_TYPE=DistributedDefinitionsManager +DB_DIR=db-data-1 diff --git a/test_environments/test2.env b/test_environments/test2.env new file mode 100644 index 000000000..18e661aec --- /dev/null +++ b/test_environments/test2.env @@ -0,0 +1,14 @@ +# test with kafka(async), events, notifications +VIEW_DIR=java/apitest/src/test/resources/views +SCHEMA_DIR=java/apitest/src/test/resources/schemas +SIGNATURE_ENABLED=true +CERTIFICATE_ENABLED=true +NOTIFICATION_ENABLED=true +TRACK_NOTIFICATIONS=true +EVENT_ENABLED=true +ASYNC_ENABLED=true +RELEASE_VERSION=latest +NOTIFICATION_URL=http://notification-ms:8765/notification-service/v1/notification +KEYCLOAK_IMPORT_DIR=java/apitest/src/test/resources +KEYCLOAK_SECRET=a52c5f4a-89fd-40b9-aea2-3f711f14c889 +DB_DIR=db-data-2 From bb02f4f55ccc30510ba7548120d2c715c9e736ac Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Fri, 8 Sep 2023 16:07:49 +0530 Subject: [PATCH 10/28] added health check to metrics service and fixed metrics service issues --- build/wait_for_port.sh | 2 +- docker-compose.yml | 8 ++++- services/metrics/go.mod | 2 ++ services/metrics/go.sum | 4 +++ services/metrics/interfaces/metrics-api.yaml | 11 ++++++ services/metrics/pkg/handler.go | 10 ++++++ .../swagger_gen/restapi/embedded_spec.go | 34 +++++++++++++++++++ .../aggregates/get_v1_aggregates.go | 6 ++-- .../get_v1_aggregates_parameters.go | 3 +- .../operations/metrics/get_v1_metrics.go | 6 ++-- .../metrics/get_v1_metrics_parameters.go | 3 +- .../restapi/operations/metrics_api.go | 16 +++++++-- .../metrics/swagger_gen/restapi/server.go | 6 +++- 13 files changed, 97 insertions(+), 14 deletions(-) diff --git a/build/wait_for_port.sh b/build/wait_for_port.sh index 33be08e7e..ee3573115 100644 --- a/build/wait_for_port.sh +++ b/build/wait_for_port.sh @@ -4,7 +4,7 @@ echo "Waiting service to launch on $1..." i=0 while ! curl localhost:$1; do sleep 10 - let i=i+1 + ((i=i+1)) if [[ $i -gt 60 ]]; then echo "Failed to get the service in sane state!" exit 1; diff --git a/docker-compose.yml b/docker-compose.yml index de6b59a56..002a50a2e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -285,9 +285,15 @@ services: REDIS_URL: redis:6379 ports: - "8070:8070" + healthcheck: + test: + [ "CMD-SHELL", "wget -nv -t1 --spider http://localhost:8070/health || exit 1" ] + interval: 30s + timeout: 10s + retries: 10 depends_on: kafka: - condition: service_started + condition: service_healthy registry: condition: service_healthy redis: diff --git a/services/metrics/go.mod b/services/metrics/go.mod index b99b92776..f1a0bd0ea 100644 --- a/services/metrics/go.mod +++ b/services/metrics/go.mod @@ -26,6 +26,7 @@ require ( github.com/andybalholm/brotli v1.0.5 // indirect github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/docker/go-units v0.5.0 // indirect github.com/go-faster/city v1.0.1 // indirect @@ -36,6 +37,7 @@ require ( github.com/go-openapi/validate v0.21.0 // indirect github.com/go-redsync/redsync/v4 v4.8.1 // indirect github.com/google/uuid v1.3.0 // indirect + github.com/gospotcheck/jwt-go v4.0.0+incompatible // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/josharian/intern v1.0.0 // indirect diff --git a/services/metrics/go.sum b/services/metrics/go.sum index c22369e32..e730469a1 100644 --- a/services/metrics/go.sum +++ b/services/metrics/go.sum @@ -47,6 +47,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= @@ -184,6 +186,8 @@ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gospotcheck/jwt-go v4.0.0+incompatible h1:IFJXoMKFNfEoZE7cXgs5pWcK2AEQyDISXMkr1jaaJBg= +github.com/gospotcheck/jwt-go v4.0.0+incompatible/go.mod h1:xV77fUnYqYQM9PwY+P7tnFw/ALG6ijfKbvbFE66O8mI= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hamba/avro v1.5.6/go.mod h1:3vNT0RLXXpFm2Tb/5KC71ZRJlOroggq1Rcitb6k4Fr8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/services/metrics/interfaces/metrics-api.yaml b/services/metrics/interfaces/metrics-api.yaml index 54b427ada..c52ec7924 100644 --- a/services/metrics/interfaces/metrics-api.yaml +++ b/services/metrics/interfaces/metrics-api.yaml @@ -10,6 +10,17 @@ consumes: produces: - application/json paths: + /health: + get: + tags: + - health + summary: Get the health status + description: API to get the notification health status + responses: + 200: + description: OK + schema: + type: object /v1/metrics: get: tags: diff --git a/services/metrics/pkg/handler.go b/services/metrics/pkg/handler.go index a7fca35ec..0f920c068 100644 --- a/services/metrics/pkg/handler.go +++ b/services/metrics/pkg/handler.go @@ -7,6 +7,7 @@ import ( "metrics/models" "metrics/swagger_gen/restapi/operations" "metrics/swagger_gen/restapi/operations/aggregates" + "metrics/swagger_gen/restapi/operations/health" "metrics/swagger_gen/restapi/operations/metrics" "github.com/go-openapi/runtime/middleware" @@ -16,6 +17,15 @@ import ( func SetupHandlers(api *operations.MetricsAPI) { api.MetricsGetV1MetricsHandler = metrics.GetV1MetricsHandlerFunc(getAllMetrics) api.AggregatesGetV1AggregatesHandler = aggregates.GetV1AggregatesHandlerFunc(getWeeklyAggregates) + api.HealthGetHealthHandler = health.GetHealthHandlerFunc(getHealthHandle) +} + +func getHealthHandle(params health.GetHealthParams) middleware.Responder { + response := health.NewGetHealthOK() + response.Payload = map[string]string{ + "status": "UP", + } + return response } func getAllMetrics(params metrics.GetV1MetricsParams) middleware.Responder { diff --git a/services/metrics/swagger_gen/restapi/embedded_spec.go b/services/metrics/swagger_gen/restapi/embedded_spec.go index 28966a9f2..d1f96977d 100644 --- a/services/metrics/swagger_gen/restapi/embedded_spec.go +++ b/services/metrics/swagger_gen/restapi/embedded_spec.go @@ -31,6 +31,23 @@ func init() { "version": "1.0.0" }, "paths": { + "/health": { + "get": { + "description": "API to get the notification health status", + "tags": [ + "health" + ], + "summary": "Get the health status", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object" + } + } + } + } + }, "/v1/aggregates": { "get": { "security": [], @@ -106,6 +123,23 @@ func init() { "version": "1.0.0" }, "paths": { + "/health": { + "get": { + "description": "API to get the notification health status", + "tags": [ + "health" + ], + "summary": "Get the health status", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object" + } + } + } + } + }, "/v1/aggregates": { "get": { "security": [], diff --git a/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates.go b/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates.go index 39a9411f9..2284889e3 100644 --- a/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates.go +++ b/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates.go @@ -30,7 +30,7 @@ func NewGetV1Aggregates(ctx *middleware.Context, handler GetV1AggregatesHandler) } /* - GetV1Aggregates swagger:route GET /v1/aggregates aggregates getV1Aggregates +GetV1Aggregates swagger:route GET /v1/aggregates aggregates getV1Aggregates get aggregates for weekly added records */ @@ -42,15 +42,17 @@ type GetV1Aggregates struct { func (o *GetV1Aggregates) ServeHTTP(rw http.ResponseWriter, r *http.Request) { route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { - *r = *rCtx + r = rCtx } var Params = NewGetV1AggregatesParams() + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params o.Context.Respond(rw, r, route.Produces, route, err) return } res := o.Handler.Handle(Params) // actually handle the request + o.Context.Respond(rw, r, route.Produces, route, res) } diff --git a/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates_parameters.go b/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates_parameters.go index 5d0e97303..3f25448b0 100644 --- a/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates_parameters.go +++ b/services/metrics/swagger_gen/restapi/operations/aggregates/get_v1_aggregates_parameters.go @@ -13,8 +13,7 @@ import ( ) // NewGetV1AggregatesParams creates a new GetV1AggregatesParams object -// -// There are no default values defined in the spec. +// no default values defined in spec. func NewGetV1AggregatesParams() GetV1AggregatesParams { return GetV1AggregatesParams{} diff --git a/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics.go b/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics.go index 53c0a5b52..7bb50083e 100644 --- a/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics.go +++ b/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics.go @@ -30,7 +30,7 @@ func NewGetV1Metrics(ctx *middleware.Context, handler GetV1MetricsHandler) *GetV } /* - GetV1Metrics swagger:route GET /v1/metrics metrics getV1Metrics +GetV1Metrics swagger:route GET /v1/metrics metrics getV1Metrics get all metrics */ @@ -42,15 +42,17 @@ type GetV1Metrics struct { func (o *GetV1Metrics) ServeHTTP(rw http.ResponseWriter, r *http.Request) { route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { - *r = *rCtx + r = rCtx } var Params = NewGetV1MetricsParams() + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params o.Context.Respond(rw, r, route.Produces, route, err) return } res := o.Handler.Handle(Params) // actually handle the request + o.Context.Respond(rw, r, route.Produces, route, res) } diff --git a/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics_parameters.go b/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics_parameters.go index 65776a71e..713ea4287 100644 --- a/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics_parameters.go +++ b/services/metrics/swagger_gen/restapi/operations/metrics/get_v1_metrics_parameters.go @@ -13,8 +13,7 @@ import ( ) // NewGetV1MetricsParams creates a new GetV1MetricsParams object -// -// There are no default values defined in the spec. +// no default values defined in spec. func NewGetV1MetricsParams() GetV1MetricsParams { return GetV1MetricsParams{} diff --git a/services/metrics/swagger_gen/restapi/operations/metrics_api.go b/services/metrics/swagger_gen/restapi/operations/metrics_api.go index f1e7d0203..3b751a9f8 100644 --- a/services/metrics/swagger_gen/restapi/operations/metrics_api.go +++ b/services/metrics/swagger_gen/restapi/operations/metrics_api.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "metrics/swagger_gen/restapi/operations/aggregates" + "metrics/swagger_gen/restapi/operations/health" "metrics/swagger_gen/restapi/operations/metrics" ) @@ -45,6 +46,9 @@ func NewMetricsAPI(spec *loads.Document) *MetricsAPI { JSONProducer: runtime.JSONProducer(), + HealthGetHealthHandler: health.GetHealthHandlerFunc(func(params health.GetHealthParams) middleware.Responder { + return middleware.NotImplemented("operation health.GetHealth has not yet been implemented") + }), AggregatesGetV1AggregatesHandler: aggregates.GetV1AggregatesHandlerFunc(func(params aggregates.GetV1AggregatesParams) middleware.Responder { return middleware.NotImplemented("operation aggregates.GetV1Aggregates has not yet been implemented") }), @@ -70,11 +74,9 @@ type MetricsAPI struct { // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. // It has a default implementation in the security package, however you can replace it for your particular usage. BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator - // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. // It has a default implementation in the security package, however you can replace it for your particular usage. APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator - // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. // It has a default implementation in the security package, however you can replace it for your particular usage. BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator @@ -87,11 +89,12 @@ type MetricsAPI struct { // - application/json JSONProducer runtime.Producer + // HealthGetHealthHandler sets the operation handler for the get health operation + HealthGetHealthHandler health.GetHealthHandler // AggregatesGetV1AggregatesHandler sets the operation handler for the get v1 aggregates operation AggregatesGetV1AggregatesHandler aggregates.GetV1AggregatesHandler // MetricsGetV1MetricsHandler sets the operation handler for the get v1 metrics operation MetricsGetV1MetricsHandler metrics.GetV1MetricsHandler - // ServeError is called when an error is received, there is a default handler // but you can set your own with this ServeError func(http.ResponseWriter, *http.Request, error) @@ -168,6 +171,9 @@ func (o *MetricsAPI) Validate() error { unregistered = append(unregistered, "JSONProducer") } + if o.HealthGetHealthHandler == nil { + unregistered = append(unregistered, "health.GetHealthHandler") + } if o.AggregatesGetV1AggregatesHandler == nil { unregistered = append(unregistered, "aggregates.GetV1AggregatesHandler") } @@ -262,6 +268,10 @@ func (o *MetricsAPI) initHandlerCache() { o.handlers = make(map[string]map[string]http.Handler) } + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/health"] = health.NewGetHealth(o.context, o.HealthGetHealthHandler) if o.handlers["GET"] == nil { o.handlers["GET"] = make(map[string]http.Handler) } diff --git a/services/metrics/swagger_gen/restapi/server.go b/services/metrics/swagger_gen/restapi/server.go index 94f704a79..d5684b995 100644 --- a/services/metrics/swagger_gen/restapi/server.go +++ b/services/metrics/swagger_gen/restapi/server.go @@ -8,6 +8,7 @@ import ( "crypto/x509" "errors" "fmt" + "io/ioutil" "log" "net" "net/http" @@ -273,7 +274,7 @@ func (s *Server) Serve() (err error) { if s.TLSCACertificate != "" { // include specified CA certificate - caCert, caCertErr := os.ReadFile(string(s.TLSCACertificate)) + caCert, caCertErr := ioutil.ReadFile(string(s.TLSCACertificate)) if caCertErr != nil { return caCertErr } @@ -304,6 +305,9 @@ func (s *Server) Serve() (err error) { s.Fatalf("no certificate was configured for TLS") } + // must have at least one certificate or panics + httpsServer.TLSConfig.BuildNameToCertificate() + configureServer(httpsServer, "https", s.httpsServerL.Addr().String()) servers = append(servers, httpsServer) From 2fc87d33bc3be90f00d6f75c3a2177ea1516004d Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Fri, 8 Sep 2023 16:23:58 +0530 Subject: [PATCH 11/28] added missing metrics files --- .../swagger_gen/models/JWTClaimBody.go | 18 ++++ .../restapi/operations/health/get_health.go | 58 +++++++++++++ .../health/get_health_parameters.go | 46 ++++++++++ .../operations/health/get_health_responses.go | 55 ++++++++++++ .../health/get_health_urlbuilder.go | 87 +++++++++++++++++++ 5 files changed, 264 insertions(+) create mode 100644 services/metrics/swagger_gen/models/JWTClaimBody.go create mode 100644 services/metrics/swagger_gen/restapi/operations/health/get_health.go create mode 100644 services/metrics/swagger_gen/restapi/operations/health/get_health_parameters.go create mode 100644 services/metrics/swagger_gen/restapi/operations/health/get_health_responses.go create mode 100644 services/metrics/swagger_gen/restapi/operations/health/get_health_urlbuilder.go diff --git a/services/metrics/swagger_gen/models/JWTClaimBody.go b/services/metrics/swagger_gen/models/JWTClaimBody.go new file mode 100644 index 000000000..234b5828e --- /dev/null +++ b/services/metrics/swagger_gen/models/JWTClaimBody.go @@ -0,0 +1,18 @@ +package models + +import ( + "github.com/dgrijalva/jwt-go" +) + +type JWTClaimBody struct { + *jwt.StandardClaims + TokenType string + ResourceAccess map[string]Group `json:"resource_access"` + Scope string `json:"scope"` + PreferredUsername string `json:"preferred_username"` + FacilityCode string `json:"facility_code"` +} + +type Group struct { + Roles []string `json:"roles"` +} diff --git a/services/metrics/swagger_gen/restapi/operations/health/get_health.go b/services/metrics/swagger_gen/restapi/operations/health/get_health.go new file mode 100644 index 000000000..fb1fa0fec --- /dev/null +++ b/services/metrics/swagger_gen/restapi/operations/health/get_health.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetHealthHandlerFunc turns a function with the right signature into a get health handler +type GetHealthHandlerFunc func(GetHealthParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetHealthHandlerFunc) Handle(params GetHealthParams) middleware.Responder { + return fn(params) +} + +// GetHealthHandler interface for that can handle valid get health params +type GetHealthHandler interface { + Handle(GetHealthParams) middleware.Responder +} + +// NewGetHealth creates a new http.Handler for the get health operation +func NewGetHealth(ctx *middleware.Context, handler GetHealthHandler) *GetHealth { + return &GetHealth{Context: ctx, Handler: handler} +} + +/* + GetHealth swagger:route GET /health health getHealth + +# Get the health status + +API to get the notification health status +*/ +type GetHealth struct { + Context *middleware.Context + Handler GetHealthHandler +} + +func (o *GetHealth) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewGetHealthParams() + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/metrics/swagger_gen/restapi/operations/health/get_health_parameters.go b/services/metrics/swagger_gen/restapi/operations/health/get_health_parameters.go new file mode 100644 index 000000000..f975f8866 --- /dev/null +++ b/services/metrics/swagger_gen/restapi/operations/health/get_health_parameters.go @@ -0,0 +1,46 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewGetHealthParams creates a new GetHealthParams object +// +// There are no default values defined in the spec. +func NewGetHealthParams() GetHealthParams { + + return GetHealthParams{} +} + +// GetHealthParams contains all the bound params for the get health operation +// typically these are obtained from a http.Request +// +// swagger:parameters GetHealth +type GetHealthParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetHealthParams() beforehand. +func (o *GetHealthParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/metrics/swagger_gen/restapi/operations/health/get_health_responses.go b/services/metrics/swagger_gen/restapi/operations/health/get_health_responses.go new file mode 100644 index 000000000..23e43a3ed --- /dev/null +++ b/services/metrics/swagger_gen/restapi/operations/health/get_health_responses.go @@ -0,0 +1,55 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// GetHealthOKCode is the HTTP code returned for type GetHealthOK +const GetHealthOKCode int = 200 + +/* +GetHealthOK OK + +swagger:response getHealthOK +*/ +type GetHealthOK struct { + + /* + In: Body + */ + Payload interface{} `json:"body,omitempty"` +} + +// NewGetHealthOK creates GetHealthOK with default headers values +func NewGetHealthOK() *GetHealthOK { + + return &GetHealthOK{} +} + +// WithPayload adds the payload to the get health o k response +func (o *GetHealthOK) WithPayload(payload interface{}) *GetHealthOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get health o k response +func (o *GetHealthOK) SetPayload(payload interface{}) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHealthOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} diff --git a/services/metrics/swagger_gen/restapi/operations/health/get_health_urlbuilder.go b/services/metrics/swagger_gen/restapi/operations/health/get_health_urlbuilder.go new file mode 100644 index 000000000..ba1e168b2 --- /dev/null +++ b/services/metrics/swagger_gen/restapi/operations/health/get_health_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package health + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// GetHealthURL generates an URL for the get health operation +type GetHealthURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHealthURL) WithBasePath(bp string) *GetHealthURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHealthURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetHealthURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/health" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/notification-service/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetHealthURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetHealthURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetHealthURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetHealthURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetHealthURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetHealthURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} From abf6d03c7e0ff08741ed50517ce9da04d7c5d2b2 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Fri, 8 Sep 2023 19:18:33 +0530 Subject: [PATCH 12/28] fixed error messages --- java/.mvn/wrapper/MavenWrapperDownloader.java | 1 - .../service/ConditionResolverServiceTest.java | 5 ++- .../middleware/util/JSONUtilTest.java | 9 +++--- .../plugin/services/DivocServices.java | 6 ++-- .../plugin/services/MosipAuthService.java | 3 +- .../plugin/services/MosipServices.java | 15 +++------ .../registry/config/GenericConfiguration.java | 6 ++-- .../registry/config/SchemaLoader.java | 2 +- .../controller/AbstractController.java | 4 +-- .../controller/FileStorageController.java | 9 ++++-- .../RegistryAttestationPolicyController.java | 10 +++--- .../RegistryCertificateController.java | 5 ++- .../controller/RegistryClaimsController.java | 5 +-- .../controller/RegistryController.java | 16 +++++----- .../controller/RegistryEntityController.java | 32 +++++++++---------- .../RegistryTemplateController.java | 5 ++- .../controller/RegistryUtilsController.java | 17 +++++----- .../sunbirdrc/registry/dao/SearchDaoImpl.java | 5 ++- .../registry/frame/FrameContext.java | 2 -- .../registry/helper/RegistryHelper.java | 7 ++-- .../registry/service/FileStorageService.java | 6 +--- .../sunbirdrc/registry/util/PrivateField.java | 2 +- .../sunbirdrc/registry/util/RefResolver.java | 2 +- .../java/org/sunbird/akka/core/BaseActor.java | 29 +++++++++-------- .../java/org/sunbird/akka/core/Router.java | 3 +- .../jsonschema/JsonValidationServiceImpl.java | 2 +- .../sunbirdrc/views/ViewTransformerTest.java | 5 +-- 27 files changed, 102 insertions(+), 111 deletions(-) diff --git a/java/.mvn/wrapper/MavenWrapperDownloader.java b/java/.mvn/wrapper/MavenWrapperDownloader.java index b901097f2..7b9f5afec 100644 --- a/java/.mvn/wrapper/MavenWrapperDownloader.java +++ b/java/.mvn/wrapper/MavenWrapperDownloader.java @@ -89,7 +89,6 @@ public static void main(String args[]) { System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); - e.printStackTrace(); System.exit(1); } } diff --git a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java index 218fd13d2..e3325b366 100644 --- a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java +++ b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; @@ -11,6 +13,7 @@ import static org.junit.Assert.*; public class ConditionResolverServiceTest { + private static final Logger logger = LoggerFactory.getLogger(ConditionResolverServiceTest.class); ConditionResolverService conditionResolverService = new ConditionResolverService(); @Test public void shouldAbleToResolveRequesterPaths() throws IOException { @@ -44,7 +47,7 @@ public void shouldReturnTrueForValidExpression() throws IOException { try { resolve = conditionResolverService.resolve(getStudentJsonNode(), requester, condition, attributes); } catch (IOException e) { - e.printStackTrace(); + logger.info("Exception occurred: {}", e.getMessage()); } String attestor = "ATTESTOR"; resolve = conditionResolverService.resolve(getTeacherJsonNode(), attestor, resolve, attributes); diff --git a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java index 0b272db24..5dd9c2013 100644 --- a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java +++ b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.pojos.AuditRecord; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.StandardCharsets; @@ -15,6 +17,7 @@ import static org.junit.Assert.*; public class JSONUtilTest { + private static final Logger logger = LoggerFactory.getLogger(JSONUtilTest.class); private static final String TEST_DIR = "src/test/resources/"; private static final String ACTUAL_DATA = "actual_data.json"; private static final String EXPECTED_DATA = "expected_data.json"; @@ -131,12 +134,8 @@ private String getContent(String fileName) { } return result.toString(StandardCharsets.UTF_8.name()); - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - + logger.info("Exception occurred: {}", e.getMessage()); } return null; } diff --git a/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java b/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java index 0ee7b2eed..db6c37ea4 100644 --- a/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java +++ b/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java @@ -70,8 +70,7 @@ public String fetchClientToken() { try { response = restTemplateProvider.exchange(divocKeycloakUrl, HttpMethod.POST, entity, Map.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Fetching divoc token failed: "); - exception.printStackTrace(); + LOGGER.error("Fetching divoc token failed: {}", exception.getMessage()); } if (response != null && response.getBody() != null && response.getBody().containsKey(ACCESS_TOKEN)) { LOGGER.info("Divoc token fetch successfully."); @@ -94,8 +93,7 @@ public byte[] fetchDivocPdf(String clientToken, String preEnrollmentCode, String response = restTemplateProvider.exchange(divocUrl, HttpMethod.POST, entity, byte[].class); return response.getBody(); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Fetching divoc PDF failed: ", exception); - exception.printStackTrace(); + LOGGER.error("Fetching divoc PDF failed: {}", exception.getMessage()); } return null; } diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java index c993281e5..8e3c8caa0 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java @@ -52,8 +52,7 @@ public HttpHeaders getAuthTokenHeader() { try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.AUTH_URL, HttpMethod.POST, entity, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Get auth token failed: "); - exception.printStackTrace(); + LOGGER.error("Get auth token failed: {}", exception.getMessage()); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully authenticated with mosip"); diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java index e1b9ff319..c2592eec0 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java @@ -80,8 +80,7 @@ void subscribeForPrintServiceEvents() { try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.SUBSCRIBE_URL, HttpMethod.POST, entity, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Subscription to topic failed: "); - exception.printStackTrace(); + LOGGER.error("Subscription to topic failed: {}", exception.getMessage()); } if (response != null && response.getStatusCode() == HttpStatus.ACCEPTED) { LOGGER.info("subscribed for topic {} at hub", topic); @@ -104,8 +103,7 @@ private void registerTopic() { try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.REGISTER_URL, HttpMethod.POST, entity, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Register topic failed: "); - exception.printStackTrace(); + LOGGER.error("Register topic failed: {}", exception.getMessage()); } if (response != null && response.getStatusCode() == HttpStatus.ACCEPTED) { LOGGER.info("topic {} registered at hub", topic); @@ -132,8 +130,7 @@ public Object generateOTP(SendOTPDto otpDto) { try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.OTP_URL, HttpMethod.POST, entity, Object.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Generate otp failed failed: "); - exception.printStackTrace(); + LOGGER.error("Generate otp failed failed: {}", exception.getMessage()); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully generated otp"); @@ -176,8 +173,7 @@ public Object fetchCredentials(FetchCredentialsDto fetchCredentialsDto) { try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.CREDENTIALS_URL, HttpMethod.POST, entity, Object.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Generate credentials failed failed: "); - exception.printStackTrace(); + LOGGER.error("Generate credentials failed failed: {}", exception.getMessage()); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully generated credentials"); @@ -200,8 +196,7 @@ public byte[] fetchMosipPdf(Map requestHeaders, String requestBo response = restTemplateProvider.exchange(printUrl + Constants.PRINT_PDF_URL, HttpMethod.POST, entity, byte[].class); return response.getBody(); } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Failed fetching pdf failed: "); - exception.printStackTrace(); + LOGGER.error("Failed fetching pdf failed: {}", exception.getMessage()); } LOGGER.error("Failed fetching pdf failed: "); return null; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java index 8400379c5..6be376b6d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java @@ -357,10 +357,8 @@ public void addInterceptors(InterceptorRegistry registry) { if (validationEnabled) { try { registry.addInterceptor(validationInterceptor()).addPathPatterns("/add").order(orderIdx++); - } catch (IOException e) { - e.printStackTrace(); - } catch (CustomException e) { - e.printStackTrace(); + } catch (IOException | CustomException e) { + logger.info("Exception occurred while adding validation interceptor: {}", e.getMessage()); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java index f5e6d6ba5..004c42632 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java @@ -54,7 +54,7 @@ private void loadSchemasFromDB() { } logger.info("Loaded {} schema from DB", searchResults.get(Schema).size()); } catch (IOException e) { - e.printStackTrace(); + logger.info("Exception occurred while loading schema from db: {}", e.getMessage()); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java index 3ccda1167..0b1c14ea1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java @@ -47,14 +47,14 @@ public abstract class AbstractController { public String uuidPropertyName; ResponseEntity badRequestException(ResponseParams responseParams, Response response, String errorMessage) { - logger.info("Error in handling the invite {}", errorMessage); + logger.info("Error in handling the invite: {}", errorMessage); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(errorMessage); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } ResponseEntity internalErrorResponse(ResponseParams responseParams, Response response, Exception ex) { - logger.info("Error in handling the invite", ex); + logger.info("Error in handling the invite: {}", ex.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg("Error occurred"); if (!StringUtils.isEmpty(ex.getMessage())) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java index c8a3b1a14..603433f29 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java @@ -3,6 +3,8 @@ import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.model.dto.DocumentsResponse; import dev.sunbirdrc.registry.service.FileStorageService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -18,6 +20,7 @@ @Controller @ConditionalOnProperty(name = "filestorage.enabled", havingValue = "true", matchIfMissing = true) public class FileStorageController { + private static final Logger logger = LoggerFactory.getLogger(FileStorageController.class); private final FileStorageService fileStorageService; private final RegistryHelper registryHelper; @@ -35,7 +38,7 @@ public ResponseEntity save(@RequestParam MultipartFile[] file try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + logger.info("Authorizing entity failed: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.saveAndFetchFileNames(files, httpServletRequest.getRequestURI()); @@ -51,7 +54,7 @@ public ResponseEntity deleteMultipleFiles(@PathVariable Strin try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + logger.info("Authorizing entity failed: {}", e.getMessage()); return new ResponseEntity(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.deleteFiles(files); @@ -67,7 +70,7 @@ public ResponseEntity deleteAFile(@PathVariable String entity, try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + logger.info("Authorizing entity failed: {}", e.getMessage()); return new ResponseEntity(HttpStatus.FORBIDDEN); } return fileStorageService.deleteDocument(httpServletRequest.getRequestURI()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java index d515d4714..4e3d6cb2e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java @@ -43,7 +43,7 @@ public ResponseEntity createAttestationPolicy(@PathVariable String entityName, @ return badRequestException(responseParams, response, "Invalid entity name"); } } catch (Exception e) { - logger.error("Failed persisting attestation policy: ", e); + logger.error("Failed persisting attestation policy: {}", e.getMessage()); return internalErrorResponse(responseParams, response, e); } } @@ -70,7 +70,7 @@ public ResponseEntity getAttestationPolicies(@PathVariable String entityName, Ht return badRequestException(responseParams, response, "Invalid entity name"); } } catch (Exception e) { - logger.error("Failed getting attestation policy: ", e); + logger.error("Failed getting attestation policy: {}", e.getMessage()); return internalErrorResponse(responseParams, response, e); } } @@ -93,7 +93,7 @@ public ResponseEntity updateAttestationPolicy(@PathVariable String entityName, @ } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: ", e); + logger.error("Failed updating attestation policy: {}", e.getMessage()); return internalErrorResponse(responseParams, response, e); } } @@ -118,7 +118,7 @@ public ResponseEntity updateAttestationPolicyStatus(@PathVariable String entityN } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: ", e); + logger.error("Failed updating attestation policy: {}", e.getMessage()); return internalErrorResponse(responseParams, response, e); } } @@ -143,7 +143,7 @@ public ResponseEntity deleteAttestationPolicy(@PathVariable String entityName, @ } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: ", e); + logger.error("Failed updating attestation policy: {}", e.getMessage()); return internalErrorResponse(responseParams, response, e); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java index dceb5d668..ed0beb47f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import dev.sunbirdrc.registry.entities.VerificationRequest; import dev.sunbirdrc.registry.helper.RegistryHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -14,7 +16,7 @@ @Controller public class RegistryCertificateController { - + private static final Logger logger = LoggerFactory.getLogger(RegistryCertificateController.class); private static final String VERIFIED = "verified"; private static final String RESULTS = "results"; @@ -41,6 +43,7 @@ public ResponseEntity verifyCertificate(@RequestBody VerificationRequest return new ResponseEntity<>(response, HttpStatus.OK); } } catch (Exception e) { + logger.info("Exception occurred while verifying certificate: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index 9e1135178..efaf3cfd1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -54,7 +54,6 @@ public ResponseEntity getAllClaims(@PathVariable String entityName, Page return new ResponseEntity<>(claims, HttpStatus.OK); } catch (Exception e) { logger.error("Fetching claims failed {}", e.getMessage()); - e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -68,10 +67,9 @@ public ResponseEntity getClaim(@PathVariable String entityName, @PathVar return new ResponseEntity<>(claim, HttpStatus.OK); } catch (HttpClientErrorException | HttpServerErrorException e) { logger.error("Fetching claim failed {}", e.getMessage()); - e.printStackTrace(); return new ResponseEntity<>(e.getStatusCode()); } catch (Exception exception) { - exception.printStackTrace(); + logger.info("Exception occurred while fetching claim: {}", exception.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -149,7 +147,6 @@ public ResponseEntity riseAttestation(HttpServletRequest request, @Reque response.setResult(Collections.singletonMap("attestationOSID", attestationOSID)); } catch (Exception exception) { logger.error("Exception occurred while saving attestation data {}", exception.getMessage()); - exception.printStackTrace(); responseParams.setErrmsg(exception.getMessage()); response = new Response(Response.API_ID.SEND, HttpStatus.INTERNAL_SERVER_ERROR.toString(), responseParams); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java index aaa24997d..6bdb42acf 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java @@ -61,7 +61,7 @@ public ResponseEntity searchEntity(@RequestHeader HttpHeaders header) responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.searchEntity"); } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); + logger.error("Exception in controller while searching entities !, {}", e.getMessage()); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -83,12 +83,12 @@ public ResponseEntity deleteEntity() { responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); } catch (UnsupportedOperationException e) { - logger.error("Controller: UnsupportedOperationException while deleting entity !", e); + logger.error("Controller: UnsupportedOperationException while deleting entity !, {}", e.getMessage()); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); } catch (Exception e) { - logger.error("Controller: Exception while deleting entity !", e); + logger.error("Controller: Exception while deleting entity !, {}", e.getMessage()); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg("Meh ! You encountered an error!"); @@ -114,7 +114,7 @@ public ResponseEntity addEntity() { responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.addToExistingEntity"); } catch (Exception e) { - logger.error("Exception in controller while adding entity !", e); + logger.error("Exception in controller while adding entity !, {}", e.getMessage()); response.setResult(result); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -147,7 +147,7 @@ public ResponseEntity readEntity(@RequestHeader HttpHeaders header) { response.setResult(resultContent.getData()); logger.info("ReadEntity,{},{}", resultNode.get(apiMessage.getRequest().getEntityType()).get(uuidPropertyName), config); } catch (Exception e) { - logger.error("Read Api Exception occurred ", e); + logger.error("Read Api Exception occurred , {}", e.getMessage()); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -166,7 +166,7 @@ public ResponseEntity getRegisters(@RequestHeader HttpHeaders header) response.setResult(registryList); logger.info("get registers,{}", registryList); } catch (Exception e) { - logger.error("Read Api Exception occurred ", e); + logger.error("Read Api Exception occurred , {}", e.getMessage()); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -183,7 +183,7 @@ public ResponseEntity getRegisters(@PathVariable String entity, @Reque response.setResult(definition); logger.info("get registers,{}", entity); } catch (Exception e) { - logger.error("Read Api Exception occurred ", e); + logger.error("Read Api Exception occurred , {}", e.getMessage()); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -206,7 +206,7 @@ public ResponseEntity updateEntity() { responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.update"); } catch (Exception e) { - logger.error("RegistryController: Exception while updating entity (without id)!", e); + logger.error("RegistryController: Exception while updating entity (without id)!, {}", e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 6a9075f2c..393899465 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -179,7 +179,7 @@ public ResponseEntity deleteEntity( response = new Response(Response.API_ID.DELETE, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("RegistryController: Exception while Deleting entity", e); + logger.error("RegistryController: Exception while Deleting entity, {}", e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -215,7 +215,7 @@ public ResponseEntity searchEntity(@PathVariable String entityName, @Req response = new Response(Response.API_ID.SEARCH, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); + logger.error("Exception in controller while searching entities !, {}", e.getMessage()); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -270,7 +270,7 @@ public ResponseEntity putEntity( response = new Response(Response.API_ID.PUT, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("RegistryController: Exception while updating entity (without id)!", e); + logger.error("RegistryController: Exception while updating entity (without id)!, {}", e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -323,7 +323,7 @@ public ResponseEntity postEntity( logger.info("Error in validating the request"); return badRequestException(responseParams, response, e.getMessage()); } catch (Exception e) { - logger.error("Exception in controller while adding entity !", e); + logger.error("Exception in controller while adding entity !, {}", e.getMessage()); response.setResult(result); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -473,7 +473,7 @@ public ResponseEntity getEntityWithConsent( Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Error in partner api access", e); + logger.error("Error in partner api access: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -498,7 +498,7 @@ private ArrayList getConsentFields(HttpServletRequest request) { } } } catch (Exception ex) { - logger.error("Error while extracting other claims", ex); + logger.error("Error while extracting other claims, {}", ex.getMessage()); } return fields; } @@ -545,7 +545,7 @@ public ResponseEntity getEntityType(@PathVariable String entityName, JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) ), HttpStatus.OK); } catch (Exception exception) { - exception.printStackTrace(); + logger.info("Exception occurred while producing entity certificate: {}", exception.getMessage()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -570,7 +570,7 @@ private String getTemplateUrlFromRequest(HttpServletRequest request, String enti } catch (UnreachableException e) { throw e; } catch (Exception e) { - logger.error("Exception while parsing certificate templates DID urls", e); + logger.error("Exception while parsing certificate templates DID urls, {}", e.getMessage()); return null; } } @@ -625,7 +625,7 @@ public ResponseEntity getEntity( response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Read Api Exception occurred ", e); + logger.error("Read Api Exception occurred: {}", e.getMessage()); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -685,7 +685,7 @@ public ResponseEntity getEntityByToken(@PathVariable String entityName, response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); + logger.error("Exception in controller while searching entities !, {}", e.getMessage()); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -717,7 +717,7 @@ public ResponseEntity getEntityForAttestation( return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - e.printStackTrace(); + logger.info("Fetching attestation properties for entity failed: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @@ -775,7 +775,7 @@ public ResponseEntity updateProperty( } catch (Exception exception) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(exception.getMessage()); - exception.printStackTrace(); + logger.info("Exception occurred which fetching a system property: {}", exception.getMessage()); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -808,7 +808,7 @@ public ResponseEntity updateAttestationProperty( } catch (Exception exception) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(exception.getMessage()); - exception.printStackTrace(); + logger.info("Exception occurred while updating attestation: {}", exception.getMessage()); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -838,7 +838,7 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); + logger.error("Exception in controller while searching entities !, {}", e.getMessage()); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -880,7 +880,7 @@ public ResponseEntity getAttestationCertificate(HttpServletRequest reque logger.error(e.getMessage()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } catch (Exception e) { - e.printStackTrace(); + logger.info("Fetching attestation certificate failed: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -920,7 +920,7 @@ public ResponseEntity revokeACredential ( watch.stop(tag); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception e) { - logger.error("Registry Controller: Exception while revoking an entity:", e); + logger.error("Registry Controller: Exception while revoking an entity: {}", e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java index 4c2afbdf8..5b47d80c0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java @@ -1,6 +1,8 @@ package dev.sunbirdrc.registry.controller; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.*; @@ -11,6 +13,7 @@ @RestController public class RegistryTemplateController{ + private static final Logger logger = LoggerFactory.getLogger(RegistryTemplateController.class); @Value("${certificate.templateFolderPath}") private String templatesFolderPath; @@ -22,7 +25,7 @@ public String getTemplate(@PathVariable String fileName) { File file = new ClassPathResource(templatesFolderPath + fileName).getFile(); content = new String(Files.readAllBytes(file.toPath())); } catch (IOException e) { - e.printStackTrace(); + logger.info("Fetching template failed: {}", e.getMessage()); } return content; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java index 3e179b743..28646c2f1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java @@ -100,7 +100,7 @@ public ResponseEntity generateSignature(HttpServletRequest requestMode responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in generating signature", e); + logger.error("Error in generating signature, {}", e.getMessage()); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.SIGN_ERROR_MESSAGE); @@ -173,7 +173,7 @@ public ResponseEntity verifySignature(HttpServletRequest request) { responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in verifying signature", e); + logger.error("Error in verifying signature, {}", e.getMessage()); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.VERIFY_SIGN_ERROR_MESSAGE); @@ -198,7 +198,7 @@ public ResponseEntity getKey( @PathVariable("id") String keyId) { responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); } catch (Exception e) { - logger.error("Error in getting key ", e); + logger.error("Error in getting key , {}", e.getMessage()); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.KEY_RETRIEVE_ERROR_MESSAGE); @@ -224,9 +224,9 @@ public ResponseEntity health() { response.setResult(JSONUtil.convertObjectJsonMap(healthCheck)); responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); - logger.debug("Application heath checked : ", healthCheckResult); + logger.debug("Application heath checked : {}", healthCheckResult); } catch (Exception e) { - logger.error("Error in health checking!", e); + logger.error("Error in health checking!, {}", e.getMessage()); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRD_SIGNATURE_SERVICE_NAME, false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); @@ -255,9 +255,9 @@ public ResponseEntity registryHealth() { response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); - logger.debug("Application heath checked : ", healthCheckResult.toString()); + logger.debug("Application heath checked : {}", healthCheckResult.toString()); } catch (Exception e) { - logger.error("Error in health checking!", e); + logger.error("Error in health checking!, {}", e.getMessage()); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRDRC_REGISTRY_API, false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); @@ -283,8 +283,7 @@ public ResponseEntity fetchAudit() { watch.stop("RegistryController.searchEntity"); } catch (Exception e) { - logger.error("Error in getting audit log !", e); - logger.error("Exception in controller while searching entities !", e); + logger.error("Error in getting audit log !, {}", e.getMessage()); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java index 74344b07d..003329a59 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java @@ -17,11 +17,14 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.has; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.hasNot; public class SearchDaoImpl implements SearchDao { + private static final Logger logger = LoggerFactory.getLogger(SearchDaoImpl.class); private IRegistryDao registryDao; public SearchDaoImpl(IRegistryDao registryDaoImpl) { @@ -169,7 +172,7 @@ private JsonNode getResult(Graph graph, GraphTraversal resultTraversal, GraphTra try { answer = registryDao.getEntity(graph, v, configurator, expandInternal); } catch (Exception e) { - e.printStackTrace(); + logger.info("Exception occurred while searching entity: {}", e.getMessage()); } result.add(answer); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java b/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java index d68ca109a..3b346df11 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java @@ -27,7 +27,6 @@ public FrameContext(String frameFileName, String registryContextBase) { frameContent = new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8); } catch (Exception e1) { - e1.printStackTrace(); logger.error(e1.getLocalizedMessage()); } @@ -48,7 +47,6 @@ public String getDomain() { try { frameNode = mapper.readTree(getContent()); } catch (IOException e) { - e.printStackTrace(); logger.error(e.getLocalizedMessage()); } return JSONUtil.findKey(frameNode, registryContextBase); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index c24b8851c..1a69d641c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -257,7 +257,7 @@ private String addEntity(JsonNode inputJson, String userId, String entityType, b watch.stop("RegistryController.addToExistingEntity"); logger.info("AddEntity,{}", recordId.toString()); } catch (Exception e) { - logger.error("Exception in controller while adding entity !", e); + logger.error("Exception in controller while adding entity !, {}", e.getMessage()); throw new Exception(e); } return recordId.toString(); @@ -456,7 +456,7 @@ private void updateGetFileUrl(JsonNode additionalInput) throws UnreachableExcept } catch (ServerException | InternalException | XmlParserException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | IOException | ErrorResponseException | InsufficientDataException e) { - e.printStackTrace(); + logger.info("Fetching signed file url failed: {}", e.getMessage()); } } ((ObjectNode)additionalInput).replace(FILE_URL, signedUrls); @@ -682,8 +682,7 @@ private void uploadAttestedFiles(PluginResponseMessage pluginResponseMessage, Ob try { fileStorageService.save(new ByteArrayInputStream(file.getFile()), propertyURI); } catch (Exception e) { - logger.error("Failed persisting file", e); - e.printStackTrace(); + logger.error("Failed persisting file: {}", e.getMessage()); } fileUris.add(propertyURI); }); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index 2e0ed2c04..02d85004b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java @@ -63,8 +63,7 @@ public DocumentsResponse saveAndFetchFileNames(MultipartFile[] files, String req documentsResponse.addDocumentLocation(objectName); } catch (Exception e) { documentsResponse.addError(file.getOriginalFilename()); - logger.error("Error has occurred while trying to save the file {}", fileName); - e.printStackTrace(); + logger.error("Error has occurred while trying to save the file {}: {}", fileName, e.getMessage()); } } return documentsResponse; @@ -91,7 +90,6 @@ public DocumentsResponse deleteFiles(List files) { documentsResponse.addError(result.get().bucketName()); } catch (Exception e) { logger.error("Error has occurred while fetching the delete error result {}", e.getMessage()); - e.printStackTrace(); } } return documentsResponse; @@ -109,7 +107,6 @@ public byte[] getDocument(String requestedURI) { bytes = IOUtils.toByteArray(inputStream); } catch (Exception e) { logger.error("Error has occurred while fetching the document {} {}", objectName, e.getMessage()); - e.printStackTrace(); } return bytes; } @@ -120,7 +117,6 @@ public ResponseEntity deleteDocument(String requestedURI) { minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build()); } catch (Exception e) { logger.error("Error has occurred while deleting the document {}", objectName); - e.printStackTrace(); return new ResponseEntity(HttpStatus.BAD_REQUEST); } return new ResponseEntity(HttpStatus.OK); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java index 109652df9..168255bf2 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java @@ -125,7 +125,7 @@ protected JsonNode process(JsonNode jsonNode, String rootFieldName, String field processArray((ArrayNode) entryValue, tempFieldName, entry.getKey()); } } catch (EncryptionException e) { - e.printStackTrace(); + logger.info("Exception occurred in PrivateField: {}", e.getMessage()); } } return jsonNode; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java index 3db7d0e05..4fcf48780 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java @@ -34,7 +34,7 @@ public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) logger.info(JSONUtil.convertObjectJsonString(resolvedDefinitions)); return resolvedDefinitions; } catch (IOException e) { - e.printStackTrace(); + logger.info("Failed resolving schema definitions for {}: {}", rootDefinitionName, e.getMessage()); } return null; } diff --git a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java index 8bbb99a42..741677df6 100644 --- a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java +++ b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java @@ -79,19 +79,22 @@ public void onReceive(Object genericMessage) throws Throwable { msgWithSrc.getSourceActorName(), msgWithSrc.getTargetActorName()); } - - // Act upon the message. - onReceive(msgWithSrc); - - // Ack if this is of type 'ask'. - if (msgWithSrc.getMsgOption() == MessageProtos.MessageOption.GET_BACK_RESPONSE) { - responseMsgBldr.setPerformOperation("onSuccess"); - Value.Builder payloadBuilder = responseMsgBldr.getPayloadBuilder(); - payloadBuilder.setStringValueBytes(ByteString.EMPTY); - - MessageProtos.Message response = responseMsgBldr.build(); - - tellToSource(response); + try { + // Act upon the message. + onReceive(msgWithSrc); + + // Ack if this is of type 'ask'. + if (msgWithSrc.getMsgOption() == MessageProtos.MessageOption.GET_BACK_RESPONSE) { + responseMsgBldr.setPerformOperation("onSuccess"); + Value.Builder payloadBuilder = responseMsgBldr.getPayloadBuilder(); + payloadBuilder.setStringValueBytes(ByteString.EMPTY); + + MessageProtos.Message response = responseMsgBldr.build(); + + tellToSource(response); + } + } catch (Exception e) { + logger.info("Exception occurred while Act upon the message {}", e.getMessage()); } } diff --git a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java index 0dbb8dd25..d3f2850d3 100644 --- a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java +++ b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java @@ -125,8 +125,7 @@ private boolean route(ActorSelection router, ActorRef ref, MessageProtos.Message public void onComplete(Throwable failure, Object result) { if (failure != null) { // We got a failure, handle it here - logger.error(failure.getMessage(), failure); - failure.printStackTrace(); + logger.error("Exception occurred: {}", failure.getMessage()); } onResponse(message, result, failure); } diff --git a/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java b/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java index 5421f8dda..6010de8ff 100644 --- a/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java +++ b/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java @@ -53,7 +53,7 @@ private Schema getEntitySchema(String entityType) throws MiddlewareHaltException return null; } } catch (Exception ioe) { - ioe.printStackTrace(); + logger.info("can't validate, {}: schema has a problem!, {}", entityType, ioe.getMessage()); throw new MiddlewareHaltException("can't validate, "+ entityType + ": schema has a problem!"); } return schema; diff --git a/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java b/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java index 3fbd9a2a8..e0b052e83 100644 --- a/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java +++ b/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java @@ -76,10 +76,7 @@ private static String readFileContent(String fileName) { } catch (FileNotFoundException e1) { e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - - } + } catch (IOException e) {} return null; } From d3910716b1e9ce89b9d1c5bf3b3e744523b3bcea Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 14:02:16 +0530 Subject: [PATCH 13/28] minor fix --- services/certificate-api/src/routes/certificate_controller.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/certificate-api/src/routes/certificate_controller.js b/services/certificate-api/src/routes/certificate_controller.js index c84a346aa..614789f78 100644 --- a/services/certificate-api/src/routes/certificate_controller.js +++ b/services/certificate-api/src/routes/certificate_controller.js @@ -299,9 +299,9 @@ async function createPDF(certificate) { // close the browser await page.close() return pdfBuffer - } catch (e) { + } catch (err) { console.log("Failed while creating pdf") - console.log(e) + console.log(err?.message) } } From 99b4d15ee03c7f899e0c940609d987d34f53c315 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 14:50:19 +0530 Subject: [PATCH 14/28] fixed certificate api docker file --- services/certificate-api/Dockerfile | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/services/certificate-api/Dockerfile b/services/certificate-api/Dockerfile index 436422a71..1c3836192 100644 --- a/services/certificate-api/Dockerfile +++ b/services/certificate-api/Dockerfile @@ -1,9 +1,5 @@ FROM node:lts-alpine -RUN apk update && apk add --no-cache nmap && \ - echo @edge http://nl.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \ - echo @edge http://nl.alpinelinux.org/alpine/edge/main >> /etc/apk/repositories && \ - apk update && \ - apk add --no-cache \ +RUN apk add \ chromium \ harfbuzz \ "freetype>2.8" \ From a516175eab1ded59ae651f485a9fffb6b23d9d8c Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 15:20:10 +0530 Subject: [PATCH 15/28] added debug plugin --- .github/workflows/maven.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index d5789c7cc..1ea9ab2db 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -22,6 +22,11 @@ jobs: cache: 'maven' - name: Set up properties run: sh configure-dependencies.sh + - name: Setup upterm session + uses: lhotari/action-upterm@v1 + with: + ## limits ssh access and adds the ssh public key for the user which triggered the workflow + limit-access-to-actor: true - name: Build and test run: make test # test: From bb1d82a3d9fd6212eaa0dca1c60e0222dbbb9635 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 15:26:45 +0530 Subject: [PATCH 16/28] added public key --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 1ea9ab2db..d723ec3c6 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -25,7 +25,7 @@ jobs: - name: Setup upterm session uses: lhotari/action-upterm@v1 with: - ## limits ssh access and adds the ssh public key for the user which triggered the workflow + ## limits ssh access and adds the ssh public key for the user which triggered the workflow ie holashchand limit-access-to-actor: true - name: Build and test run: make test From 33b074a677776f1f52f110bc2645a00ed390b992 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 15:40:03 +0530 Subject: [PATCH 17/28] added manual workflow --- .github/workflows/maven.yml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index d723ec3c6..560123c31 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -8,6 +8,29 @@ on: branches: [ main ] pull_request: branches: [ main ] + workflow_dispatch: + inputs: + logLevel: + description: 'Log level' + required: true + default: 'warning' + type: choice + options: + - info + - warning + - debug + print_tags: + description: 'True to print to STDOUT' + required: true + type: boolean + tags: + description: 'Test scenario tags' + required: true + type: string + environment: + description: 'Environment to run tests against' + type: environment + required: true jobs: build: From 33411ebb9a96b7cce18bef3b54264bdce3ba9657 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Mon, 11 Sep 2023 18:20:44 +0530 Subject: [PATCH 18/28] suppressing exception while loading schema from db --- .../main/java/dev/sunbirdrc/registry/config/SchemaLoader.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java index 004c42632..56e1d30ed 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java @@ -49,12 +49,14 @@ private void loadSchemasFromDB() { try { schemaService.addSchema(JsonNodeFactory.instance.objectNode().set(Schema, schemaNode)); } catch (Exception e) { - logger.error("Failed loading schema to definition manager:", e); + logger.error("Failed loading schema to definition manager: {}", e.getMessage()); } } logger.info("Loaded {} schema from DB", searchResults.get(Schema).size()); } catch (IOException e) { logger.info("Exception occurred while loading schema from db: {}", e.getMessage()); + } catch (Exception e) { + logger.info("Exception occurred while searching for schemas: {}", e.getMessage()); } } } From 263d211750c83171a1cb9174f9f4432fc4046631 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Tue, 12 Sep 2023 13:33:04 +0530 Subject: [PATCH 19/28] fixed elastic search version and removed debug config --- .github/workflows/maven.yml | 34 ++++--------------- docker-compose.yml | 2 +- .../registry/config/SchemaLoader.java | 1 + 3 files changed, 8 insertions(+), 29 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 560123c31..843718b6a 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -8,29 +8,6 @@ on: branches: [ main ] pull_request: branches: [ main ] - workflow_dispatch: - inputs: - logLevel: - description: 'Log level' - required: true - default: 'warning' - type: choice - options: - - info - - warning - - debug - print_tags: - description: 'True to print to STDOUT' - required: true - type: boolean - tags: - description: 'Test scenario tags' - required: true - type: string - environment: - description: 'Environment to run tests against' - type: environment - required: true jobs: build: @@ -45,11 +22,12 @@ jobs: cache: 'maven' - name: Set up properties run: sh configure-dependencies.sh - - name: Setup upterm session - uses: lhotari/action-upterm@v1 - with: - ## limits ssh access and adds the ssh public key for the user which triggered the workflow ie holashchand - limit-access-to-actor: true +# # debug step +# - name: Setup upterm session +# uses: lhotari/action-upterm@v1 +# with: +# ## limits ssh access and adds the ssh public key for the user which triggered the workflow ie holashchand +# limit-access-to-actor: true - name: Build and test run: make test # test: diff --git a/docker-compose.yml b/docker-compose.yml index 002a50a2e..ce0b53252 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,7 +2,7 @@ version: "2.4" services: es: - image: docker.elastic.co/elasticsearch/elasticsearch:8.8.1 + image: docker.elastic.co/elasticsearch/elasticsearch:7.17.13 environment: - discovery.type=single-node - "ES_JAVA_OPTS=-Xms512m -Xmx512m" diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java index 56e1d30ed..74462210e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java @@ -57,6 +57,7 @@ private void loadSchemasFromDB() { logger.info("Exception occurred while loading schema from db: {}", e.getMessage()); } catch (Exception e) { logger.info("Exception occurred while searching for schemas: {}", e.getMessage()); + logger.info("Make sure, you are running a compatible version of search provider"); } } } From c4a34531dc8cf4ab0a79133fac6482a27d07d1e5 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Tue, 12 Sep 2023 15:42:13 +0530 Subject: [PATCH 20/28] fixed error messages --- .../divoc/api/authenticator/NotifyService.java | 9 +++++---- .../claim/service/ClaimsAuthorizer.java | 2 +- .../sunbirdrc/elastic/ElasticServiceImpl.java | 8 ++++---- .../controller/MosipCallbackController.java | 2 +- .../java/dev/sunbirdrc/pojos/APIMessage.java | 2 +- .../dev/sunbirdrc/pojos/ResponseWrapper.java | 4 ++-- .../registry/config/MinioClientConfig.java | 2 +- .../sunbirdrc/registry/config/SchemaFilter.java | 2 +- .../controller/RegistryEntityController.java | 2 +- .../sunbirdrc/registry/dao/SearchDaoImpl.java | 2 +- .../registry/helper/RegistryHelper.java | 10 +++++----- .../registry/service/ElasticReadService.java | 2 +- .../registry/service/ElasticSearchService.java | 4 ++-- .../registry/service/KafkaHealthService.java | 2 +- .../registry/service/NativeSearchService.java | 4 ++-- .../registry/service/WebhookService.java | 2 +- .../registry/service/impl/AuditDBImpl.java | 4 ++-- .../registry/service/impl/AuditFileImpl.java | 2 +- .../registry/service/impl/AuditServiceImpl.java | 2 +- .../service/impl/CertificateServiceImpl.java | 4 ++-- .../service/impl/EncryptionServiceImpl.java | 6 +++--- .../service/impl/SignatureServiceImpl.java | 16 ++++++++-------- .../registry/sink/DatabaseProvider.java | 2 +- .../registry/sink/shard/ShardAdvisor.java | 2 +- .../dev/sunbirdrc/registry/util/ArrayHelper.java | 2 +- .../dev/sunbirdrc/registry/util/Definition.java | 2 +- .../registry/util/DefinitionsManager.java | 4 ++-- .../sunbirdrc/registry/util/EntityParenter.java | 9 ++++----- .../dev/sunbirdrc/registry/util/RefResolver.java | 2 +- .../sunbirdrc/registry/util/ServiceProvider.java | 4 ++-- .../registry/util/ViewTemplateManager.java | 2 +- .../provider/RemovePathFunctionProvider.java | 4 ++-- .../sunbirdrc/provider/UUIDFunctionProvider.java | 2 +- scripts/index.js | 4 ++-- .../src/routes/certificate_controller.js | 4 ++-- services/certificate-signer/main.js | 2 +- services/public-key-service/main.js | 2 +- .../src/components/VerifyCertificate/index.js | 2 +- 38 files changed, 71 insertions(+), 71 deletions(-) diff --git a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java index b5f74b8b7..f26c1b543 100644 --- a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java +++ b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java @@ -1,7 +1,8 @@ package in.divoc.api.authenticator; -import okhttp3.*; -import org.jboss.logging.Logger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; @@ -12,7 +13,7 @@ import java.nio.charset.StandardCharsets; public class NotifyService { - private static final Logger logger = Logger.getLogger(NotifyService.class); + private static final Logger logger = LoggerFactory.getLogger(NotifyService.class); private static final String notificationURL = System.getenv().getOrDefault("NOTIFICATION_SERVICE_URL", "http://localhost:8765/notification-service/v1/notification"); private static final String messageTemplate = System.getenv().getOrDefault("MESSAGE_TEMPLATE", "Your OTP to access SunbirdRC portal is %s. Please dont share this with anyone."); @@ -44,7 +45,7 @@ public void notify(String to, String otp) throws IOException { System.out.println(response.toString()); } } catch (IOException e) { - logger.error(e); + logger.error("Exception occurred while notifying: {}", e.getMessage()); } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java index 2daf26eaa..d5caa8a0c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java @@ -35,7 +35,7 @@ public boolean isAuthorizedAttestor(Claim claim, JsonNode attestorNode) { ); return conditionResolverService.evaluate(resolvedCondition); } catch (Exception e) { - logger.error(e.getMessage()); + logger.error("Exception occurred while resolving condition {}", e.getMessage()); return false; } } diff --git a/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java b/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java index 56b22f339..b7916e08d 100644 --- a/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java +++ b/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java @@ -200,7 +200,7 @@ public RestStatus addEntity(String index, String entityId, JsonNode inputEntity) Map inputMap = JSONUtil.convertJsonNodeToMap(inputEntity); response = getClient(index).index(new IndexRequest(index, searchType, entityId).source(inputMap), RequestOptions.DEFAULT); } catch (IOException e) { - logger.error("Exception in adding record to ElasticSearch", e); + logger.error("Exception in adding record to ElasticSearch: {}", e.getMessage()); } return response.status(); } @@ -242,7 +242,7 @@ public RestStatus updateEntity(String index, String osid, JsonNode inputEntity) logger.debug("updateEntity inputEntity {}", inputEntity); response = getClient(index.toLowerCase()).update(new UpdateRequest(index.toLowerCase(), searchType, osid).doc(inputMap), RequestOptions.DEFAULT); } catch (IOException e) { - logger.error("Exception in updating a record to ElasticSearch", e); + logger.error("Exception in updating a record to ElasticSearch: {}", e.getMessage()); } return response.status(); } @@ -264,7 +264,7 @@ public RestStatus deleteEntity(String index, String osid) { readMap.put(Constants.STATUS_KEYWORD, Constants.STATUS_INACTIVE); response = getClient(indexL).update(new UpdateRequest(indexL, searchType, osid).doc(readMap), RequestOptions.DEFAULT); } catch (NullPointerException | IOException e) { - logger.error("exception in deleteEntity {}", e); + logger.error("exception in deleteEntity {}", e.getMessage()); return RestStatus.NOT_FOUND; } return response.status(); @@ -308,7 +308,7 @@ public ComponentHealthInfo getHealthInfo() { ClusterHealthResponse health = getClient("schema").cluster().health(request, RequestOptions.DEFAULT); return new ComponentHealthInfo(getServiceName(), Arrays.asList("yellow", "green").contains(health.getStatus().name().toLowerCase()), "", ""); } catch (IOException e) { - logger.error("Elastic health status", e); + logger.error("Elastic health status {}", e.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java index f5b02c837..1361a5806 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java @@ -69,7 +69,7 @@ public ResponseEntity callbackHandler(@RequestHeader Map headers return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(queryParams.get(Constants.HUB_CHALLENGE)); } } catch (Exception e) { - LOGGER.error("Failed fetching mosip pdf", e); + LOGGER.error("Failed fetching mosip pdf: {}", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(queryParams.get(Constants.HUB_CHALLENGE)); } } diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java index 0d2fe21b3..e935c0162 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java @@ -42,7 +42,7 @@ public APIMessage(HttpServletRequest servletRequest) { try { request = new ObjectMapper().readValue(body, Request.class); } catch (IOException jpe) { - logger.error("Can't read request body", jpe); + logger.error("Can't read request body: {}", jpe.getMessage()); request = null; } } diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java index dfdf3b172..7af184cb7 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java @@ -42,13 +42,13 @@ public void writeResponseBody(String content) { bufferedWriter.write(content); } } catch (Exception ex) { - logger.error("ERROR IN SENDING RESPONSE:", ex); + logger.error("ERROR IN SENDING RESPONSE: {}", ex.getMessage()); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (Exception ex) { - logger.error("ERROR in closing stream", ex); + logger.error("ERROR in closing stream: {}", ex.getMessage()); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java index b70ce573b..235c5e61a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java @@ -38,7 +38,7 @@ public MinioClient minioClient() { logger.info("Minio bucket already exists: {}", bucketName); } } catch (Exception e) { - logger.error("Minio initialization failed: {}", e.getMessage(), e); + logger.error("Minio initialization failed: {}", e.getMessage()); } return minioClient; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java index 7bb07d446..75fe4964d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java @@ -31,7 +31,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } filterChain.doFilter(servletRequest, servletResponse); } catch (Exception e) { - logger.error("Exception while applying security filters: ", e); + logger.error("Exception while applying security filters: {}", e.getMessage()); throw e; } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 393899465..9c60b3f80 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -545,7 +545,7 @@ public ResponseEntity getEntityType(@PathVariable String entityName, JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) ), HttpStatus.OK); } catch (Exception exception) { - logger.info("Exception occurred while producing entity certificate: {}", exception.getMessage()); + logger.error("Exception occurred while producing entity certificate: {}", exception.getMessage()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java index 003329a59..10cf9b80a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java @@ -172,7 +172,7 @@ private JsonNode getResult(Graph graph, GraphTraversal resultTraversal, GraphTra try { answer = registryDao.getEntity(graph, v, configurator, expandInternal); } catch (Exception e) { - logger.info("Exception occurred while searching entity: {}", e.getMessage()); + logger.error("Exception occurred while searching entity: {}", e.getMessage()); } result.add(answer); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 1a69d641c..66d01684a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -456,7 +456,7 @@ private void updateGetFileUrl(JsonNode additionalInput) throws UnreachableExcept } catch (ServerException | InternalException | XmlParserException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | IOException | ErrorResponseException | InsufficientDataException e) { - logger.info("Fetching signed file url failed: {}", e.getMessage()); + logger.error("Fetching signed file url failed: {}", e.getMessage()); } } ((ObjectNode)additionalInput).replace(FILE_URL, signedUrls); @@ -631,7 +631,7 @@ private void triggerNextFLowIfExists(PluginResponseMessage pluginResponseMessage .propertyData(JSONUtil.convertStringJsonNode(pluginResponseMessage.getResponse())).build(); triggerAttestation(attestationRequest, nextAttestationPolicy); } catch (PolicyNotFoundException e) { - logger.error("Next level attestation policy not found:", e); + logger.error("Next level attestation policy not found: {}", e.getMessage()); } } else if (attestationPolicy.getCompletionType() == FlowType.FUNCTION) { FunctionDefinition functionDefinition = definitionsManager.getDefinition(sourceEntity).getOsSchemaConfiguration() @@ -645,7 +645,7 @@ private void triggerNextFLowIfExists(PluginResponseMessage pluginResponseMessage updateEntity(updatedNode, userId); } } catch (JsonProcessingException e) { - logger.error("Exception while executing function definition: {} {}", attestationPolicy.getOnComplete(), functionDefinition, e); + logger.error("Exception while executing function definition: {} {}, {}", attestationPolicy.getOnComplete(), functionDefinition, e.getMessage()); } } else { logger.error("Invalid function name specified for onComplete: {}", attestationPolicy.getOnComplete()); @@ -824,7 +824,7 @@ public String authorize(String entityName, String entityId, HttpServletRequest r try { return authorizeManageEntity(request, entityName); } catch (Exception e) { - logger.error("Exception while authorizing roles", e); + logger.error("Exception while authorizing roles: {}", e.getMessage()); } } JsonNode response = readEntity(userIdFromRequest, entityName, entityId, false, null, false); @@ -1080,7 +1080,7 @@ private List getAttestationsFromRegistry(String entityName) { JsonNode searchResponse = searchEntity(searchRequest); return convertJsonNodeToAttestationList(searchResponse); } catch (Exception e) { - logger.error("Error fetching attestation policy", e); + logger.error("Error fetching attestation policy: {}", e.getMessage()); return Collections.emptyList(); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java index 1e77fa9d5..c9ef129d1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java @@ -61,7 +61,7 @@ public JsonNode getEntity(Shard shard, String userId, String id, String entityTy try { response = elasticService.readEntity(entityType.toLowerCase(), id); } catch (IOException e) { - logger.error("Exception in reading a record to ElasticSearch", e); + logger.error("Exception in reading a record to ElasticSearch: {}", e.getMessage()); } if (response == null || Constants.STATUS_INACTIVE.equals(response.get(Constants.STATUS_KEYWORD)) ) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java index 2b0041f40..22dbf06e4 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java @@ -85,7 +85,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { resultNode.set(indexName, node); } catch (Exception e) { - logger.error("Elastic search operation - {}", e); + logger.error("Exception in Elastic search operation: {}", e.getMessage()); } } @@ -93,7 +93,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { auditService.auditElasticSearch( new AuditRecord().setUserId(apiMessage.getUserID()), searchQuery.getEntityTypes(), inputQueryNode); } catch (Exception e) { - logger.error("Exception while auditing " + e); + logger.error("Exception while auditing: {}", e.getMessage()); } return resultNode; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java index a905a6e90..e3fdd4ee3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java @@ -39,7 +39,7 @@ public ComponentHealthInfo getHealthInfo() { DescribeClusterResult clusterDescription = kafkaAdminClient.describeCluster(options); return new ComponentHealthInfo(getServiceName(), clusterDescription.nodes().get().size() > 0); } catch (Exception e) { - logger.error("Kafka connection exception,", e); + logger.error("Kafka connection exception: {}", e.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java index fdf00989e..f48a379b5 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java @@ -125,7 +125,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { } } } catch (Exception e) { - logger.error("search operation failed: {}", e); + logger.error("search operation failed: {}", e.getMessage()); } finally { continueSearch = !isSpecificSearch; } @@ -136,7 +136,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { .setTransactionId(transaction), shard, searchQuery.getEntityTypes(), inputQueryNode); } catch (Exception e) { - logger.error("Exception while auditing " + e); + logger.error("Exception while auditing: {}", e.getMessage()); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java index 65869d2b4..6a9283a73 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java @@ -34,7 +34,7 @@ public void postEvent(WebhookEvent event) { ResponseEntity response = retryRestTemplate.postForEntity(event.getWebhookUrl(), entity); } catch (JsonProcessingException e) { - logger.error("Failed calling webhook event, {}", e.getMessage(), e); + logger.error("Failed calling webhook event: {}", e.getMessage()); } } else { logger.info("Webhook service is disabled"); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java index 6ddf2fa9d..ecf30a75f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java @@ -59,9 +59,9 @@ public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) { auditToDB(rootNode, entityType, shard); } catch (AuditFailedException ae) { - logger.error("Error in saving audit info: {}", ae); + logger.error("Error in saving audit info: {}", ae.getMessage()); } catch (Exception e) { - logger.error("Generic error in saving audit info : {}", e); + logger.error("Generic error in saving audit info : {}", e.getMessage()); } logger.debug("doAudit ends"); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java index 1168993ca..d30ddc267 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditFileImpl.java @@ -35,7 +35,7 @@ public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) { // sendAuditToActor(auditRecord, inputNode, auditRecord.getEntityType()); } catch (Exception e) { - logger.error("Generic error in saving audit info : {}", e); + logger.error("Generic error in saving audit info : {}", e.getMessage()); } logger.debug("doAudit ends"); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java index db2752ab0..fda1f34f0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java @@ -165,7 +165,7 @@ public List createAuditInfoWithJson(String auditAction, JsonNode diff try { auditItemDetails = Arrays.asList(objectMapper.treeToValue(differenceJson, AuditInfo[].class)); } catch (Exception e) { - logger.error("Generic error in saving audit info : {}", e); + logger.error("Generic error in saving audit info : {}", e.getMessage()); } return auditItemDetails; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index f871d8a31..775708f64 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -65,7 +65,7 @@ public Object getCertificate(JsonNode certificateData, String entityName, String HttpEntity> httpEntity = new HttpEntity<>(requestBody, headers); return restTemplate.postForObject(certificateUrl, httpEntity, byte[].class); } catch (Exception e) { - logger.error("Get certificate failed", e); + logger.error("Get certificate failed: {}", e.getMessage()); } return null; } @@ -103,7 +103,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), false); } } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the Sunbird certificate service: ", ex); + logger.error("RestClientException when checking the health of the certificate service: {}", ex.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java index cd708ea48..3bdf8d8e6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java @@ -69,10 +69,10 @@ public String encrypt(Object propertyValue) throws EncryptionException { ResponseEntity response = retryRestTemplate.postForEntity(encryptionUri, request); return response.getBody(); } catch (ResourceAccessException e) { - logger.error("ResourceAccessException while connecting enryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service! "); + logger.error("ResourceAccessException while connecting encryption service : {}", e.getMessage()); + throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { - logger.error("Exception in encryption service !: ", e); + logger.error("Exception in encryption service !: {}", e.getMessage()); throw new EncryptionException("Exception in encryption service"); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java index e141ef943..ea0039e83 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java @@ -66,7 +66,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), false); } } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the Sunbird signature service: ", ex); + logger.error("RestClientException when checking the health of the Sunbird signature service: {}", ex.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } else { @@ -99,13 +99,13 @@ public Object sign(Map propertyValue) result = objectMapper.readTree(response.getBody()); logger.info("Successfully generated signed credentials"); } catch (SignatureException.UnreachableException ex) { - logger.error("SignatureException when signing: ", ex); + logger.error("SignatureException when signing: {}", ex.getMessage()); throw ex; } catch (RestClientException ex) { - logger.error("RestClientException when signing: ", ex); + logger.error("RestClientException when signing: {}", ex.getMessage()); throw new SignatureException().new UnreachableException(ex.getMessage()); } catch (Exception e) { - logger.error("SignatureException when signing: ", e); + logger.error("SignatureException when signing: {}", e.getMessage()); throw new SignatureException().new CreationException(e.getMessage()); } return result; @@ -128,10 +128,10 @@ public boolean verify(Object propertyValue) JsonNode resultNode = objectMapper.readTree(response.getBody()); result = resultNode.get("verified").asBoolean(); } catch (RestClientException ex) { - logger.error("RestClientException when verifying: ", ex); + logger.error("RestClientException when verifying: {}", ex.getMessage()); throw new SignatureException().new UnreachableException(ex.getMessage()); } catch (Exception e) { - logger.error("RestClientException when verifying: ", e); + logger.error("RestClientException when verifying: {}", e.getMessage()); throw new SignatureException().new VerificationException(e.getMessage()); } logger.debug("verify method ends with value {}",result); @@ -154,10 +154,10 @@ public String getKey(String keyId) response = retryRestTemplate.getForEntity(keysURL + "/" + keyId); result = response.getBody(); } catch (RestClientException ex) { - logger.error("RestClientException when verifying: ", ex); + logger.error("RestClientException when verifying: {}", ex.getMessage()); throw new SignatureException().new UnreachableException(ex.getMessage()); } catch (Exception e) { - logger.error("RestClientException when verifying: ", e); + logger.error("RestClientException when verifying: {}", e.getMessage()); throw new SignatureException().new KeyNotFoundException(keyId); } logger.debug("getKey method ends with value {}",result); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java index d46bbf048..92e7ab2b4 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java @@ -182,7 +182,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), databaseStatusUp); } } catch (Exception ex) { - logger.error("Database service is not running. " + ex); + logger.error("Database service is not running: {}", ex.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java index 783edc49f..56c3a7934 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java @@ -25,7 +25,7 @@ public IShardAdvisor getInstance(String advisorClassName) { } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error("Shard advisor class {} cannot be instantiate with exception:", advisorClassName, e); + logger.error("Shard advisor class {} cannot be instantiate with exception: {}", advisorClassName, e.getMessage()); } return advisor; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java index e91e25ba0..b1a6e65e3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java @@ -103,7 +103,7 @@ public static ArrayNode constructArrayNode(String valItems) { TypeFactory.defaultInstance().constructCollectionType(List.class, Object.class)); arrNode = mapper.valueToTree(itemList); } catch (Exception e) { - logger.error("Error in converting array elements to JsonNode" + e); + logger.error("Error in converting array elements to JsonNode: {}", e.getMessage()); } return arrNode; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java index 0e0ffb748..67c450041 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java @@ -48,7 +48,7 @@ public Definition(JsonNode schemaNode) { try { osSchemaConfiguration = mapper.treeToValue(configJson, OSSchemaConfiguration.class); } catch (JsonProcessingException e) { - logger.error("Error processing {} JSON: ", OSCONFIG, e); + logger.error("Error processing {} JSON: {}", OSCONFIG, e.getMessage()); logger.debug(title + " does not have OS configuration."); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java index 2eba53a0a..e0a0404b6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java @@ -138,7 +138,7 @@ public void appendNewDefinition(JsonNode jsonNode) { try { appendNewDefinition(Definition.toDefinition(jsonNode)); } catch (Exception e) { - logger.error("Failed loading schema from DB", e); + logger.error("Failed loading schema from DB: {}", e.getMessage()); } } @@ -157,7 +157,7 @@ public void removeDefinition(JsonNode jsonNode) { String schemaTitle = schemaJsonNode.get(TITLE).asText(); definitionMap.remove(schemaTitle); } catch (Exception e) { - logger.error("Failed removing schema from definition manager", e); + logger.error("Failed removing schema from definition manager: {}", e.getMessage()); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java index c6554103a..74531d634 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java @@ -158,7 +158,7 @@ public Optional ensureKnownParenters() { dbConnectionInfo.getShardId()); } } catch (Exception e) { - logger.error("Can't ensure parents for definitions " + e); + logger.error("Can't ensure parents for definitions: {}", e.getMessage()); } }); @@ -237,8 +237,8 @@ public void ensureIndexExists(DatabaseProvider dbProvider, Vertex parentVertex, asyncAddIndex(dbProvider, shardId, parentVertex, definition); } } catch (Exception e) { - logger.error("ensureIndexExists: Can't create index on table {} for shardId: {} ", definition.getTitle(), - shardId); + logger.error("ensureIndexExists: Can't create index on table {} for shardId {}: {}", definition.getTitle(), + shardId, e.getMessage()); } } @@ -273,8 +273,7 @@ private void asyncAddIndex(DatabaseProvider dbProvider, String shardId, Vertex p indexHelper.updateDefinitionIndex(shardId, definition.getTitle(), true); } } catch (Exception e) { - logger.error(e.getMessage()); - logger.error("Failed Transaction creating index {}", definition.getTitle()); + logger.error("Failed Transaction creating index {}: {}", definition.getTitle(), e.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java index 4fcf48780..7b2427533 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java @@ -78,7 +78,7 @@ private JsonNode fetchDefinition(String refPath, String currentDefinitionName) { } } catch (Exception e) { - logger.error("Fetching definition of $ref {} failed", refPath, e); + logger.error("Fetching definition of $ref {} failed: {}", refPath, e.getMessage()); return null; } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java index e700c0b1a..65e15c4fa 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java @@ -26,7 +26,7 @@ public ISearchService getSearchInstance(String advisorProviderName, boolean elas logger.info("Invoked search provider class with classname: " + advisorProviderName); } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - logger.error("Search provider class {} cannot be instantiate with exception:", advisorProviderName, e); + logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, e.getMessage()); } return searchService; @@ -46,7 +46,7 @@ public IReadService getReadInstance(String advisorProviderName, boolean elasticS } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - logger.error("Search provider class {} cannot be instantiate with exception:", advisorProviderName, e); + logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, e.getMessage()); } return readService; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java index 804eb686d..1116f37e1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java @@ -85,7 +85,7 @@ public ViewTemplate getViewTemplate(JsonNode requestNode) { viewTemp = getViewTemplateByContent(requestNode.get(viewTemplate).toString()); } } catch (Exception e) { - logger.error("Bad request to create a view template, {}", e); + logger.error("Bad request to create a view template, {}", e.getMessage()); } return viewTemp; } diff --git a/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java b/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java index 42f485e69..ec3f9e6ed 100644 --- a/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java +++ b/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java @@ -30,13 +30,13 @@ public JsonNode doAction(List values, String[] paths) { try { documentContext.delete(JsonPath.compile(path)); } catch (Exception e) { - logger.error("Error while deleting path: ", e); + logger.error("Error while deleting path '{}': {}", path, e.getMessage()); } } return new ObjectMapper().readTree(documentContext.jsonString()); } } catch (Exception e) { - logger.error("Error while removing paths: ", e); + logger.error("Error while removing paths: {}", e.getMessage()); } return JsonNodeFactory.instance.textNode(""); diff --git a/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java b/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java index d91d67a4d..00ad4ee9b 100644 --- a/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java +++ b/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java @@ -41,7 +41,7 @@ public String generateUUID(List args) { try { return new ObjectMapper().writeValueAsString(inputNode); } catch (JsonProcessingException e) { - logger.error("Error while performing transformation", e); + logger.error("Error while performing transformation: {}", e.getMessage()); return ""; } } diff --git a/scripts/index.js b/scripts/index.js index 9b71720ab..6450b9206 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -35,7 +35,7 @@ var invoke_add = function (nIter, payload, callback) { //console.log("This is the api response " + JSON.stringify(body)) var apiResponse = JSON.parse(body) if (err) { - console.error(err) + console.error(err?.message) console.log(" error for " + payload) callback(err) } else { @@ -237,7 +237,7 @@ var execute_tasks = function (tasks, fileName, cb) { console.log("Executed tasks") cb(null) } else { - console.error(err) + console.error(err?.message) console.log("One or more errors occurred.") cb(err) } diff --git a/services/certificate-api/src/routes/certificate_controller.js b/services/certificate-api/src/routes/certificate_controller.js index 614789f78..112063fee 100644 --- a/services/certificate-api/src/routes/certificate_controller.js +++ b/services/certificate-api/src/routes/certificate_controller.js @@ -216,7 +216,7 @@ async function getCertificatePDF(req, res) { res = await createCertificatePDF(certificate, templateUrl, res, entityId, entityName, entity); return res } catch (err) { - console.error(err); + console.error(err?.message); res.statusCode = 500; } } @@ -235,7 +235,7 @@ async function getCertificate(req, res) { res = await generateRawCertificate(certificate, templateUrl, entityId, entityName, entity); return res } catch (err) { - console.error(err); + console.error(err?.message); res.statusCode = 500; } } diff --git a/services/certificate-signer/main.js b/services/certificate-signer/main.js index ec5f9886a..b28059922 100644 --- a/services/certificate-signer/main.js +++ b/services/certificate-signer/main.js @@ -37,7 +37,7 @@ const server = http.createServer(async (req, res) => { } console.timeEnd(req.url) } catch (e) { - console.error(e) + console.error(e?.message) res.statusCode = e["code"] || 500; res.end(`{"error": "${http.STATUS_CODES[res.statusCode]}", "message": ${e.message}}`) } diff --git a/services/public-key-service/main.js b/services/public-key-service/main.js index b7e4b526c..7dc4e3f04 100644 --- a/services/public-key-service/main.js +++ b/services/public-key-service/main.js @@ -37,7 +37,7 @@ const server = http.createServer(async (req, res) => { console.timeEnd(req.url) } catch (e) { - console.error(e) + console.error(e?.message) res.statusCode = e["code"] || 500; res.end(`{"error": "${http.STATUS_CODES[res.statusCode]}", "message": ${e.message}}`) } diff --git a/services/verification-ui/src/components/VerifyCertificate/index.js b/services/verification-ui/src/components/VerifyCertificate/index.js index ef39c739e..8927e5907 100644 --- a/services/verification-ui/src/components/VerifyCertificate/index.js +++ b/services/verification-ui/src/components/VerifyCertificate/index.js @@ -29,7 +29,7 @@ export const VerifyCertificate = () => { } }; const handleError = err => { - console.error(err) + console.error(err?.message) }; return (
From 78c9c8b1363ba13585c2f9e248f7fd5fda7e65f3 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Tue, 12 Sep 2023 16:40:50 +0530 Subject: [PATCH 21/28] fixed error messages --- .../registry/service/impl/AuditDBWriter.java | 2 +- .../service/impl/EncryptionServiceImpl.java | 20 +++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBWriter.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBWriter.java index caf9ab52c..67476d1f0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBWriter.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBWriter.java @@ -59,7 +59,7 @@ public String auditToDB(Shard shard, JsonNode rootNode, String entityType) throw logger.debug("Audit added : " + entityId); } catch (Exception e) { - logger.error("Audit failed : {}" + e); + logger.error("Audit failed : {}", e.getMessage()); throw new AuditFailedException("Audit failed : " + e.getMessage()); } finally { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java index 3bdf8d8e6..1f75440f3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java @@ -93,10 +93,10 @@ public String decrypt(Object propertyValue) throws EncryptionException { logger.info("Property decrypted successfully !"); return response.getBody(); } catch (ResourceAccessException e) { - logger.error("ResourceAccessException while connecting dcryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service ! "); + logger.error("ResourceAccessException while connecting decryption service : {}", e.getMessage()); + throw new EncryptionException("Exception while connecting encryption service ! "); } catch (Exception e) { - logger.error("Exception in decryption service !: ", e); + logger.error("Exception in decryption service !: {}", e.getMessage()); throw new EncryptionException("Exception in encryption service ! "); } } @@ -122,10 +122,10 @@ public Map encrypt(Map propertyValue) throws Enc return gson.fromJson(response.getBody(), new TypeToken>() { }.getType()); } catch (ResourceAccessException e) { - logger.error("Exception while connecting enryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service! "); + logger.error("Exception while connecting encryption service : {}", e.getMessage()); + throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { - logger.error("Exception in encryption servie !: ", e); + logger.error("Exception in encryption service !: {}", e.getMessage()); throw new EncryptionException("Exception in encryption service."); } } @@ -152,10 +152,10 @@ public Map decrypt(Map propertyValue) throws Enc return gson.fromJson(response.getBody(), new TypeToken>() { }.getType()); } catch (ResourceAccessException e) { - logger.error("Exception while connecting dcryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service ! "); + logger.error("Exception while connecting decryption service : {}", e.getMessage()); + throw new EncryptionException("Exception while connecting encryption service ! "); } catch (Exception e) { - logger.error("Exception in decryption service !: ", e); + logger.error("Exception in decryption service !: {}", e.getMessage()); throw new EncryptionException("Exception in encryption service ! "); } } @@ -183,7 +183,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, response.getBody()); } } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the Sunbird encryption service: ", ex); + logger.error("RestClientException when checking the health of the encryption service: {}", ex.getMessage()); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } else { From 03145c70913c61b118c35d4a363ff129e4ec92be Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Tue, 12 Sep 2023 18:42:07 +0530 Subject: [PATCH 22/28] change error messages to print stack --- .../api/authenticator/NotifyService.java | 3 +- .../claim/service/ClaimsAuthorizer.java | 3 +- .../sunbirdrc/elastic/ElasticServiceImpl.java | 9 ++-- .../registry/middleware/util/JSONUtil.java | 4 +- .../plugin/services/DivocServices.java | 9 ++-- .../controller/MosipCallbackController.java | 3 +- .../plugin/services/MosipAuthService.java | 5 +- .../plugin/services/MosipServices.java | 21 +++++---- .../java/dev/sunbirdrc/pojos/APIMessage.java | 5 +- .../dev/sunbirdrc/pojos/ResponseWrapper.java | 9 ++-- .../registry/config/MinioClientConfig.java | 3 +- .../controller/RegistryEntityController.java | 47 ++++++++++--------- .../controller/RegistryUtilsController.java | 13 ++--- .../sunbirdrc/registry/dao/SearchDaoImpl.java | 4 +- .../registry/frame/FrameContext.java | 7 +-- .../registry/helper/RegistryHelper.java | 13 ++--- .../registry/service/ElasticReadService.java | 3 +- .../service/ElasticSearchService.java | 5 +- .../registry/service/FileStorageService.java | 7 +-- .../registry/service/KafkaHealthService.java | 3 +- .../registry/service/NativeSearchService.java | 3 +- .../registry/service/WebhookService.java | 3 +- .../service/impl/AuditServiceImpl.java | 3 +- .../service/impl/EncryptionServiceImpl.java | 3 +- .../registry/sink/DatabaseProvider.java | 9 ++-- .../registry/sink/shard/ShardAdvisor.java | 3 +- .../sunbirdrc/registry/util/ArrayHelper.java | 3 +- .../sunbirdrc/registry/util/Definition.java | 3 +- .../registry/util/DefinitionsManager.java | 5 +- .../registry/util/EntityParenter.java | 7 +-- .../sunbirdrc/registry/util/RefResolver.java | 3 +- .../registry/util/ServiceProvider.java | 5 +- .../registry/util/ViewTemplateManager.java | 3 +- .../provider/RemovePathFunctionProvider.java | 5 +- .../provider/UUIDFunctionProvider.java | 3 +- 35 files changed, 137 insertions(+), 100 deletions(-) diff --git a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java index f26c1b543..54867bd78 100644 --- a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java +++ b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java @@ -1,6 +1,7 @@ package in.divoc.api.authenticator; +import org.apache.commons.lang.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +46,7 @@ public void notify(String to, String otp) throws IOException { System.out.println(response.toString()); } } catch (IOException e) { - logger.error("Exception occurred while notifying: {}", e.getMessage()); + logger.error("Exception occurred while notifying: {}", ExceptionUtils.getStackTrace(e)); } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java index d5caa8a0c..04cf69970 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.claim.entity.Claim; import dev.sunbirdrc.registry.middleware.service.ConditionResolverService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -35,7 +36,7 @@ public boolean isAuthorizedAttestor(Claim claim, JsonNode attestorNode) { ); return conditionResolverService.evaluate(resolvedCondition); } catch (Exception e) { - logger.error("Exception occurred while resolving condition {}", e.getMessage()); + logger.error("Exception occurred while resolving condition {}", ExceptionUtils.getStackTrace(e)); return false; } } diff --git a/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java b/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java index b7916e08d..75815048d 100644 --- a/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java +++ b/java/elastic-search/src/main/java/dev/sunbirdrc/elastic/ElasticServiceImpl.java @@ -19,6 +19,7 @@ import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.keyvalue.DefaultKeyValue; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; @@ -200,7 +201,7 @@ public RestStatus addEntity(String index, String entityId, JsonNode inputEntity) Map inputMap = JSONUtil.convertJsonNodeToMap(inputEntity); response = getClient(index).index(new IndexRequest(index, searchType, entityId).source(inputMap), RequestOptions.DEFAULT); } catch (IOException e) { - logger.error("Exception in adding record to ElasticSearch: {}", e.getMessage()); + logger.error("Exception in adding record to ElasticSearch: {}", ExceptionUtils.getStackTrace(e)); } return response.status(); } @@ -242,7 +243,7 @@ public RestStatus updateEntity(String index, String osid, JsonNode inputEntity) logger.debug("updateEntity inputEntity {}", inputEntity); response = getClient(index.toLowerCase()).update(new UpdateRequest(index.toLowerCase(), searchType, osid).doc(inputMap), RequestOptions.DEFAULT); } catch (IOException e) { - logger.error("Exception in updating a record to ElasticSearch: {}", e.getMessage()); + logger.error("Exception in updating a record to ElasticSearch: {}", ExceptionUtils.getStackTrace(e)); } return response.status(); } @@ -264,7 +265,7 @@ public RestStatus deleteEntity(String index, String osid) { readMap.put(Constants.STATUS_KEYWORD, Constants.STATUS_INACTIVE); response = getClient(indexL).update(new UpdateRequest(indexL, searchType, osid).doc(readMap), RequestOptions.DEFAULT); } catch (NullPointerException | IOException e) { - logger.error("exception in deleteEntity {}", e.getMessage()); + logger.error("exception in deleteEntity {}", ExceptionUtils.getStackTrace(e)); return RestStatus.NOT_FOUND; } return response.status(); @@ -308,7 +309,7 @@ public ComponentHealthInfo getHealthInfo() { ClusterHealthResponse health = getClient("schema").cluster().health(request, RequestOptions.DEFAULT); return new ComponentHealthInfo(getServiceName(), Arrays.asList("yellow", "green").contains(health.getStatus().name().toLowerCase()), "", ""); } catch (IOException e) { - logger.error("Elastic health status {}", e.getMessage()); + logger.error("Elastic health status {}", ExceptionUtils.getStackTrace(e)); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } diff --git a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/middleware/util/JSONUtil.java b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/middleware/util/JSONUtil.java index 6265f343e..00769e6b9 100644 --- a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/middleware/util/JSONUtil.java +++ b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/middleware/util/JSONUtil.java @@ -27,8 +27,10 @@ import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.NestedExceptionUtils; public class JSONUtil { @@ -298,7 +300,7 @@ public static JsonNode removeNodesByPath(JsonNode root, Set nodePaths) t try { doc.delete(jsonPath); } catch (Exception e) { - logger.error("Path not found {} {}", jsonPath, e.getMessage()); + logger.error("Path not found {} {}", jsonPath, ExceptionUtils.getStackTrace(e)); } } return convertStringJsonNode(doc.jsonString()); diff --git a/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java b/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java index db6c37ea4..4e6b93273 100644 --- a/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java +++ b/java/plugins/divoc-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/DivocServices.java @@ -1,5 +1,6 @@ package dev.sunbirdrc.plugin.services; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -69,8 +70,8 @@ public String fetchClientToken() { ResponseEntity response = null; try { response = restTemplateProvider.exchange(divocKeycloakUrl, HttpMethod.POST, entity, Map.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Fetching divoc token failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Fetching divoc token failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getBody() != null && response.getBody().containsKey(ACCESS_TOKEN)) { LOGGER.info("Divoc token fetch successfully."); @@ -92,8 +93,8 @@ public byte[] fetchDivocPdf(String clientToken, String preEnrollmentCode, String try { response = restTemplateProvider.exchange(divocUrl, HttpMethod.POST, entity, byte[].class); return response.getBody(); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Fetching divoc PDF failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Fetching divoc PDF failed: {}", ExceptionUtils.getStackTrace(e)); } return null; } diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java index 1361a5806..303c96242 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/controller/MosipCallbackController.java @@ -10,6 +10,7 @@ import dev.sunbirdrc.pojos.PluginFile; import dev.sunbirdrc.pojos.PluginResponseMessage; import dev.sunbirdrc.pojos.attestation.Action; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -69,7 +70,7 @@ public ResponseEntity callbackHandler(@RequestHeader Map headers return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(queryParams.get(Constants.HUB_CHALLENGE)); } } catch (Exception e) { - LOGGER.error("Failed fetching mosip pdf: {}", e.getMessage()); + LOGGER.error("Failed fetching mosip pdf: {}", ExceptionUtils.getStackTrace(e)); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(queryParams.get(Constants.HUB_CHALLENGE)); } } diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java index 8e3c8caa0..8a07a14bb 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipAuthService.java @@ -4,6 +4,7 @@ import dev.sunbirdrc.plugin.dto.AuthRequestDto; import dev.sunbirdrc.plugin.dto.RequestCredentialsDto; import dev.sunbirdrc.plugin.dto.RequestDto; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -51,8 +52,8 @@ public HttpHeaders getAuthTokenHeader() { ResponseEntity response = null; try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.AUTH_URL, HttpMethod.POST, entity, String.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Get auth token failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Get auth token failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully authenticated with mosip"); diff --git a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java index c2592eec0..23611481d 100644 --- a/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java +++ b/java/plugins/mosip-external-plugin/src/main/java/dev/sunbirdrc/plugin/services/MosipServices.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.plugin.constant.Constants; import dev.sunbirdrc.plugin.dto.*; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -79,8 +80,8 @@ void subscribeForPrintServiceEvents() { ResponseEntity response = null; try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.SUBSCRIBE_URL, HttpMethod.POST, entity, String.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Subscription to topic failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Subscription to topic failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getStatusCode() == HttpStatus.ACCEPTED) { LOGGER.info("subscribed for topic {} at hub", topic); @@ -102,8 +103,8 @@ private void registerTopic() { ResponseEntity response = null; try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.REGISTER_URL, HttpMethod.POST, entity, String.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Register topic failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Register topic failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getStatusCode() == HttpStatus.ACCEPTED) { LOGGER.info("topic {} registered at hub", topic); @@ -129,8 +130,8 @@ public Object generateOTP(SendOTPDto otpDto) { ResponseEntity response = null; try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.OTP_URL, HttpMethod.POST, entity, Object.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Generate otp failed failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Generate otp failed failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully generated otp"); @@ -172,8 +173,8 @@ public Object fetchCredentials(FetchCredentialsDto fetchCredentialsDto) { ResponseEntity response = null; try { response = restTemplateProvider.exchange(webSubHubUrl + Constants.CREDENTIALS_URL, HttpMethod.POST, entity, Object.class); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Generate credentials failed failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Generate credentials failed failed: {}", ExceptionUtils.getStackTrace(e)); } if (response != null && response.getStatusCode() == HttpStatus.OK) { LOGGER.info("Successfully generated credentials"); @@ -195,8 +196,8 @@ public byte[] fetchMosipPdf(Map requestHeaders, String requestBo try { response = restTemplateProvider.exchange(printUrl + Constants.PRINT_PDF_URL, HttpMethod.POST, entity, byte[].class); return response.getBody(); - } catch (HttpClientErrorException | HttpServerErrorException exception) { - LOGGER.error("Failed fetching pdf failed: {}", exception.getMessage()); + } catch (HttpClientErrorException | HttpServerErrorException e) { + LOGGER.error("Failed fetching pdf failed: {}", ExceptionUtils.getStackTrace(e)); } LOGGER.error("Failed fetching pdf failed: "); return null; diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java index e935c0162..91a188b15 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/APIMessage.java @@ -1,6 +1,7 @@ package dev.sunbirdrc.pojos; import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -41,8 +42,8 @@ public APIMessage(HttpServletRequest servletRequest) { if(body != null && !body.isEmpty()) { try { request = new ObjectMapper().readValue(body, Request.class); - } catch (IOException jpe) { - logger.error("Can't read request body: {}", jpe.getMessage()); + } catch (IOException e) { + logger.error("Can't read request body: {}", ExceptionUtils.getStackTrace(e)); request = null; } } diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java index 7af184cb7..5863ec412 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/ResponseWrapper.java @@ -1,6 +1,7 @@ package dev.sunbirdrc.pojos; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.util.ContentCachingResponseWrapper; @@ -41,14 +42,14 @@ public void writeResponseBody(String content) { bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); bufferedWriter.write(content); } - } catch (Exception ex) { - logger.error("ERROR IN SENDING RESPONSE: {}", ex.getMessage()); + } catch (Exception e) { + logger.error("ERROR IN SENDING RESPONSE: {}", ExceptionUtils.getStackTrace(e)); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); - } catch (Exception ex) { - logger.error("ERROR in closing stream: {}", ex.getMessage()); + } catch (Exception e) { + logger.error("ERROR in closing stream: {}", ExceptionUtils.getStackTrace(e)); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java index 235c5e61a..15ca43d80 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java @@ -3,6 +3,7 @@ import io.minio.BucketExistsArgs; import io.minio.MakeBucketArgs; import io.minio.MinioClient; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -38,7 +39,7 @@ public MinioClient minioClient() { logger.info("Minio bucket already exists: {}", bucketName); } } catch (Exception e) { - logger.error("Minio initialization failed: {}", e.getMessage()); + logger.error("Minio initialization failed: {}", ExceptionUtils.getStackTrace(e)); } return minioClient; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 9c60b3f80..5ad161e03 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -28,6 +28,7 @@ import dev.sunbirdrc.registry.util.ViewTemplateManager; import dev.sunbirdrc.validators.ValidationException; import org.agrona.Strings; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.jetbrains.annotations.NotNull; @@ -179,7 +180,7 @@ public ResponseEntity deleteEntity( response = new Response(Response.API_ID.DELETE, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("RegistryController: Exception while Deleting entity, {}", e.getMessage()); + logger.error("RegistryController: Exception while Deleting entity, {}", ExceptionUtils.getStackTrace(e)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -215,7 +216,7 @@ public ResponseEntity searchEntity(@PathVariable String entityName, @Req response = new Response(Response.API_ID.SEARCH, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !, {}", e.getMessage()); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -270,7 +271,7 @@ public ResponseEntity putEntity( response = new Response(Response.API_ID.PUT, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("RegistryController: Exception while updating entity (without id)!, {}", e.getMessage()); + logger.error("RegistryController: Exception while updating entity (without id)!, {}", ExceptionUtils.getStackTrace(e)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -323,7 +324,7 @@ public ResponseEntity postEntity( logger.info("Error in validating the request"); return badRequestException(responseParams, response, e.getMessage()); } catch (Exception e) { - logger.error("Exception in controller while adding entity !, {}", e.getMessage()); + logger.error("Exception in controller while adding entity !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(result); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -473,7 +474,7 @@ public ResponseEntity getEntityWithConsent( Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Error in partner api access: {}", e.getMessage()); + logger.error("Error in partner api access: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -497,8 +498,8 @@ private ArrayList getConsentFields(HttpServletRequest request) { fields.add(key.toString()); } } - } catch (Exception ex) { - logger.error("Error while extracting other claims, {}", ex.getMessage()); + } catch (Exception e) { + logger.error("Error while extracting other claims, {}", ExceptionUtils.getStackTrace(e)); } return fields; } @@ -544,8 +545,8 @@ public ResponseEntity getEntityType(@PathVariable String entityName, getTemplateUrlFromRequest(request, entityName), JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) ), HttpStatus.OK); - } catch (Exception exception) { - logger.error("Exception occurred while producing entity certificate: {}", exception.getMessage()); + } catch (Exception e) { + logger.error("Exception occurred while producing entity certificate: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -570,7 +571,7 @@ private String getTemplateUrlFromRequest(HttpServletRequest request, String enti } catch (UnreachableException e) { throw e; } catch (Exception e) { - logger.error("Exception while parsing certificate templates DID urls, {}", e.getMessage()); + logger.error("Exception while parsing certificate templates DID urls, {}", ExceptionUtils.getStackTrace(e)); return null; } } @@ -625,7 +626,7 @@ public ResponseEntity getEntity( response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Read Api Exception occurred: {}", e.getMessage()); + logger.error("Read Api Exception occurred: {}", ExceptionUtils.getStackTrace(e)); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); @@ -685,7 +686,7 @@ public ResponseEntity getEntityByToken(@PathVariable String entityName, response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !, {}", e.getMessage()); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -717,7 +718,7 @@ public ResponseEntity getEntityForAttestation( return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.info("Fetching attestation properties for entity failed: {}", e.getMessage()); + logger.error("Fetching attestation properties for entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @@ -772,10 +773,10 @@ public ResponseEntity updateProperty( responseParams.setStatus(Response.Status.SUCCESSFUL); responseParams.setResultList(Collections.singletonList(response)); return new ResponseEntity<>(responseParams, HttpStatus.OK); - } catch (Exception exception) { + } catch (Exception e) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - logger.info("Exception occurred which fetching a system property: {}", exception.getMessage()); + responseParams.setErrmsg(e.getMessage()); + logger.info("Exception occurred which fetching a system property: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -805,10 +806,10 @@ public ResponseEntity updateAttestationProperty( responseParams.setErrmsg(ex.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); return new ResponseEntity<>(responseParams, HttpStatus.SERVICE_UNAVAILABLE); - } catch (Exception exception) { + } catch (Exception e) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - logger.info("Exception occurred while updating attestation: {}", exception.getMessage()); + responseParams.setErrmsg(e.getMessage()); + logger.error("Exception occurred while updating attestation: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -838,7 +839,7 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.error("Exception in controller while searching entities !, {}", e.getMessage()); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -877,10 +878,10 @@ public ResponseEntity getAttestationCertificate(HttpServletRequest reque return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } catch (AttestationNotFoundException e) { - logger.error(e.getMessage()); + logger.error("Attestation not found: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } catch (Exception e) { - logger.info("Fetching attestation certificate failed: {}", e.getMessage()); + logger.info("Fetching attestation certificate failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -920,7 +921,7 @@ public ResponseEntity revokeACredential ( watch.stop(tag); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception e) { - logger.error("Registry Controller: Exception while revoking an entity: {}", e.getMessage()); + logger.error("Registry Controller: Exception while revoking an entity: {}", ExceptionUtils.getStackTrace(e)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java index 28646c2f1..472a118df 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryUtilsController.java @@ -21,6 +21,7 @@ import dev.sunbirdrc.registry.service.SignatureService; import dev.sunbirdrc.registry.sink.shard.Shard; import dev.sunbirdrc.registry.sink.shard.ShardManager; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -100,7 +101,7 @@ public ResponseEntity generateSignature(HttpServletRequest requestMode responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in generating signature, {}", e.getMessage()); + logger.error("Error in generating signature, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.SIGN_ERROR_MESSAGE); @@ -173,7 +174,7 @@ public ResponseEntity verifySignature(HttpServletRequest request) { responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in verifying signature, {}", e.getMessage()); + logger.error("Error in verifying signature, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.VERIFY_SIGN_ERROR_MESSAGE); @@ -198,7 +199,7 @@ public ResponseEntity getKey( @PathVariable("id") String keyId) { responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); } catch (Exception e) { - logger.error("Error in getting key , {}", e.getMessage()); + logger.error("Error in getting key , {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.KEY_RETRIEVE_ERROR_MESSAGE); @@ -226,7 +227,7 @@ public ResponseEntity health() { responseParams.setStatus(Response.Status.SUCCESSFUL); logger.debug("Application heath checked : {}", healthCheckResult); } catch (Exception e) { - logger.error("Error in health checking!, {}", e.getMessage()); + logger.error("Error in health checking!, {}", ExceptionUtils.getStackTrace(e)); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRD_SIGNATURE_SERVICE_NAME, false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); @@ -257,7 +258,7 @@ public ResponseEntity registryHealth() { responseParams.setStatus(Response.Status.SUCCESSFUL); logger.debug("Application heath checked : {}", healthCheckResult.toString()); } catch (Exception e) { - logger.error("Error in health checking!, {}", e.getMessage()); + logger.error("Error in health checking!, {}", ExceptionUtils.getStackTrace(e)); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRDRC_REGISTRY_API, false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); @@ -283,7 +284,7 @@ public ResponseEntity fetchAudit() { watch.stop("RegistryController.searchEntity"); } catch (Exception e) { - logger.error("Error in getting audit log !, {}", e.getMessage()); + logger.error("Error in getting audit log !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java index 10cf9b80a..f40e09eb6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java @@ -12,6 +12,8 @@ import java.util.ArrayList; import java.util.List; import java.util.function.BiPredicate; + +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; @@ -172,7 +174,7 @@ private JsonNode getResult(Graph graph, GraphTraversal resultTraversal, GraphTra try { answer = registryDao.getEntity(graph, v, configurator, expandInternal); } catch (Exception e) { - logger.error("Exception occurred while searching entity: {}", e.getMessage()); + logger.error("Exception occurred while searching entity: {}", ExceptionUtils.getStackTrace(e)); } result.add(answer); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java b/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java index 3b346df11..ac75f8ecc 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/frame/FrameContext.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.ByteStreams; import dev.sunbirdrc.registry.middleware.util.JSONUtil; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,8 +27,8 @@ public FrameContext(String frameFileName, String registryContextBase) { in = this.getClass().getClassLoader().getResourceAsStream(frameFileName); frameContent = new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8); - } catch (Exception e1) { - logger.error(e1.getLocalizedMessage()); + } catch (Exception e) { + logger.error(ExceptionUtils.getStackTrace(e)); } } @@ -47,7 +48,7 @@ public String getDomain() { try { frameNode = mapper.readTree(getContent()); } catch (IOException e) { - logger.error(e.getLocalizedMessage()); + logger.error(ExceptionUtils.getStackTrace(e)); } return JSONUtil.findKey(frameNode, registryContextBase); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 66d01684a..4e81261e4 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -46,6 +46,7 @@ import org.agrona.Strings; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; +import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.jetbrains.annotations.NotNull; @@ -257,7 +258,7 @@ private String addEntity(JsonNode inputJson, String userId, String entityType, b watch.stop("RegistryController.addToExistingEntity"); logger.info("AddEntity,{}", recordId.toString()); } catch (Exception e) { - logger.error("Exception in controller while adding entity !, {}", e.getMessage()); + logger.error("Exception in controller while adding entity !, {}", ExceptionUtils.getStackTrace(e)); throw new Exception(e); } return recordId.toString(); @@ -456,7 +457,7 @@ private void updateGetFileUrl(JsonNode additionalInput) throws UnreachableExcept } catch (ServerException | InternalException | XmlParserException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | IOException | ErrorResponseException | InsufficientDataException e) { - logger.error("Fetching signed file url failed: {}", e.getMessage()); + logger.error("Fetching signed file url failed: {}", ExceptionUtils.getStackTrace(e)); } } ((ObjectNode)additionalInput).replace(FILE_URL, signedUrls); @@ -631,7 +632,7 @@ private void triggerNextFLowIfExists(PluginResponseMessage pluginResponseMessage .propertyData(JSONUtil.convertStringJsonNode(pluginResponseMessage.getResponse())).build(); triggerAttestation(attestationRequest, nextAttestationPolicy); } catch (PolicyNotFoundException e) { - logger.error("Next level attestation policy not found: {}", e.getMessage()); + logger.error("Next level attestation policy not found: {}", ExceptionUtils.getStackTrace(e)); } } else if (attestationPolicy.getCompletionType() == FlowType.FUNCTION) { FunctionDefinition functionDefinition = definitionsManager.getDefinition(sourceEntity).getOsSchemaConfiguration() @@ -682,7 +683,7 @@ private void uploadAttestedFiles(PluginResponseMessage pluginResponseMessage, Ob try { fileStorageService.save(new ByteArrayInputStream(file.getFile()), propertyURI); } catch (Exception e) { - logger.error("Failed persisting file: {}", e.getMessage()); + logger.error("Failed persisting file: {}", ExceptionUtils.getStackTrace(e)); } fileUris.add(propertyURI); }); @@ -824,7 +825,7 @@ public String authorize(String entityName, String entityId, HttpServletRequest r try { return authorizeManageEntity(request, entityName); } catch (Exception e) { - logger.error("Exception while authorizing roles: {}", e.getMessage()); + logger.error("Exception while authorizing roles: {}", ExceptionUtils.getStackTrace(e)); } } JsonNode response = readEntity(userIdFromRequest, entityName, entityId, false, null, false); @@ -1080,7 +1081,7 @@ private List getAttestationsFromRegistry(String entityName) { JsonNode searchResponse = searchEntity(searchRequest); return convertJsonNodeToAttestationList(searchResponse); } catch (Exception e) { - logger.error("Error fetching attestation policy: {}", e.getMessage()); + logger.error("Error fetching attestation policy: {}", ExceptionUtils.getStackTrace(e)); return Collections.emptyList(); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java index c9ef129d1..5456d91d9 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.Map; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -61,7 +62,7 @@ public JsonNode getEntity(Shard shard, String userId, String id, String entityTy try { response = elasticService.readEntity(entityType.toLowerCase(), id); } catch (IOException e) { - logger.error("Exception in reading a record to ElasticSearch: {}", e.getMessage()); + logger.error("Exception in reading a record to ElasticSearch: {}", ExceptionUtils.getStackTrace(e)); } if (response == null || Constants.STATUS_INACTIVE.equals(response.get(Constants.STATUS_KEYWORD)) ) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java index 22dbf06e4..775c1f264 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.List; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -85,7 +86,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { resultNode.set(indexName, node); } catch (Exception e) { - logger.error("Exception in Elastic search operation: {}", e.getMessage()); + logger.error("Exception in Elastic search operation: {}", ExceptionUtils.getStackTrace(e)); } } @@ -93,7 +94,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { auditService.auditElasticSearch( new AuditRecord().setUserId(apiMessage.getUserID()), searchQuery.getEntityTypes(), inputQueryNode); } catch (Exception e) { - logger.error("Exception while auditing: {}", e.getMessage()); + logger.error("Exception while auditing: {}", ExceptionUtils.getStackTrace(e)); } return resultNode; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index 02d85004b..172b3c276 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java @@ -9,6 +9,7 @@ import io.minio.messages.Bucket; import io.minio.messages.DeleteError; import io.minio.messages.DeleteObject; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.poi.util.IOUtils; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; @@ -63,7 +64,7 @@ public DocumentsResponse saveAndFetchFileNames(MultipartFile[] files, String req documentsResponse.addDocumentLocation(objectName); } catch (Exception e) { documentsResponse.addError(file.getOriginalFilename()); - logger.error("Error has occurred while trying to save the file {}: {}", fileName, e.getMessage()); + logger.error("Error has occurred while trying to save the file {}: {}", fileName, ExceptionUtils.getStackTrace(e)); } } return documentsResponse; @@ -89,7 +90,7 @@ public DocumentsResponse deleteFiles(List files) { try { documentsResponse.addError(result.get().bucketName()); } catch (Exception e) { - logger.error("Error has occurred while fetching the delete error result {}", e.getMessage()); + logger.error("Error has occurred while fetching the delete error result {}", ExceptionUtils.getStackTrace(e)); } } return documentsResponse; @@ -106,7 +107,7 @@ public byte[] getDocument(String requestedURI) { InputStream inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build()); bytes = IOUtils.toByteArray(inputStream); } catch (Exception e) { - logger.error("Error has occurred while fetching the document {} {}", objectName, e.getMessage()); + logger.error("Error has occurred while fetching the document {} {}", objectName, ExceptionUtils.getStackTrace(e)); } return bytes; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java index e3fdd4ee3..c88717344 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/KafkaHealthService.java @@ -2,6 +2,7 @@ import dev.sunbirdrc.pojos.ComponentHealthInfo; import dev.sunbirdrc.pojos.HealthIndicator; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.DescribeClusterOptions; import org.apache.kafka.clients.admin.DescribeClusterResult; @@ -39,7 +40,7 @@ public ComponentHealthInfo getHealthInfo() { DescribeClusterResult clusterDescription = kafkaAdminClient.describeCluster(options); return new ComponentHealthInfo(getServiceName(), clusterDescription.nodes().get().size() > 0); } catch (Exception e) { - logger.error("Kafka connection exception: {}", e.getMessage()); + logger.error("Kafka connection exception: {}", ExceptionUtils.getStackTrace(e)); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java index f48a379b5..f53263427 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.*; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import org.slf4j.Logger; @@ -125,7 +126,7 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { } } } catch (Exception e) { - logger.error("search operation failed: {}", e.getMessage()); + logger.error("search operation failed: {}", ExceptionUtils.getStackTrace(e)); } finally { continueSearch = !isSpecificSearch; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java index 6a9283a73..50c04484d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/WebhookService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import dev.sunbirdrc.registry.model.dto.WebhookEvent; import dev.sunbirdrc.registry.service.impl.RetryRestTemplate; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -34,7 +35,7 @@ public void postEvent(WebhookEvent event) { ResponseEntity response = retryRestTemplate.postForEntity(event.getWebhookUrl(), entity); } catch (JsonProcessingException e) { - logger.error("Failed calling webhook event: {}", e.getMessage()); + logger.error("Failed calling webhook event: {}", ExceptionUtils.getStackTrace(e)); } } else { logger.info("Webhook service is disabled"); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java index fda1f34f0..c85fadd85 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditServiceImpl.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.List; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -165,7 +166,7 @@ public List createAuditInfoWithJson(String auditAction, JsonNode diff try { auditItemDetails = Arrays.asList(objectMapper.treeToValue(differenceJson, AuditInfo[].class)); } catch (Exception e) { - logger.error("Generic error in saving audit info : {}", e.getMessage()); + logger.error("Generic error in saving audit info : {}", ExceptionUtils.getStackTrace(e)); } return auditItemDetails; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java index 1f75440f3..014493882 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java @@ -6,6 +6,7 @@ import dev.sunbirdrc.pojos.SunbirdRCInstrumentation; import dev.sunbirdrc.registry.exception.EncryptionException; import dev.sunbirdrc.registry.service.EncryptionService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -69,7 +70,7 @@ public String encrypt(Object propertyValue) throws EncryptionException { ResponseEntity response = retryRestTemplate.postForEntity(encryptionUri, request); return response.getBody(); } catch (ResourceAccessException e) { - logger.error("ResourceAccessException while connecting encryption service : {}", e.getMessage()); + logger.error("ResourceAccessException while connecting encryption service : {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { logger.error("Exception in encryption service !: {}", e.getMessage()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java index 92e7ab2b4..1e590dba2 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java @@ -3,6 +3,7 @@ import dev.sunbirdrc.pojos.ComponentHealthInfo; import dev.sunbirdrc.pojos.HealthIndicator; import dev.sunbirdrc.registry.middleware.util.Constants; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; @@ -86,7 +87,7 @@ protected void commitTransaction(Graph graph, Transaction tx, boolean closeGraph try { graph.close(); } catch (Exception e) { - logger.error("Can't close graph " + e.getMessage()); + logger.error("Can't close graph " + ExceptionUtils.getStackTrace(e)); } } @@ -181,9 +182,9 @@ public ComponentHealthInfo getHealthInfo() { databaseStatusUp = count >= 0; return new ComponentHealthInfo(getServiceName(), databaseStatusUp); } - } catch (Exception ex) { - logger.error("Database service is not running: {}", ex.getMessage()); - return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); + } catch (Exception e) { + logger.error("Database service is not running: {}", ExceptionUtils.getStackTrace(e)); + return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java index 56c3a7934..9962599d1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/shard/ShardAdvisor.java @@ -1,5 +1,6 @@ package dev.sunbirdrc.registry.sink.shard; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +26,7 @@ public IShardAdvisor getInstance(String advisorClassName) { } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error("Shard advisor class {} cannot be instantiate with exception: {}", advisorClassName, e.getMessage()); + logger.error("Shard advisor class {} cannot be instantiate with exception: {}", advisorClassName, ExceptionUtils.getStackTrace(e)); } return advisor; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java index b1a6e65e3..86ce55d63 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ArrayHelper.java @@ -11,6 +11,7 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -103,7 +104,7 @@ public static ArrayNode constructArrayNode(String valItems) { TypeFactory.defaultInstance().constructCollectionType(List.class, Object.class)); arrNode = mapper.valueToTree(itemList); } catch (Exception e) { - logger.error("Error in converting array elements to JsonNode: {}", e.getMessage()); + logger.error("Error in converting array elements to JsonNode: {}", ExceptionUtils.getStackTrace(e)); } return arrNode; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java index 67c450041..5e21d4966 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,7 +49,7 @@ public Definition(JsonNode schemaNode) { try { osSchemaConfiguration = mapper.treeToValue(configJson, OSSchemaConfiguration.class); } catch (JsonProcessingException e) { - logger.error("Error processing {} JSON: {}", OSCONFIG, e.getMessage()); + logger.error("Error processing {} JSON: {}", OSCONFIG, ExceptionUtils.getStackTrace(e)); logger.debug(title + " does not have OS configuration."); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java index e0a0404b6..0c7ecaab0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DefinitionsManager.java @@ -5,6 +5,7 @@ import dev.sunbirdrc.pojos.OwnershipsAttributes; import dev.sunbirdrc.registry.middleware.util.Constants; import org.apache.commons.collections.map.HashedMap; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -138,7 +139,7 @@ public void appendNewDefinition(JsonNode jsonNode) { try { appendNewDefinition(Definition.toDefinition(jsonNode)); } catch (Exception e) { - logger.error("Failed loading schema from DB: {}", e.getMessage()); + logger.error("Failed loading schema from DB: {}", ExceptionUtils.getStackTrace(e)); } } @@ -157,7 +158,7 @@ public void removeDefinition(JsonNode jsonNode) { String schemaTitle = schemaJsonNode.get(TITLE).asText(); definitionMap.remove(schemaTitle); } catch (Exception e) { - logger.error("Failed removing schema from definition manager: {}", e.getMessage()); + logger.error("Failed removing schema from definition manager: {}", ExceptionUtils.getStackTrace(e)); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java index 74531d634..54f4c2a60 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/EntityParenter.java @@ -8,6 +8,7 @@ import dev.sunbirdrc.registry.sink.DBProviderFactory; import dev.sunbirdrc.registry.sink.DatabaseProvider; import dev.sunbirdrc.registry.sink.OSGraph; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -158,7 +159,7 @@ public Optional ensureKnownParenters() { dbConnectionInfo.getShardId()); } } catch (Exception e) { - logger.error("Can't ensure parents for definitions: {}", e.getMessage()); + logger.error("Can't ensure parents for definitions: {}", ExceptionUtils.getStackTrace(e)); } }); @@ -238,7 +239,7 @@ public void ensureIndexExists(DatabaseProvider dbProvider, Vertex parentVertex, } } catch (Exception e) { logger.error("ensureIndexExists: Can't create index on table {} for shardId {}: {}", definition.getTitle(), - shardId, e.getMessage()); + shardId, ExceptionUtils.getStackTrace(e)); } } @@ -273,7 +274,7 @@ private void asyncAddIndex(DatabaseProvider dbProvider, String shardId, Vertex p indexHelper.updateDefinitionIndex(shardId, definition.getTitle(), true); } } catch (Exception e) { - logger.error("Failed Transaction creating index {}: {}", definition.getTitle(), e.getMessage()); + logger.error("Failed Transaction creating index {}: {}", definition.getTitle(), ExceptionUtils.getStackTrace(e)); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java index 7b2427533..e2dc55898 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.registry.middleware.util.JSONUtil; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -78,7 +79,7 @@ private JsonNode fetchDefinition(String refPath, String currentDefinitionName) { } } catch (Exception e) { - logger.error("Fetching definition of $ref {} failed: {}", refPath, e.getMessage()); + logger.error("Fetching definition of $ref {} failed: {}", refPath, ExceptionUtils.getStackTrace(e)); return null; } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java index 65e15c4fa..3c055528d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ServiceProvider.java @@ -2,6 +2,7 @@ import dev.sunbirdrc.registry.service.IReadService; import dev.sunbirdrc.registry.service.ISearchService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,7 +27,7 @@ public ISearchService getSearchInstance(String advisorProviderName, boolean elas logger.info("Invoked search provider class with classname: " + advisorProviderName); } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, e.getMessage()); + logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, ExceptionUtils.getStackTrace(e)); } return searchService; @@ -46,7 +47,7 @@ public IReadService getReadInstance(String advisorProviderName, boolean elasticS } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, e.getMessage()); + logger.error("Search provider class {} cannot be instantiate with exception: {}", advisorProviderName, ExceptionUtils.getStackTrace(e)); } return readService; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java index 1116f37e1..b9dd6b5a8 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ViewTemplateManager.java @@ -16,6 +16,7 @@ import javax.annotation.PostConstruct; import org.agrona.Strings; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -85,7 +86,7 @@ public ViewTemplate getViewTemplate(JsonNode requestNode) { viewTemp = getViewTemplateByContent(requestNode.get(viewTemplate).toString()); } } catch (Exception e) { - logger.error("Bad request to create a view template, {}", e.getMessage()); + logger.error("Bad request to create a view template, {}", ExceptionUtils.getStackTrace(e)); } return viewTemp; } diff --git a/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java b/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java index ec3f9e6ed..426e67ee5 100644 --- a/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java +++ b/java/view-templates/src/main/java/dev/sunbirdrc/provider/RemovePathFunctionProvider.java @@ -6,6 +6,7 @@ import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import dev.sunbirdrc.views.IViewFunctionProvider; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,13 +31,13 @@ public JsonNode doAction(List values, String[] paths) { try { documentContext.delete(JsonPath.compile(path)); } catch (Exception e) { - logger.error("Error while deleting path '{}': {}", path, e.getMessage()); + logger.error("Error while deleting path '{}': {}", path, ExceptionUtils.getStackTrace(e)); } } return new ObjectMapper().readTree(documentContext.jsonString()); } } catch (Exception e) { - logger.error("Error while removing paths: {}", e.getMessage()); + logger.error("Error while removing paths: {}", ExceptionUtils.getStackTrace(e)); } return JsonNodeFactory.instance.textNode(""); diff --git a/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java b/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java index 00ad4ee9b..2829dc858 100644 --- a/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java +++ b/java/view-templates/src/main/java/dev/sunbirdrc/provider/UUIDFunctionProvider.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.views.IViewFunctionProvider; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +42,7 @@ public String generateUUID(List args) { try { return new ObjectMapper().writeValueAsString(inputNode); } catch (JsonProcessingException e) { - logger.error("Error while performing transformation: {}", e.getMessage()); + logger.error("Error while performing transformation: {}", ExceptionUtils.getStackTrace(e)); return ""; } } From 9c6dc533e2c2dddf2ad4d463c9311463eef44406 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Wed, 13 Sep 2023 11:52:20 +0530 Subject: [PATCH 23/28] changed kafka port exposing to 9092 --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index ce0b53252..4e5991154 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -217,7 +217,7 @@ services: zookeeper: condition: service_started ports: - - "9094:9094" + - "9092:9092" environment: KAFKA_BROKER_ID: "1" KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" From 5d186fd05267bef1b028b9f8510e3750c22f88ca Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Thu, 14 Sep 2023 12:40:04 +0530 Subject: [PATCH 24/28] fixed error messages, failing tests and renamed test environments --- Makefile | 4 +- .../BirthCertificateSchemaRequest.json | 2 +- ...CertificateSchemaRequestForRevokeFlow.json | 2 +- .../transform/Json2LdTransformer.java | 7 ++-- .../transform/Ld2JsonTransformer.java | 7 ++-- .../service/ConditionResolverServiceTest.java | 4 +- .../middleware/util/JSONUtilTest.java | 7 ++-- .../registry/config/GenericConfiguration.java | 3 +- .../registry/config/SchemaFilter.java | 3 +- .../registry/config/SchemaLoader.java | 11 +++--- .../consumers/CreateEntityConsumer.java | 5 ++- .../controller/AbstractController.java | 3 +- .../controller/FileStorageController.java | 7 ++-- .../RegistryAttestationPolicyController.java | 11 +++--- .../RegistryCertificateController.java | 3 +- .../controller/RegistryClaimsController.java | 23 ++++++------ .../controller/RegistryController.java | 17 +++++---- .../controller/RegistrySwaggerController.java | 9 ++++- .../RegistryTemplateController.java | 3 +- .../exception/CustomExceptionHandler.java | 3 +- .../registry/helper/RegistryHelper.java | 3 +- .../registry/service/IAuditService.java | 27 +++++++++----- .../registry/service/ICertificateService.java | 2 +- .../registry/service/NativeSearchService.java | 2 +- .../registry/service/impl/AuditDBImpl.java | 7 ++-- .../registry/service/impl/AuditDBWriter.java | 4 +- .../registry/service/impl/AuditFileImpl.java | 7 +++- .../service/impl/AuditServiceImpl.java | 3 +- .../service/impl/CertificateServiceImpl.java | 34 ++++++++--------- .../service/impl/EncryptionServiceImpl.java | 16 ++++---- .../impl/RegistryAsyncServiceImpl.java | 5 ++- .../service/impl/SignatureServiceImpl.java | 37 ++++++++++--------- .../sunbirdrc/registry/util/PrivateField.java | 3 +- .../sunbirdrc/registry/util/RefResolver.java | 6 +-- java/sunbird-actor/pom.xml | 5 +++ .../java/org/sunbird/akka/core/BaseActor.java | 5 ++- .../java/org/sunbird/akka/core/Router.java | 3 +- .../jsonschema/JsonValidationServiceImpl.java | 5 ++- ...with_asyncCreate_events_notifications.env} | 0 ...th_distributedDefManager_nativeSearch.env} | 0 40 files changed, 176 insertions(+), 132 deletions(-) rename test_environments/{test2.env => test_with_asyncCreate_events_notifications.env} (100%) rename test_environments/{test1.env => test_with_distributedDefManager_nativeSearch.env} (100%) diff --git a/Makefile b/Makefile index 1efc42883..f321d634f 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ test: build @docker-compose down @rm -rf db-data* || echo "no permission to delete" # test with distributed definition manager and native search - @docker-compose --env-file test_environments/test1.env up -d db keycloak registry certificate-signer certificate-api redis + @docker-compose --env-file test_environments/test_with_distributedDefManager_nativeSearch.env up -d db keycloak registry certificate-signer certificate-api redis @echo "Starting the test" && sh build/wait_for_port.sh 8080 @echo "Starting the test" && sh build/wait_for_port.sh 8081 @docker-compose ps @@ -40,7 +40,7 @@ test: build @docker-compose down @rm -rf db-data-1 || echo "no permission to delete" # test with kafka(async), events, notifications, - @docker-compose --env-file test_environments/test2.env up -d db clickhouse redis es keycloak registry certificate-signer certificate-api kafka zookeeper notification-ms metrics + @docker-compose --env-file test_environments/test_with_asyncCreate_events_notifications.env up -d db clickhouse redis es keycloak registry certificate-signer certificate-api kafka zookeeper notification-ms metrics @echo "Starting the test" && sh build/wait_for_port.sh 8080 @echo "Starting the test" && sh build/wait_for_port.sh 8081 @docker-compose ps diff --git a/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequest.json b/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequest.json index 71a0c746a..81ad99edb 100644 --- a/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequest.json +++ b/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequest.json @@ -1,5 +1,5 @@ { "name": "BirthCertificate16", - "schema": "{\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"BirthCertificate\": {\n \"$ref\": \"#/definitions/BirthCertificate\"\n }\n },\n \"required\": [\n \"BirthCertificate\"\n ],\n \"title\": \"BirthCertificate\",\n \"definitions\": {\n \"BirthCertificate\": {\n \"$id\": \"#/properties/BirthCertificate\",\n \"type\": \"object\",\n \"title\": \"The BirthCertificate Schema\",\n \"required\": [\n \"name\",\n \"gender\",\n \"date_of_birth\",\n \"place_of_birth\",\n \"contact\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"gender\": {\n \"type\": \"string\"\n },\n \"date_of_birth\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"hospital\": {\n \"type\": \"string\"\n },\n \"place_of_birth\": {\n \"type\": \"string\",\n \"enum\": [\"Bangalore\", \"Mysore\", \"Mandya\"]\n },\n \"name_of_mother\": {\n \"type\": \"string\"\n },\n \"name_of_father\": {\n \"type\": \"string\"\n },\n \"present_address\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 50\n },\n \"contact\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"_osConfig\": {\n \"uniqueIndexFields\": [\n \"contact\"\n ],\n \"ownershipAttributes\": [],\n \"roles\": [],\n \"inviteRoles\": [\n \"anonymous\"\n ],\n \"credentialTemplate\": {\n \"@context\": [\n \"https://www.w3.org/2018/credentials/v1\",\n {\n \"@context\": {\n \"@version\": 1.1,\n \"@protected\": true,\n \"BirthCertificate\": {\n \"@id\": \"https://github.com/sunbird-specs/vc-specs#BirthCertificate\",\n \"@context\": {\n \"id\": \"@id\",\n \"@version\": 1.1,\n \"@protected\": true,\n \"skills\": \"schema:Text\",\n \"name\": \"schema:Text\",\n \"gender\": \"schema:Text\",\n \"date_of_birth\": \"schema:Text\",\n \"hospital\": \"schema:Text\",\n \"place_of_birth\": \"schema:Text\",\n \"name_of_mother\": \"schema:Text\",\n \"name_of_father\": \"schema:Text\",\n \"present_address\": \"schema:Text\",\n \"contact\": \"schema:Text\"\n }\n }\n }\n }\n ],\n \"type\": [\n \"VerifiableCredential\"\n ],\n \"issuanceDate\": \"2021-08-27T10:57:57.237Z\",\n \"credentialSubject\": {\n \"type\": \"BirthCertificate\",\n \"name\": \"{{name}}\",\n \"gender\": \"{{gender}}\",\n \"date_of_birth\": \"{{date_of_birth}}\",\n \"hospital\": \"{{hospital}}\",\n \"place_of_birth\": \"{{place_of_birth}}\",\n \"name_of_mother\": \"{{name_of_mother}}\",\n \"name_of_father\": \"{{name_of_father}}\",\n \"present_address\": \"{{present_address}}\",\n \"contact\": \"{{contact}}\"\n },\n \"issuer\": \"did:web:sunbirdrc.dev/vc/BirthCertificate\"\n },\n \"certificateTemplates\": {\n \"html\": \"https://gist.githubusercontent.com/tejash-jl/56b97ffcb99f93e2e1ec49e88c0c2c7f/raw/1242b9af7f58b9d5ca1e4f11d442aa4815598a31/BirthCertificate.html\"\n }\n }\n}", + "schema": "{\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"BirthCertificate\": {\n \"$ref\": \"#/definitions/BirthCertificate\"\n }\n },\n \"required\": [\n \"BirthCertificate\"\n ],\n \"title\": \"BirthCertificate\",\n \"definitions\": {\n \"BirthCertificate\": {\n \"$id\": \"#/properties/BirthCertificate\",\n \"type\": \"object\",\n \"title\": \"The BirthCertificate Schema\",\n \"required\": [\n \"name\",\n \"gender\",\n \"date_of_birth\",\n \"place_of_birth\",\n \"contact\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"gender\": {\n \"type\": \"string\"\n },\n \"date_of_birth\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"hospital\": {\n \"type\": \"string\"\n },\n \"place_of_birth\": {\n \"type\": \"string\",\n \"enum\": [\"Bangalore\", \"Mysore\", \"Mandya\"]\n },\n \"name_of_mother\": {\n \"type\": \"string\"\n },\n \"name_of_father\": {\n \"type\": \"string\"\n },\n \"present_address\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 50\n },\n \"contact\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"_osConfig\": {\n \"uniqueIndexFields\": [\n \"contact\"\n ],\n \"ownershipAttributes\": [],\n \"roles\": [],\n \"inviteRoles\": [\n \"anonymous\"\n ],\n \"credentialTemplate\": {\n \"@context\": [\n \"https://www.w3.org/2018/credentials/v1\",\n {\n \"@context\": {\n \"@version\": 1.1,\n \"@protected\": true,\n \"BirthCertificate\": {\n \"@id\": \"https://github.com/sunbird-specs/vc-specs#BirthCertificate\",\n \"@context\": {\n \"id\": \"@id\",\n \"@version\": 1.1,\n \"@protected\": true,\n \"skills\": \"schema:Text\",\n \"name\": \"schema:Text\",\n \"gender\": \"schema:Text\",\n \"date_of_birth\": \"schema:Text\",\n \"hospital\": \"schema:Text\",\n \"place_of_birth\": \"schema:Text\",\n \"name_of_mother\": \"schema:Text\",\n \"name_of_father\": \"schema:Text\",\n \"present_address\": \"schema:Text\",\n \"contact\": \"schema:Text\"\n }\n }\n }\n }\n ],\n \"type\": [\n \"VerifiableCredential\"\n ],\n \"issuanceDate\": \"2021-08-27T10:57:57.237Z\",\n \"credentialSubject\": {\n \"type\": \"BirthCertificate\",\n \"name\": \"{{name}}\",\n \"gender\": \"{{gender}}\",\n \"date_of_birth\": \"{{date_of_birth}}\",\n \"hospital\": \"{{hospital}}\",\n \"place_of_birth\": \"{{place_of_birth}}\",\n \"name_of_mother\": \"{{name_of_mother}}\",\n \"name_of_father\": \"{{name_of_father}}\",\n \"present_address\": \"{{present_address}}\",\n \"contact\": \"{{contact}}\"\n },\n \"issuer\": \"did:web:sunbirdrc.dev/vc/BirthCertificate\"\n },\n \"certificateTemplates\": {\n \"html\": \"https://gist.githubusercontent.com/holashchand/03785ec73f278f955c2dec749afc9e76/raw/b18edeca22980dd388d498e12cb1223e3d6c3a49/BirthCertificate.html\"\n }\n }\n}", "status": "PUBLISHED" } \ No newline at end of file diff --git a/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequestForRevokeFlow.json b/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequestForRevokeFlow.json index 2f42f42ac..d7022755a 100644 --- a/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequestForRevokeFlow.json +++ b/java/apitest/src/test/java/e2e/registry/BirthCertificateSchemaRequestForRevokeFlow.json @@ -1,5 +1,5 @@ { "name": "BirthCertificate139", - "schema": "{\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"BirthCertificate1\": {\n \"$ref\": \"#/definitions/BirthCertificate1\"\n }\n },\n \"required\": [\n \"BirthCertificate1\"\n ],\n \"title\": \"BirthCertificate1\",\n \"definitions\": {\n \"BirthCertificate1\": {\n \"$id\": \"#/properties/BirthCertificate1\",\n \"type\": \"object\",\n \"title\": \"The BirthCertificate1 Schema\",\n \"required\": [\n \"name\",\n \"gender\",\n \"date_of_birth\",\n \"place_of_birth\",\n \"contact\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"gender\": {\n \"type\": \"string\"\n },\n \"date_of_birth\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"hospital\": {\n \"type\": \"string\"\n },\n \"place_of_birth\": {\n \"type\": \"string\",\n \"enum\": [\"Bangalore\", \"Mysore\", \"Mandya\"]\n },\n \"name_of_mother\": {\n \"type\": \"string\"\n },\n \"name_of_father\": {\n \"type\": \"string\"\n },\n \"present_address\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 50\n },\n \"contact\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"_osConfig\": {\n \"uniqueIndexFields\": [\n \"contact\"\n ],\n \"ownershipAttributes\": [],\n \"roles\": [],\n \"inviteRoles\": [\n \"anonymous\"\n ],\n \"credentialTemplate\": {\n \"@context\": [\n \"https://www.w3.org/2018/credentials/v1\",\n {\n \"@context\": {\n \"@version\": 1.1,\n \"@protected\": true,\n \"BirthCertificate1\": {\n \"@id\": \"https://github.com/sunbird-specs/vc-specs#BirthCertificate1\",\n \"@context\": {\n \"id\": \"@id\",\n \"@version\": 1.1,\n \"@protected\": true,\n \"skills\": \"schema:Text\",\n \"name\": \"schema:Text\",\n \"gender\": \"schema:Text\",\n \"date_of_birth\": \"schema:Text\",\n \"hospital\": \"schema:Text\",\n \"place_of_birth\": \"schema:Text\",\n \"name_of_mother\": \"schema:Text\",\n \"name_of_father\": \"schema:Text\",\n \"present_address\": \"schema:Text\",\n \"contact\": \"schema:Text\"\n }\n }\n }\n }\n ],\n \"type\": [\n \"VerifiableCredential\"\n ],\n \"issuanceDate\": \"2021-08-27T10:57:57.237Z\",\n \"credentialSubject\": {\n \"type\": \"BirthCertificate1\",\n \"name\": \"{{name}}\",\n \"gender\": \"{{gender}}\",\n \"date_of_birth\": \"{{date_of_birth}}\",\n \"hospital\": \"{{hospital}}\",\n \"place_of_birth\": \"{{place_of_birth}}\",\n \"name_of_mother\": \"{{name_of_mother}}\",\n \"name_of_father\": \"{{name_of_father}}\",\n \"present_address\": \"{{present_address}}\",\n \"contact\": \"{{contact}}\"\n },\n \"issuer\": \"did:web:sunbirdrc.dev/vc/BirthCertificate1\"\n },\n \"certificateTemplates\": {\n \"html\": \"https://gist.githubusercontent.com/tejash-jl/56b97ffcb99f93e2e1ec49e88c0c2c7f/raw/1242b9af7f58b9d5ca1e4f11d442aa4815598a31/BirthCertificate1.html\"\n }\n }\n}", + "schema": "{\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"BirthCertificate1\": {\n \"$ref\": \"#/definitions/BirthCertificate1\"\n }\n },\n \"required\": [\n \"BirthCertificate1\"\n ],\n \"title\": \"BirthCertificate1\",\n \"definitions\": {\n \"BirthCertificate1\": {\n \"$id\": \"#/properties/BirthCertificate1\",\n \"type\": \"object\",\n \"title\": \"The BirthCertificate1 Schema\",\n \"required\": [\n \"name\",\n \"gender\",\n \"date_of_birth\",\n \"place_of_birth\",\n \"contact\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"gender\": {\n \"type\": \"string\"\n },\n \"date_of_birth\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"hospital\": {\n \"type\": \"string\"\n },\n \"place_of_birth\": {\n \"type\": \"string\",\n \"enum\": [\"Bangalore\", \"Mysore\", \"Mandya\"]\n },\n \"name_of_mother\": {\n \"type\": \"string\"\n },\n \"name_of_father\": {\n \"type\": \"string\"\n },\n \"present_address\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 50\n },\n \"contact\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"_osConfig\": {\n \"uniqueIndexFields\": [\n \"contact\"\n ],\n \"ownershipAttributes\": [],\n \"roles\": [],\n \"inviteRoles\": [\n \"anonymous\"\n ],\n \"credentialTemplate\": {\n \"@context\": [\n \"https://www.w3.org/2018/credentials/v1\",\n {\n \"@context\": {\n \"@version\": 1.1,\n \"@protected\": true,\n \"BirthCertificate1\": {\n \"@id\": \"https://github.com/sunbird-specs/vc-specs#BirthCertificate1\",\n \"@context\": {\n \"id\": \"@id\",\n \"@version\": 1.1,\n \"@protected\": true,\n \"skills\": \"schema:Text\",\n \"name\": \"schema:Text\",\n \"gender\": \"schema:Text\",\n \"date_of_birth\": \"schema:Text\",\n \"hospital\": \"schema:Text\",\n \"place_of_birth\": \"schema:Text\",\n \"name_of_mother\": \"schema:Text\",\n \"name_of_father\": \"schema:Text\",\n \"present_address\": \"schema:Text\",\n \"contact\": \"schema:Text\"\n }\n }\n }\n }\n ],\n \"type\": [\n \"VerifiableCredential\"\n ],\n \"issuanceDate\": \"2021-08-27T10:57:57.237Z\",\n \"credentialSubject\": {\n \"type\": \"BirthCertificate1\",\n \"name\": \"{{name}}\",\n \"gender\": \"{{gender}}\",\n \"date_of_birth\": \"{{date_of_birth}}\",\n \"hospital\": \"{{hospital}}\",\n \"place_of_birth\": \"{{place_of_birth}}\",\n \"name_of_mother\": \"{{name_of_mother}}\",\n \"name_of_father\": \"{{name_of_father}}\",\n \"present_address\": \"{{present_address}}\",\n \"contact\": \"{{contact}}\"\n },\n \"issuer\": \"did:web:sunbirdrc.dev/vc/BirthCertificate1\"\n },\n \"certificateTemplates\": {\n \"html\": \"https://gist.githubusercontent.com/holashchand/03785ec73f278f955c2dec749afc9e76/raw/b18edeca22980dd388d498e12cb1223e3d6c3a49/BirthCertificate.html\"\n }\n }\n}", "status": "PUBLISHED" } \ No newline at end of file diff --git a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Json2LdTransformer.java b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Json2LdTransformer.java index 306c5ba01..462ff6f3d 100644 --- a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Json2LdTransformer.java +++ b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Json2LdTransformer.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.registry.middleware.util.Constants.JsonldConstants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,9 +47,9 @@ public Data transform(Data data) throws TransformationException // Insert context to the result resultNode.setAll(contextNode); return new Data<>(resultNode); - } catch (Exception ex) { - logger.error("Error trnsx : " + ex.getMessage(), ex); - throw new TransformationException(ex.getMessage(), ex, ErrorCode.JSON_TO_JSONLD_TRANFORMATION_ERROR); + } catch (Exception e) { + logger.error("Error trnsx : {}", ExceptionUtils.getStackTrace(e)); + throw new TransformationException(e.getMessage(), e, ErrorCode.JSON_TO_JSONLD_TRANFORMATION_ERROR); } } diff --git a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Ld2JsonTransformer.java b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Ld2JsonTransformer.java index 0dda25180..6054a2521 100644 --- a/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Ld2JsonTransformer.java +++ b/java/middleware-commons/src/main/java/dev/sunbirdrc/registry/transform/Ld2JsonTransformer.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.registry.middleware.util.Constants.JsonldConstants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,9 +29,9 @@ public Data transform(Data data) throws TransformationException ObjectNode input = (ObjectNode) mapper.readTree(data.getData().toString()); JsonNode jsonNode = getconstructedJson(input, keysToPurge); return new Data<>(jsonNode); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - throw new TransformationException(ex.getMessage(), ex, ErrorCode.JSONLD_TO_JSON_TRANFORMATION_ERROR); + } catch (Exception e) { + logger.error(ExceptionUtils.getStackTrace(e)); + throw new TransformationException(e.getMessage(), e, ErrorCode.JSONLD_TO_JSON_TRANFORMATION_ERROR); } } diff --git a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java index e3325b366..6cd5b167c 100644 --- a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java +++ b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/service/ConditionResolverServiceTest.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,7 +48,8 @@ public void shouldReturnTrueForValidExpression() throws IOException { try { resolve = conditionResolverService.resolve(getStudentJsonNode(), requester, condition, attributes); } catch (IOException e) { - logger.info("Exception occurred: {}", e.getMessage()); + logger.error("Exception occurred: {}", ExceptionUtils.getStackTrace(e)); + throw e; } String attestor = "ATTESTOR"; resolve = conditionResolverService.resolve(getTeacherJsonNode(), attestor, resolve, attributes); diff --git a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java index 5dd9c2013..33d78ed9e 100644 --- a/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java +++ b/java/middleware-commons/src/test/java/dev/sunbirdrc/registry/middleware/util/JSONUtilTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.pojos.AuditRecord; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -122,7 +123,7 @@ public void removeNode() { // public void findKey() { // } - private String getContent(String fileName) { + private String getContent(String fileName) throws IOException { InputStream in; try { in = this.getClass().getClassLoader().getResourceAsStream(fileName); @@ -135,9 +136,9 @@ private String getContent(String fileName) { return result.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { - logger.info("Exception occurred: {}", e.getMessage()); + logger.error("Exception occurred: {}", ExceptionUtils.getStackTrace(e)); + throw e; } - return null; } @Test diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java index 6be376b6d..10ffcec5e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/GenericConfiguration.java @@ -32,6 +32,7 @@ import dev.sunbirdrc.validators.IValidate; import dev.sunbirdrc.validators.ValidationFilter; import dev.sunbirdrc.validators.json.jsonschema.JsonValidationServiceImpl; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClientBuilder; @@ -358,7 +359,7 @@ public void addInterceptors(InterceptorRegistry registry) { try { registry.addInterceptor(validationInterceptor()).addPathPatterns("/add").order(orderIdx++); } catch (IOException | CustomException e) { - logger.info("Exception occurred while adding validation interceptor: {}", e.getMessage()); + logger.error("Exception occurred while adding validation interceptor: {}", ExceptionUtils.getStackTrace(e)); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java index 75fe4964d..459fdd58f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaFilter.java @@ -1,6 +1,7 @@ package dev.sunbirdrc.registry.config; import dev.sunbirdrc.registry.util.IDefinitionsManager; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -31,7 +32,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } filterChain.doFilter(servletRequest, servletResponse); } catch (Exception e) { - logger.error("Exception while applying security filters: {}", e.getMessage()); + logger.error("Exception while applying security filters: {}", ExceptionUtils.getStackTrace(e)); throw e; } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java index 74462210e..99d97783c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SchemaLoader.java @@ -8,6 +8,7 @@ import dev.sunbirdrc.registry.service.SchemaService; import dev.sunbirdrc.registry.util.IDefinitionsManager; import dev.sunbirdrc.validators.IValidate; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,15 +50,15 @@ private void loadSchemasFromDB() { try { schemaService.addSchema(JsonNodeFactory.instance.objectNode().set(Schema, schemaNode)); } catch (Exception e) { - logger.error("Failed loading schema to definition manager: {}", e.getMessage()); + logger.error("Failed loading schema to definition manager: {}", ExceptionUtils.getStackTrace(e)); } } - logger.info("Loaded {} schema from DB", searchResults.get(Schema).size()); + logger.error("Loaded {} schema from DB", searchResults.get(Schema).size()); } catch (IOException e) { - logger.info("Exception occurred while loading schema from db: {}", e.getMessage()); + logger.error("Exception occurred while loading schema from db: {}", ExceptionUtils.getStackTrace(e)); } catch (Exception e) { - logger.info("Exception occurred while searching for schemas: {}", e.getMessage()); - logger.info("Make sure, you are running a compatible version of search provider"); + logger.error("Exception occurred while searching for schemas: {}", ExceptionUtils.getStackTrace(e)); + logger.error("Make sure, you are running a compatible version of search provider"); } } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/consumers/CreateEntityConsumer.java b/java/registry/src/main/java/dev/sunbirdrc/registry/consumers/CreateEntityConsumer.java index ada423d2e..7e123b512 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/consumers/CreateEntityConsumer.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/consumers/CreateEntityConsumer.java @@ -13,6 +13,7 @@ import dev.sunbirdrc.registry.sink.shard.Shard; import dev.sunbirdrc.registry.sink.shard.ShardManager; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,7 +79,7 @@ public void createEntityConsumer(@Payload String message, @Header(KafkaHeaders.R postCreateEntityMessage = PostCreateEntityMessage.builder().entityType(entityType).osid(entityOsid) .transactionId(key).userId(createEntityMessage.getUserId()).status(CreateEntityStatus.SUCCESSFUL).message("").build(); } catch (Exception e) { - logger.error("Creating entity failed, {}", e.getMessage(), e); + logger.error("Creating entity failed: {}", ExceptionUtils.getStackTrace(e)); postCreateEntityMessage = PostCreateEntityMessage.builder().status(CreateEntityStatus.FAILED).transactionId(key).message(e.getMessage()).build(); } finally { try { @@ -88,7 +89,7 @@ public void createEntityConsumer(@Payload String message, @Header(KafkaHeaders.R .webhookUrl(webhookUrl) .timestamp(Timestamp.from(Instant.now())).build()); } catch (Exception e) { - logger.error("Sending message to {} topic failed: {}", postCreateEntityMessage, e.getMessage(), e); + logger.error("Sending message to {} topic failed: {}", postCreateEntityMessage, ExceptionUtils.getStackTrace(e)); } acknowledgment.acknowledge(); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java index 0b1c14ea1..18574a09e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/AbstractController.java @@ -10,6 +10,7 @@ import dev.sunbirdrc.registry.transform.Transformer; import dev.sunbirdrc.registry.util.IDefinitionsManager; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -54,7 +55,7 @@ ResponseEntity badRequestException(ResponseParams responseParams, Respon } ResponseEntity internalErrorResponse(ResponseParams responseParams, Response response, Exception ex) { - logger.info("Error in handling the invite: {}", ex.getMessage()); + logger.error("Error in handling the invite: {}", ExceptionUtils.getStackTrace(ex)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg("Error occurred"); if (!StringUtils.isEmpty(ex.getMessage())) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java index 603433f29..e3ebca36f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/FileStorageController.java @@ -3,6 +3,7 @@ import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.model.dto.DocumentsResponse; import dev.sunbirdrc.registry.service.FileStorageService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -38,7 +39,7 @@ public ResponseEntity save(@RequestParam MultipartFile[] file try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - logger.info("Authorizing entity failed: {}", e.getMessage()); + logger.error("Authorizing entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.saveAndFetchFileNames(files, httpServletRequest.getRequestURI()); @@ -54,7 +55,7 @@ public ResponseEntity deleteMultipleFiles(@PathVariable Strin try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - logger.info("Authorizing entity failed: {}", e.getMessage()); + logger.error("Authorizing entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.deleteFiles(files); @@ -70,7 +71,7 @@ public ResponseEntity deleteAFile(@PathVariable String entity, try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - logger.info("Authorizing entity failed: {}", e.getMessage()); + logger.error("Authorizing entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity(HttpStatus.FORBIDDEN); } return fileStorageService.deleteDocument(httpServletRequest.getRequestURI()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java index 4e3d6cb2e..dc5741f6e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryAttestationPolicyController.java @@ -4,6 +4,7 @@ import dev.sunbirdrc.pojos.ResponseParams; import dev.sunbirdrc.registry.entities.AttestationPolicy; import dev.sunbirdrc.registry.entities.AttestationStatus; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -43,7 +44,7 @@ public ResponseEntity createAttestationPolicy(@PathVariable String entityName, @ return badRequestException(responseParams, response, "Invalid entity name"); } } catch (Exception e) { - logger.error("Failed persisting attestation policy: {}", e.getMessage()); + logger.error("Failed persisting attestation policy: {}", ExceptionUtils.getStackTrace(e)); return internalErrorResponse(responseParams, response, e); } } @@ -70,7 +71,7 @@ public ResponseEntity getAttestationPolicies(@PathVariable String entityName, Ht return badRequestException(responseParams, response, "Invalid entity name"); } } catch (Exception e) { - logger.error("Failed getting attestation policy: {}", e.getMessage()); + logger.error("Failed getting attestation policy: {}", ExceptionUtils.getStackTrace(e)); return internalErrorResponse(responseParams, response, e); } } @@ -93,7 +94,7 @@ public ResponseEntity updateAttestationPolicy(@PathVariable String entityName, @ } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: {}", e.getMessage()); + logger.error("Failed updating attestation policy: {}", ExceptionUtils.getStackTrace(e)); return internalErrorResponse(responseParams, response, e); } } @@ -118,7 +119,7 @@ public ResponseEntity updateAttestationPolicyStatus(@PathVariable String entityN } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: {}", e.getMessage()); + logger.error("Failed updating attestation policy: {}", ExceptionUtils.getStackTrace(e)); return internalErrorResponse(responseParams, response, e); } } @@ -143,7 +144,7 @@ public ResponseEntity deleteAttestationPolicy(@PathVariable String entityName, @ } return badRequestException(responseParams, response, "Invalid entity name"); } catch (Exception e) { - logger.error("Failed updating attestation policy: {}", e.getMessage()); + logger.error("Failed updating attestation policy: {}", ExceptionUtils.getStackTrace(e)); return internalErrorResponse(responseParams, response, e); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java index ed0beb47f..9f19d9b92 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryCertificateController.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import dev.sunbirdrc.registry.entities.VerificationRequest; import dev.sunbirdrc.registry.helper.RegistryHelper; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -43,7 +44,7 @@ public ResponseEntity verifyCertificate(@RequestBody VerificationRequest return new ResponseEntity<>(response, HttpStatus.OK); } } catch (Exception e) { - logger.info("Exception occurred while verifying certificate: {}", e.getMessage()); + logger.error("Exception occurred while verifying certificate: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index efaf3cfd1..6ccf8226b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -13,6 +13,7 @@ import dev.sunbirdrc.registry.model.dto.AttestationRequest; import dev.sunbirdrc.registry.util.ClaimRequestClient; import dev.sunbirdrc.registry.util.IDefinitionsManager; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +54,7 @@ public ResponseEntity getAllClaims(@PathVariable String entityName, Page logger.info("Received {} claims", claims.size()); return new ResponseEntity<>(claims, HttpStatus.OK); } catch (Exception e) { - logger.error("Fetching claims failed {}", e.getMessage()); + logger.error("Fetching claims failed {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -66,10 +67,10 @@ public ResponseEntity getClaim(@PathVariable String entityName, @PathVar JsonNode claim = claimRequestClient.getClaim(result.get(entityName).get(0), entityName, claimId); return new ResponseEntity<>(claim, HttpStatus.OK); } catch (HttpClientErrorException | HttpServerErrorException e) { - logger.error("Fetching claim failed {}", e.getMessage()); + logger.error("Fetching claim failed {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(e.getStatusCode()); - } catch (Exception exception) { - logger.info("Exception occurred while fetching claim: {}", exception.getMessage()); + } catch (Exception e) { + logger.error("Exception occurred while fetching claim: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -96,10 +97,10 @@ public ResponseEntity attestClaim( responseParams.setStatus(Response.Status.SUCCESSFUL); return new ResponseEntity<>(responseParams, HttpStatus.OK); - } catch (Exception exception) { - logger.error("Exception : {}", exception.getMessage()); + } catch (Exception e) { + logger.error("Exception : {}", ExceptionUtils.getStackTrace(e)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); + responseParams.setErrmsg(e.getMessage()); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -123,7 +124,7 @@ public ResponseEntity riseAttestation(HttpServletRequest request, @Reque try { registryHelper.authorize(attestationRequest.getEntityName(), attestationRequest.getEntityId(), request); } catch (Exception e) { - logger.error("Unauthorized exception {}", e.getMessage()); + logger.error("Unauthorized exception {}", ExceptionUtils.getStackTrace(e)); return createUnauthorizedExceptionResponse(e); } AttestationPolicy attestationPolicy = registryHelper.getAttestationPolicy(attestationRequest.getEntityName(), attestationRequest.getName()); @@ -145,9 +146,9 @@ public ResponseEntity riseAttestation(HttpServletRequest request, @Reque attestationRequest.setEmailId(emailId); String attestationOSID = registryHelper.triggerAttestation(attestationRequest, attestationPolicy); response.setResult(Collections.singletonMap("attestationOSID", attestationOSID)); - } catch (Exception exception) { - logger.error("Exception occurred while saving attestation data {}", exception.getMessage()); - responseParams.setErrmsg(exception.getMessage()); + } catch (Exception e) { + logger.error("Exception occurred while saving attestation data {}", ExceptionUtils.getStackTrace(e)); + responseParams.setErrmsg(e.getMessage()); response = new Response(Response.API_ID.SEND, HttpStatus.INTERNAL_SERVER_ERROR.toString(), responseParams); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java index 6bdb42acf..eaf0534cd 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryController.java @@ -13,6 +13,7 @@ import dev.sunbirdrc.registry.transform.ITransformer; import dev.sunbirdrc.registry.util.Definition; import dev.sunbirdrc.registry.util.RecordIdentifier; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -61,7 +62,7 @@ public ResponseEntity searchEntity(@RequestHeader HttpHeaders header) responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.searchEntity"); } catch (Exception e) { - logger.error("Exception in controller while searching entities !, {}", e.getMessage()); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -83,12 +84,12 @@ public ResponseEntity deleteEntity() { responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); } catch (UnsupportedOperationException e) { - logger.error("Controller: UnsupportedOperationException while deleting entity !, {}", e.getMessage()); + logger.error("Controller: UnsupportedOperationException while deleting entity !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); } catch (Exception e) { - logger.error("Controller: Exception while deleting entity !, {}", e.getMessage()); + logger.error("Controller: Exception while deleting entity !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg("Meh ! You encountered an error!"); @@ -114,7 +115,7 @@ public ResponseEntity addEntity() { responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.addToExistingEntity"); } catch (Exception e) { - logger.error("Exception in controller while adding entity !, {}", e.getMessage()); + logger.error("Exception in controller while adding entity !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(result); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -147,7 +148,7 @@ public ResponseEntity readEntity(@RequestHeader HttpHeaders header) { response.setResult(resultContent.getData()); logger.info("ReadEntity,{},{}", resultNode.get(apiMessage.getRequest().getEntityType()).get(uuidPropertyName), config); } catch (Exception e) { - logger.error("Read Api Exception occurred , {}", e.getMessage()); + logger.error("Read Api Exception occurred , {}", ExceptionUtils.getStackTrace(e)); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -166,7 +167,7 @@ public ResponseEntity getRegisters(@RequestHeader HttpHeaders header) response.setResult(registryList); logger.info("get registers,{}", registryList); } catch (Exception e) { - logger.error("Read Api Exception occurred , {}", e.getMessage()); + logger.error("Read Api Exception occurred , {}", ExceptionUtils.getStackTrace(e)); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -183,7 +184,7 @@ public ResponseEntity getRegisters(@PathVariable String entity, @Reque response.setResult(definition); logger.info("get registers,{}", entity); } catch (Exception e) { - logger.error("Read Api Exception occurred , {}", e.getMessage()); + logger.error("Read Api Exception occurred , {}", ExceptionUtils.getStackTrace(e)); responseParams.setErrmsg(e.getMessage()); responseParams.setStatus(Response.Status.UNSUCCESSFUL); } @@ -206,7 +207,7 @@ public ResponseEntity updateEntity() { responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.update"); } catch (Exception e) { - logger.error("RegistryController: Exception while updating entity (without id)!, {}", e.getMessage()); + logger.error("RegistryController: Exception while updating entity (without id)!, {}", ExceptionUtils.getStackTrace(e)); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java index b3b8820ee..5a967c91b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java @@ -114,8 +114,13 @@ private ObjectNode generateAPIMethods(Set entities, HttpServletRequest r @GetMapping(value = "/api/docs/{file}.json", produces = "application/json") public ResponseEntity getSwaggerDocImportFiles( @PathVariable String file - ) throws IOException { - JsonNode definitions = refResolver.getResolvedSchema(file, "properties"); + ) { + JsonNode definitions = null; + try { + definitions = refResolver.getResolvedSchema(file, "properties"); + } catch (IOException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } return new ResponseEntity<>(definitions, HttpStatus.OK); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java index 5b47d80c0..4a998d8e6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java @@ -1,6 +1,7 @@ package dev.sunbirdrc.registry.controller; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -25,7 +26,7 @@ public String getTemplate(@PathVariable String fileName) { File file = new ClassPathResource(templatesFolderPath + fileName).getFile(); content = new String(Files.readAllBytes(file.toPath())); } catch (IOException e) { - logger.info("Fetching template failed: {}", e.getMessage()); + logger.info("Fetching template failed: {}", ExceptionUtils.getStackTrace(e)); } return content; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/exception/CustomExceptionHandler.java b/java/registry/src/main/java/dev/sunbirdrc/registry/exception/CustomExceptionHandler.java index 87d19f187..707aa513a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/exception/CustomExceptionHandler.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/exception/CustomExceptionHandler.java @@ -2,6 +2,7 @@ import com.google.gson.Gson; import dev.sunbirdrc.registry.interceptor.handler.BaseResponseHandler; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; @@ -24,7 +25,7 @@ public CustomExceptionHandler(Gson gson) { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { - logger.info("Exception thrown-" + ex.getMessage()); + logger.error("Exception thrown: {}", ExceptionUtils.getStackTrace(ex)); setResponse(response); writeResponseObj(gson, ex.getMessage()); } catch (Exception e) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 4e81261e4..d95f59584 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -646,7 +646,8 @@ private void triggerNextFLowIfExists(PluginResponseMessage pluginResponseMessage updateEntity(updatedNode, userId); } } catch (JsonProcessingException e) { - logger.error("Exception while executing function definition: {} {}, {}", attestationPolicy.getOnComplete(), functionDefinition, e.getMessage()); + logger.error("Exception while executing function definition: {} {}, {}", attestationPolicy.getOnComplete(), functionDefinition, ExceptionUtils.getStackTrace(e)); + throw e; } } else { logger.error("Invalid function name specified for onComplete: {}", attestationPolicy.getOnComplete()); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/IAuditService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/IAuditService.java index 2a954904a..7ac983f92 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/IAuditService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/IAuditService.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.UUID; +import dev.sunbirdrc.registry.exception.AuditFailedException; import org.apache.tinkerpop.gremlin.structure.Transaction; import com.fasterxml.jackson.databind.JsonNode; @@ -23,7 +24,7 @@ public interface IAuditService { * * */ - void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard); + void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) throws AuditFailedException; boolean shouldAudit(String entityType); String isAuditAction(String entityType); @@ -63,7 +64,7 @@ default String getAuditDefinitionName(String entityType, String auditSuffixSepar return entityType; } - default void auditAdd(AuditRecord auditRecord, Shard shard, JsonNode mergedNode){ + default void auditAdd(AuditRecord auditRecord, Shard shard, JsonNode mergedNode) throws AuditFailedException { if(shouldAudit(auditRecord.getEntityType())) { auditRecord.setAction(Constants.AUDIT_ACTION_ADD); JsonNode inputNode = JSONUtil.diffJsonNode(null, mergedNode); @@ -73,7 +74,7 @@ default void auditAdd(AuditRecord auditRecord, Shard shard, JsonNode mergedNode) } } - default void auditUpdate(AuditRecord auditRecord, Shard shard, JsonNode mergedNode, JsonNode readNode){ + default void auditUpdate(AuditRecord auditRecord, Shard shard, JsonNode mergedNode, JsonNode readNode) throws AuditFailedException { if(shouldAudit(auditRecord.getEntityType())) { auditRecord.setAction(Constants.AUDIT_ACTION_UPDATE); JsonNode inputNode = JSONUtil.diffJsonNode(readNode, mergedNode); @@ -83,7 +84,7 @@ default void auditUpdate(AuditRecord auditRecord, Shard shard, JsonNode mergedNo } } - default void auditDelete(AuditRecord auditRecord, Shard shard) { + default void auditDelete(AuditRecord auditRecord, Shard shard) throws AuditFailedException { if(shouldAudit(auditRecord.getEntityType())) { auditRecord.setAction(Constants.AUDIT_ACTION_DELETE); auditRecord.setAuditInfo(createAuditInfo(auditRecord.getAction(), auditRecord.getEntityType())); @@ -92,7 +93,7 @@ default void auditDelete(AuditRecord auditRecord, Shard shard) { } } - default void auditRead(AuditRecord auditRecord, Shard shard) { + default void auditRead(AuditRecord auditRecord, Shard shard) throws AuditFailedException { if(shouldAudit(auditRecord.getEntityType())) { auditRecord.setAction(Constants.AUDIT_ACTION_READ); auditRecord.setAuditInfo(createAuditInfo(auditRecord.getAction(), auditRecord.getEntityType())); @@ -110,8 +111,12 @@ default void auditElasticSearch(AuditRecord auditRecord, List entityType if(shouldAudit(auditRecord.getEntityType())) { auditRecord.setAction(isAuditAction(auditRecord.getEntityType())); auditRecord.setAuditInfo(createAuditInfo(auditRecord.getAction(), auditRecord.getEntityType())); - - doAudit(auditRecord, inputNode, null); + + try { + doAudit(auditRecord, inputNode, null); + } catch (AuditFailedException e) { + throw new RuntimeException(e); + } } }); } @@ -124,8 +129,12 @@ default void auditNativeSearch(AuditRecord auditRecord, Shard shard, List requestBody = new HashMap(){{ - put("templateUrl", finalTemplateUrl); - put("certificate", certificateData.toString()); - put("entityId", entityId); - put("entityName", entityName); - put("entity", entity); - }}; - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", mediaType); - HttpEntity> httpEntity = new HttpEntity<>(requestBody, headers); - return restTemplate.postForObject(certificateUrl, httpEntity, byte[].class); - } catch (Exception e) { - logger.error("Get certificate failed: {}", e.getMessage()); - } - return null; + Map requestBody = new HashMap(){{ + put("templateUrl", finalTemplateUrl); + put("certificate", certificateData.toString()); + put("entityId", entityId); + put("entityName", entityName); + put("entity", entity); + }}; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", mediaType); + HttpEntity> httpEntity = new HttpEntity<>(requestBody, headers); + return restTemplate.postForObject(certificateUrl, httpEntity, byte[].class); } @NotNull @@ -103,7 +99,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), false); } } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the certificate service: {}", ex.getMessage()); + logger.error("RestClientException when checking the health of the certificate service: {}", ExceptionUtils.getStackTrace(ex)); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java index 014493882..9c5d21323 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/EncryptionServiceImpl.java @@ -73,7 +73,7 @@ public String encrypt(Object propertyValue) throws EncryptionException { logger.error("ResourceAccessException while connecting encryption service : {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { - logger.error("Exception in encryption service !: {}", e.getMessage()); + logger.error("Exception in encryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service"); } } @@ -94,10 +94,10 @@ public String decrypt(Object propertyValue) throws EncryptionException { logger.info("Property decrypted successfully !"); return response.getBody(); } catch (ResourceAccessException e) { - logger.error("ResourceAccessException while connecting decryption service : {}", e.getMessage()); + logger.error("ResourceAccessException while connecting decryption service : {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception while connecting encryption service ! "); } catch (Exception e) { - logger.error("Exception in decryption service !: {}", e.getMessage()); + logger.error("Exception in decryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service ! "); } } @@ -123,10 +123,10 @@ public Map encrypt(Map propertyValue) throws Enc return gson.fromJson(response.getBody(), new TypeToken>() { }.getType()); } catch (ResourceAccessException e) { - logger.error("Exception while connecting encryption service : {}", e.getMessage()); + logger.error("Exception while connecting encryption service : {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { - logger.error("Exception in encryption service !: {}", e.getMessage()); + logger.error("Exception in encryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service."); } } @@ -153,10 +153,10 @@ public Map decrypt(Map propertyValue) throws Enc return gson.fromJson(response.getBody(), new TypeToken>() { }.getType()); } catch (ResourceAccessException e) { - logger.error("Exception while connecting decryption service : {}", e.getMessage()); + logger.error("Exception while connecting decryption service : {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception while connecting encryption service ! "); } catch (Exception e) { - logger.error("Exception in decryption service !: {}", e.getMessage()); + logger.error("Exception in decryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service ! "); } } @@ -184,7 +184,7 @@ public ComponentHealthInfo getHealthInfo() { return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, response.getBody()); } } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the encryption service: {}", ex.getMessage()); + logger.error("RestClientException when checking the health of the encryption service: {}", ExceptionUtils.getStackTrace(ex)); return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); } } else { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryAsyncServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryAsyncServiceImpl.java index 9c4bc2fe9..1d23e2f2a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryAsyncServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryAsyncServiceImpl.java @@ -6,6 +6,7 @@ import dev.sunbirdrc.registry.model.dto.CreateEntityMessage; import dev.sunbirdrc.registry.service.RegistryService; import dev.sunbirdrc.registry.sink.shard.Shard; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.slf4j.Logger; @@ -56,8 +57,8 @@ public void onSuccess(SendResult result) { } @Override - public void onFailure(@NotNull Throwable ex) { - logger.error("Unable to send message=[{}] with offset=[{}] due to : {}", message, ex.getMessage(), ex); + public void onFailure(@NotNull Throwable e) { + logger.error("Unable to send message=[{}] due to : {}", message, ExceptionUtils.getStackTrace(e)); } }); return transactionId; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java index ea0039e83..60f0c43c6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/SignatureServiceImpl.java @@ -6,6 +6,7 @@ import dev.sunbirdrc.registry.exception.SignatureException; import dev.sunbirdrc.registry.service.FileStorageService; import dev.sunbirdrc.registry.service.SignatureService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -65,9 +66,9 @@ public ComponentHealthInfo getHealthInfo() { } else { return new ComponentHealthInfo(getServiceName(), false); } - } catch (RestClientException ex) { - logger.error("RestClientException when checking the health of the Sunbird signature service: {}", ex.getMessage()); - return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, ex.getMessage()); + } catch (RestClientException e) { + logger.error("RestClientException when checking the health of the signature service: {}", ExceptionUtils.getStackTrace(e)); + return new ComponentHealthInfo(getServiceName(), false, CONNECTION_FAILURE, e.getMessage()); } } else { return new ComponentHealthInfo(getServiceName(), true, "SIGNATURE_ENABLED", "false"); @@ -98,14 +99,14 @@ public Object sign(Map propertyValue) response = retryRestTemplate.postForEntity(signURL, propertyValue); result = objectMapper.readTree(response.getBody()); logger.info("Successfully generated signed credentials"); - } catch (SignatureException.UnreachableException ex) { - logger.error("SignatureException when signing: {}", ex.getMessage()); - throw ex; - } catch (RestClientException ex) { - logger.error("RestClientException when signing: {}", ex.getMessage()); - throw new SignatureException().new UnreachableException(ex.getMessage()); + } catch (SignatureException.UnreachableException e) { + logger.error("SignatureException when signing: {}", ExceptionUtils.getStackTrace(e)); + throw e; + } catch (RestClientException e) { + logger.error("RestClientException when signing: {}", ExceptionUtils.getStackTrace(e)); + throw new SignatureException().new UnreachableException(e.getMessage()); } catch (Exception e) { - logger.error("SignatureException when signing: {}", e.getMessage()); + logger.error("SignatureException when signing: {}", ExceptionUtils.getStackTrace(e)); throw new SignatureException().new CreationException(e.getMessage()); } return result; @@ -127,11 +128,11 @@ public boolean verify(Object propertyValue) response = retryRestTemplate.postForEntity(verifyURL, propertyValue); JsonNode resultNode = objectMapper.readTree(response.getBody()); result = resultNode.get("verified").asBoolean(); - } catch (RestClientException ex) { - logger.error("RestClientException when verifying: {}", ex.getMessage()); - throw new SignatureException().new UnreachableException(ex.getMessage()); + } catch (RestClientException e) { + logger.error("RestClientException when verifying: {}", ExceptionUtils.getStackTrace(e)); + throw new SignatureException().new UnreachableException(e.getMessage()); } catch (Exception e) { - logger.error("RestClientException when verifying: {}", e.getMessage()); + logger.error("RestClientException when verifying: {}", ExceptionUtils.getStackTrace(e)); throw new SignatureException().new VerificationException(e.getMessage()); } logger.debug("verify method ends with value {}",result); @@ -153,11 +154,11 @@ public String getKey(String keyId) try { response = retryRestTemplate.getForEntity(keysURL + "/" + keyId); result = response.getBody(); - } catch (RestClientException ex) { - logger.error("RestClientException when verifying: {}", ex.getMessage()); - throw new SignatureException().new UnreachableException(ex.getMessage()); + } catch (RestClientException e) { + logger.error("RestClientException when verifying: {}", ExceptionUtils.getStackTrace(e)); + throw new SignatureException().new UnreachableException(e.getMessage()); } catch (Exception e) { - logger.error("RestClientException when verifying: {}", e.getMessage()); + logger.error("RestClientException when verifying: {}", ExceptionUtils.getStackTrace(e)); throw new SignatureException().new KeyNotFoundException(keyId); } logger.debug("getKey method ends with value {}",result); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java index 168255bf2..a97f80790 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PrivateField.java @@ -6,6 +6,7 @@ import dev.sunbirdrc.registry.exception.EncryptionException; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.service.EncryptionService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -125,7 +126,7 @@ protected JsonNode process(JsonNode jsonNode, String rootFieldName, String field processArray((ArrayNode) entryValue, tempFieldName, entry.getKey()); } } catch (EncryptionException e) { - logger.info("Exception occurred in PrivateField: {}", e.getMessage()); + logger.error("Exception occurred in PrivateField: {}", ExceptionUtils.getStackTrace(e)); } } return jsonNode; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java index e2dc55898..98d5966e9 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/RefResolver.java @@ -25,7 +25,7 @@ public RefResolver(IDefinitionsManager definitionsManager) { this.definitionsManager = definitionsManager; } - public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) { + public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) throws IOException { Definition definition = definitionsManager.getDefinition(rootDefinitionName); String content = definition.getContent(); try { @@ -35,9 +35,9 @@ public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) logger.info(JSONUtil.convertObjectJsonString(resolvedDefinitions)); return resolvedDefinitions; } catch (IOException e) { - logger.info("Failed resolving schema definitions for {}: {}", rootDefinitionName, e.getMessage()); + logger.error("Failed resolving schema definitions for {}: {}", rootDefinitionName, ExceptionUtils.getStackTrace(e)); + throw e; } - return null; } public JsonNode resolveDefinitions(String currentDefinitionName, JsonNode currentNode) { diff --git a/java/sunbird-actor/pom.xml b/java/sunbird-actor/pom.xml index 3859f5bd7..81f558dc7 100644 --- a/java/sunbird-actor/pom.xml +++ b/java/sunbird-actor/pom.xml @@ -30,6 +30,11 @@ protobuf-java 3.6.1 + + org.apache.commons + commons-lang3 + 3.0 + diff --git a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java index 741677df6..1643e4761 100644 --- a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java +++ b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/BaseActor.java @@ -5,6 +5,7 @@ import akka.event.LoggingAdapter; import com.google.protobuf.ByteString; import com.google.protobuf.Value; +import org.apache.commons.lang3.exception.ExceptionUtils; /** * An abstract actor @@ -94,12 +95,12 @@ public void onReceive(Object genericMessage) throws Throwable { tellToSource(response); } } catch (Exception e) { - logger.info("Exception occurred while Act upon the message {}", e.getMessage()); + logger.error("Exception occurred while Act upon the message {}", ExceptionUtils.getStackTrace(e)); } } } catch (ClassCastException e) { - logger.info("Ignoring message because it is not in expected format {}", genericMessage.toString()); + logger.error("Ignoring message because it is not in expected format {}", genericMessage.toString()); } } } diff --git a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java index d3f2850d3..1fe2524bf 100644 --- a/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java +++ b/java/sunbird-actor/src/main/java/org/sunbird/akka/core/Router.java @@ -5,6 +5,7 @@ import akka.dispatch.OnComplete; import akka.pattern.Patterns; import akka.util.Timeout; +import org.apache.commons.lang3.exception.ExceptionUtils; import scala.concurrent.ExecutionContext; import scala.concurrent.Future; import scala.concurrent.duration.Duration; @@ -125,7 +126,7 @@ private boolean route(ActorSelection router, ActorRef ref, MessageProtos.Message public void onComplete(Throwable failure, Object result) { if (failure != null) { // We got a failure, handle it here - logger.error("Exception occurred: {}", failure.getMessage()); + logger.error("Exception occurred: {}", ExceptionUtils.getStackTrace(failure)); } onResponse(message, result, failure); } diff --git a/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java b/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java index 6010de8ff..e724f314e 100644 --- a/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java +++ b/java/validators/json/jsonschema/src/main/java/dev/sunbirdrc/validators/json/jsonschema/JsonValidationServiceImpl.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import dev.sunbirdrc.registry.middleware.MiddlewareHaltException; import dev.sunbirdrc.validators.IValidate; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; @@ -52,8 +53,8 @@ private Schema getEntitySchema(String entityType) throws MiddlewareHaltException } else { return null; } - } catch (Exception ioe) { - logger.info("can't validate, {}: schema has a problem!, {}", entityType, ioe.getMessage()); + } catch (Exception e) { + logger.error("can't validate, {}: schema has a problem!, {}", entityType, ExceptionUtils.getStackTrace(e)); throw new MiddlewareHaltException("can't validate, "+ entityType + ": schema has a problem!"); } return schema; diff --git a/test_environments/test2.env b/test_environments/test_with_asyncCreate_events_notifications.env similarity index 100% rename from test_environments/test2.env rename to test_environments/test_with_asyncCreate_events_notifications.env diff --git a/test_environments/test1.env b/test_environments/test_with_distributedDefManager_nativeSearch.env similarity index 100% rename from test_environments/test1.env rename to test_environments/test_with_distributedDefManager_nativeSearch.env From 488bdef3cfdb29c55034015406fa90d71e6c0b6b Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Thu, 14 Sep 2023 12:45:04 +0530 Subject: [PATCH 25/28] throwing notify exception --- .../src/main/java/in/divoc/api/authenticator/NotifyService.java | 1 + 1 file changed, 1 insertion(+) diff --git a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java index 54867bd78..901dd18f8 100644 --- a/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java +++ b/deps/keycloak-mobile-number-login-spi/src/main/java/in/divoc/api/authenticator/NotifyService.java @@ -47,6 +47,7 @@ public void notify(String to, String otp) throws IOException { } } catch (IOException e) { logger.error("Exception occurred while notifying: {}", ExceptionUtils.getStackTrace(e)); + throw e; } } From 65eb66c0853635010da2d205b1069f3664cfecd0 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Thu, 14 Sep 2023 14:15:26 +0530 Subject: [PATCH 26/28] reverted from error messages to stack trace --- .../dev/sunbirdrc/views/ViewTransformerTest.java | 13 +++++++++---- scripts/index.js | 2 +- .../src/routes/certificate_controller.js | 2 +- services/certificate-signer/main.js | 2 +- services/metrics/swagger_gen/restapi/server.go | 3 +-- services/public-key-service/main.js | 2 +- .../src/components/VerifyCertificate/index.js | 2 +- 7 files changed, 15 insertions(+), 11 deletions(-) diff --git a/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java b/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java index e0b052e83..0ae342f0e 100644 --- a/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java +++ b/java/view-templates/src/test/java/dev/sunbirdrc/views/ViewTransformerTest.java @@ -11,10 +11,16 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; + +import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ViewTransformerTest { + private static final Logger logger = LoggerFactory.getLogger(ViewTransformerTest.class); + private ViewTransformer transformer = new ViewTransformer(); @Test @@ -73,10 +79,9 @@ private static String readFileContent(String fileName) { } return result.toString(StandardCharsets.UTF_8.name()); - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - - } catch (IOException e) {} + } catch (IOException e) { + logger.error(ExceptionUtils.getStackTrace(e)); + } return null; } diff --git a/scripts/index.js b/scripts/index.js index 6450b9206..9a926e5bf 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -237,7 +237,7 @@ var execute_tasks = function (tasks, fileName, cb) { console.log("Executed tasks") cb(null) } else { - console.error(err?.message) + console.error(err) console.log("One or more errors occurred.") cb(err) } diff --git a/services/certificate-api/src/routes/certificate_controller.js b/services/certificate-api/src/routes/certificate_controller.js index 112063fee..eaf1b35b5 100644 --- a/services/certificate-api/src/routes/certificate_controller.js +++ b/services/certificate-api/src/routes/certificate_controller.js @@ -301,7 +301,7 @@ async function createPDF(certificate) { return pdfBuffer } catch (err) { console.log("Failed while creating pdf") - console.log(err?.message) + console.log(err) } } diff --git a/services/certificate-signer/main.js b/services/certificate-signer/main.js index b28059922..ec5f9886a 100644 --- a/services/certificate-signer/main.js +++ b/services/certificate-signer/main.js @@ -37,7 +37,7 @@ const server = http.createServer(async (req, res) => { } console.timeEnd(req.url) } catch (e) { - console.error(e?.message) + console.error(e) res.statusCode = e["code"] || 500; res.end(`{"error": "${http.STATUS_CODES[res.statusCode]}", "message": ${e.message}}`) } diff --git a/services/metrics/swagger_gen/restapi/server.go b/services/metrics/swagger_gen/restapi/server.go index d5684b995..e20ba7819 100644 --- a/services/metrics/swagger_gen/restapi/server.go +++ b/services/metrics/swagger_gen/restapi/server.go @@ -8,7 +8,6 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" "log" "net" "net/http" @@ -274,7 +273,7 @@ func (s *Server) Serve() (err error) { if s.TLSCACertificate != "" { // include specified CA certificate - caCert, caCertErr := ioutil.ReadFile(string(s.TLSCACertificate)) + caCert, caCertErr := os.ReadFile(string(s.TLSCACertificate)) if caCertErr != nil { return caCertErr } diff --git a/services/public-key-service/main.js b/services/public-key-service/main.js index 7dc4e3f04..b7e4b526c 100644 --- a/services/public-key-service/main.js +++ b/services/public-key-service/main.js @@ -37,7 +37,7 @@ const server = http.createServer(async (req, res) => { console.timeEnd(req.url) } catch (e) { - console.error(e?.message) + console.error(e) res.statusCode = e["code"] || 500; res.end(`{"error": "${http.STATUS_CODES[res.statusCode]}", "message": ${e.message}}`) } diff --git a/services/verification-ui/src/components/VerifyCertificate/index.js b/services/verification-ui/src/components/VerifyCertificate/index.js index 8927e5907..ef39c739e 100644 --- a/services/verification-ui/src/components/VerifyCertificate/index.js +++ b/services/verification-ui/src/components/VerifyCertificate/index.js @@ -29,7 +29,7 @@ export const VerifyCertificate = () => { } }; const handleError = err => { - console.error(err?.message) + console.error(err) }; return (
From ffbfcdafbb0cbfe19a065cfc195a6935f9574d54 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Fri, 15 Sep 2023 10:46:35 +0530 Subject: [PATCH 27/28] fixed error messages for golang --- .../java/dev/sunbirdrc/registry/app/AppStartupRunner.java | 1 - scripts/index.js | 4 ++-- services/metrics/cron/cron.go | 4 ++-- services/notification-service/pkg/services/sms_service.go | 4 +--- 4 files changed, 5 insertions(+), 8 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java index 95d8eda63..24e163c3f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java @@ -22,6 +22,5 @@ public void run(ApplicationArguments args) throws Exception { logger.info("On Boot starts loading: parent vertex and shard records"); entityParenter.ensureKnownParenters(); entityParenter.loadDefinitionIndex(); - entityParenter.ensureIndexExists(); } } diff --git a/scripts/index.js b/scripts/index.js index 9a926e5bf..221f323d2 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -36,7 +36,7 @@ var invoke_add = function (nIter, payload, callback) { var apiResponse = JSON.parse(body) if (err) { console.error(err?.message) - console.log(" error for " + payload) + console.error(" error for " + payload) callback(err) } else { var responseErr = apiResponse @@ -292,7 +292,7 @@ function populateData(cb) { populateData(function (err, result) { if (err) { return (err); - console.log("Errorrrrr==>", err); + console.error("Errorrrrr==>", err); } console.log("Finished successfully"); return result; diff --git a/services/metrics/cron/cron.go b/services/metrics/cron/cron.go index 43f688be7..670d527ff 100644 --- a/services/metrics/cron/cron.go +++ b/services/metrics/cron/cron.go @@ -50,13 +50,13 @@ func (cron *Cron) SaveWeeklyMetrics() { aggregate := (*cron.db).GetAggregates(clauses) bytes, err := json.Marshal(aggregate) if err != nil { - log.Infof("Error in marshalling : %v", err) + log.Errorf("Error in marshalling : %v", err) } ctx := context.Background() log.Infof(string(bytes)) err = cron.redisClient.Set(ctx, "weeklyUpdates", string(bytes), 0).Err() if err != nil { - log.Infof("Error in saving to redis : %v", err) + log.Errorf("Error in saving to redis : %v", err) } log.Info("Saved to redis") } diff --git a/services/notification-service/pkg/services/sms_service.go b/services/notification-service/pkg/services/sms_service.go index 837402eeb..9051db9f3 100644 --- a/services/notification-service/pkg/services/sms_service.go +++ b/services/notification-service/pkg/services/sms_service.go @@ -48,9 +48,7 @@ func GetSmsRequestPayload(message string, mobileNumber string) map[string]interf log.Infof("success") return smsRequest } else { - log.Infof("error") - log.Error(err) + log.Errorf("error: %v", err) } - log.Infof("error") return nil } From 43f260d251cd3ba89fa5d0e4b1b48ffa6de058b2 Mon Sep 17 00:00:00 2001 From: Holash Chand Date: Fri, 15 Sep 2023 11:11:48 +0530 Subject: [PATCH 28/28] adding ensure index at startup back --- .../main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java | 1 + 1 file changed, 1 insertion(+) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java index 24e163c3f..65d442f56 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/AppStartupRunner.java @@ -22,5 +22,6 @@ public void run(ApplicationArguments args) throws Exception { logger.info("On Boot starts loading: parent vertex and shard records"); entityParenter.ensureKnownParenters(); entityParenter.loadDefinitionIndex(); + entityParenter.ensureIndexExists(); } }