diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index d5789c7cc..843718b6a 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -22,6 +22,12 @@ jobs: cache: 'maven' - name: Set up properties run: sh configure-dependencies.sh +# # 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/Makefile b/Makefile index e27716e2a..f321d634f 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/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 @@ -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/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/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/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..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 @@ -1,7 +1,9 @@ package in.divoc.api.authenticator; -import okhttp3.*; -import org.jboss.logging.Logger; + +import org.apache.commons.lang.exception.ExceptionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; @@ -12,7 +14,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 +46,8 @@ 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: {}", ExceptionUtils.getStackTrace(e)); + throw e; } } diff --git a/docker-compose.yml b/docker-compose.yml index 4c520d8cf..4e5991154 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" @@ -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 @@ -54,15 +55,18 @@ 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=${CLAIMS_ENABLED-false} - claims_url=http://claim-ms:8082 + - 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 - - signature_enabled=true + - 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 - sunbird_keycloak_user_set_password=true + - filestorage_enabled=false - filestorage_connection_url=http://file-storage:9000 - filestorage_access_key=admin - filestorage_secret_key=12345678 @@ -281,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/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/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/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimsAuthorizer.java index 2daf26eaa..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(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 56b22f339..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); + 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); + 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); + 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); + 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/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 218fd13d2..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,7 +2,10 @@ 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; import java.io.IOException; import java.util.ArrayList; @@ -11,6 +14,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 +48,8 @@ public void shouldReturnTrueForValidExpression() throws IOException { try { resolve = conditionResolverService.resolve(getStudentJsonNode(), requester, condition, attributes); } catch (IOException e) { - e.printStackTrace(); + 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 0b272db24..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,7 +5,10 @@ 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; import java.io.*; import java.nio.charset.StandardCharsets; @@ -15,6 +18,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"; @@ -119,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); @@ -131,14 +135,10 @@ private String getContent(String fileName) { } return result.toString(StandardCharsets.UTF_8.name()); - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - + logger.error("Exception occurred: {}", ExceptionUtils.getStackTrace(e)); + throw e; } - return null; } @Test 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/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..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,9 +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.printStackTrace(); + } 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."); @@ -93,9 +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); - exception.printStackTrace(); + } 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 f5b02c837..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); + 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 c993281e5..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,9 +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.printStackTrace(); + } 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 e1b9ff319..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,9 +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.printStackTrace(); + } 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); @@ -103,9 +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.printStackTrace(); + } 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); @@ -131,9 +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.printStackTrace(); + } 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"); @@ -175,9 +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.printStackTrace(); + } 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"); @@ -199,9 +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.printStackTrace(); + } 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 4df2e7ae3..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; @@ -38,11 +39,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 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 dfdf3b172..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); + } 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); + } catch (Exception e) { + logger.error("ERROR in closing stream: {}", ExceptionUtils.getStackTrace(e)); } } } 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..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,6 +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(); + entityParenter.ensureIndexExists(); } } 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..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; @@ -40,6 +41,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; @@ -61,6 +63,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 @@ -352,10 +358,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.error("Exception occurred while adding validation interceptor: {}", ExceptionUtils.getStackTrace(e)); } } } @@ -413,6 +417,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(); @@ -424,11 +430,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/config/MinioClientConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/MinioClientConfig.java index 2da1c2252..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,13 +3,16 @@ 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; +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); @@ -36,7 +39,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: {}", ExceptionUtils.getStackTrace(e)); } 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..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); + 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 f5e6d6ba5..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,12 +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); + 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) { - e.printStackTrace(); + logger.error("Exception occurred while loading schema from db: {}", ExceptionUtils.getStackTrace(e)); + } catch (Exception e) { + 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 3ccda1167..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; @@ -47,14 +48,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.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 a937650be..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,10 @@ 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; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -15,7 +19,9 @@ // TODO: Get should be viewed by both attestor and reviewer @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; @@ -33,7 +39,7 @@ public ResponseEntity save(@RequestParam MultipartFile[] file try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + logger.error("Authorizing entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.saveAndFetchFileNames(files, httpServletRequest.getRequestURI()); @@ -49,7 +55,7 @@ public ResponseEntity deleteMultipleFiles(@PathVariable Strin try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + logger.error("Authorizing entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity(HttpStatus.FORBIDDEN); } DocumentsResponse documentsResponse = fileStorageService.deleteFiles(files); @@ -65,7 +71,7 @@ public ResponseEntity deleteAFile(@PathVariable String entity, try { registryHelper.authorize(entity, entityId, httpServletRequest); } catch (Exception e) { - e.printStackTrace(); + 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 d515d4714..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); + 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); + 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); + 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); + 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); + 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 dceb5d668..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,9 @@ 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; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -14,7 +17,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 +44,7 @@ public ResponseEntity verifyCertificate(@RequestBody VerificationRequest return new ResponseEntity<>(response, HttpStatus.OK); } } catch (Exception e) { + 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 edad915bf..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,9 +13,11 @@ 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; +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 +31,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; @@ -51,8 +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()); - e.printStackTrace(); + logger.error("Fetching claims failed {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -65,11 +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()); - e.printStackTrace(); + logger.error("Fetching claim failed {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(e.getStatusCode()); - } catch (Exception exception) { - exception.printStackTrace(); + } 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,10 +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()); - exception.printStackTrace(); - 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 aaa24997d..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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 5b29c2af9..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 @@ -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; @@ -27,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; @@ -48,6 +50,7 @@ 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; @RestController @@ -56,10 +59,16 @@ 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; + @Value("${certificate.enabled}") + private boolean certificateEnabled; + @Autowired(required = false) private ICertificateService certificateService; - @Autowired + @Value("${filestorage.enabled}") + private boolean fileStorageEnabled; + @Autowired(required = false) private FileStorageService fileStorageService; @Autowired @@ -171,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); + 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); @@ -207,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); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -262,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); + 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); @@ -315,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); + logger.error("Exception in controller while adding entity !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(result); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -465,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); + logger.error("Error in partner api access: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -489,8 +498,8 @@ private ArrayList getConsentFields(HttpServletRequest request) { fields.add(key.toString()); } } - } catch (Exception ex) { - logger.error("Error while extracting other claims", ex); + } catch (Exception e) { + logger.error("Error while extracting other claims, {}", ExceptionUtils.getStackTrace(e)); } return fields; } @@ -503,6 +512,9 @@ public ResponseEntity getEntityType(@PathVariable String entityName, @RequestHeader(required = false) String viewTemplateId) { ResponseParams responseParams = new ResponseParams(); Response response ; + if (!certificateEnabled) { + return ServiceNotEnabledResponse("Certificate service",null, responseParams); + } if (registryHelper.doesEntityOperationRequireAuthorization(entityName) && securityEnabled) { try { @@ -533,14 +545,14 @@ public ResponseEntity getEntityType(@PathVariable String entityName, getTemplateUrlFromRequest(request, entityName), JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) ), HttpStatus.OK); - } catch (Exception exception) { - exception.printStackTrace(); + } catch (Exception e) { + logger.error("Exception occurred while producing entity certificate: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } - 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,12 +561,17 @@ 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); + logger.error("Exception while parsing certificate templates DID urls, {}", ExceptionUtils.getStackTrace(e)); return null; } } @@ -609,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); + 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); @@ -669,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); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -701,7 +718,7 @@ public ResponseEntity getEntityForAttestation( return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { - e.printStackTrace(); + logger.error("Fetching attestation properties for entity failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @@ -756,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()); - exception.printStackTrace(); + responseParams.setErrmsg(e.getMessage()); + logger.info("Exception occurred which fetching a system property: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -785,10 +802,14 @@ public ResponseEntity updateAttestationProperty( responseParams.setStatus(Response.Status.SUCCESSFUL); responseParams.setResultList(Collections.singletonList("response")); return new ResponseEntity<>(responseParams, HttpStatus.OK); - } catch (Exception exception) { + } catch (UnreachableException ex) { + responseParams.setErrmsg(ex.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(responseParams, HttpStatus.SERVICE_UNAVAILABLE); + } catch (Exception e) { responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - exception.printStackTrace(); + responseParams.setErrmsg(e.getMessage()); + logger.error("Exception occurred while updating attestation: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -798,6 +819,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 ServiceNotEnabledResponse("Signature service", response, responseParams); + } try { checkEntityNameInDefinitionManager(entityName); JsonNode result = registryHelper.getRequestedUserDetails(request, entityName); @@ -815,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); + logger.error("Exception in controller while searching entities !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -828,6 +852,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 (!certificateEnabled) { + return ServiceNotEnabledResponse("Certificate service", null, responseParams); + } try { checkEntityNameInDefinitionManager(entityName); String readerUserId = getUserId(entityName, request); @@ -851,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) { - e.printStackTrace(); + logger.info("Fetching attestation certificate failed: {}", ExceptionUtils.getStackTrace(e)); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @@ -894,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); + 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/RegistrySwaggerController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistrySwaggerController.java index 599d4896e..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 @@ -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); @@ -104,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); } @@ -261,4 +276,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/controller/RegistryTemplateController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryTemplateController.java index 4c2afbdf8..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,9 @@ 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; import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.*; @@ -11,6 +14,7 @@ @RestController public class RegistryTemplateController{ + private static final Logger logger = LoggerFactory.getLogger(RegistryTemplateController.class); @Value("${certificate.templateFolderPath}") private String templatesFolderPath; @@ -22,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) { - e.printStackTrace(); + logger.info("Fetching template failed: {}", ExceptionUtils.getStackTrace(e)); } 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 4df846a47..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 @@ -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; @@ -20,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; @@ -49,7 +51,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 +84,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(); @@ -95,7 +101,7 @@ public ResponseEntity generateSignature(HttpServletRequest requestMode responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in generating signature", e); + logger.error("Error in generating signature, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.SIGN_ERROR_MESSAGE); @@ -111,7 +117,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(); @@ -166,7 +174,7 @@ public ResponseEntity verifySignature(HttpServletRequest request) { responseParams.setErrmsg(""); } } catch (Exception e) { - logger.error("Error in verifying signature", e); + logger.error("Error in verifying signature, {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.VERIFY_SIGN_ERROR_MESSAGE); @@ -181,7 +189,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); @@ -189,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); + logger.error("Error in getting key , {}", ExceptionUtils.getStackTrace(e)); response.setResult(null); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(Constants.KEY_RETRIEVE_ERROR_MESSAGE); @@ -206,20 +216,23 @@ 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); 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!, {}", ExceptionUtils.getStackTrace(e)); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRD_SIGNATURE_SERVICE_NAME, 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); } @@ -243,9 +256,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!, {}", ExceptionUtils.getStackTrace(e)); HealthCheckResponse healthCheckResult = new HealthCheckResponse(Constants.SUNBIRDRC_REGISTRY_API, false, null); response.setResult(JSONUtil.convertObjectJsonMap(healthCheckResult)); @@ -271,8 +284,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 !, {}", ExceptionUtils.getStackTrace(e)); response.setResult(""); responseParams.setStatus(Response.Status.UNSUCCESSFUL); responseParams.setErrmsg(e.getMessage()); @@ -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/dao/SearchDaoImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/SearchDaoImpl.java index 74344b07d..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,16 +12,21 @@ 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; 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 +174,7 @@ private JsonNode getResult(Graph graph, GraphTraversal resultTraversal, GraphTra try { answer = registryDao.getEntity(graph, v, configurator, expandInternal); } catch (Exception e) { - e.printStackTrace(); + logger.error("Exception occurred while searching entity: {}", ExceptionUtils.getStackTrace(e)); } result.add(answer); } 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/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/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); + } +} 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..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,9 +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) { - e1.printStackTrace(); - logger.error(e1.getLocalizedMessage()); + } catch (Exception e) { + logger.error(ExceptionUtils.getStackTrace(e)); } } @@ -48,8 +48,7 @@ public String getDomain() { try { frameNode = mapper.readTree(getContent()); } catch (IOException e) { - e.printStackTrace(); - 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/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/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..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 @@ -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; @@ -45,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; @@ -54,6 +56,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; @@ -91,7 +95,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; @@ -127,7 +131,9 @@ public class RegistryHelper { @Autowired private DBConnectionInfoMgr dbConnectionInfoMgr; - @Autowired + @Value("${encryption.enabled}") + private boolean encryptionEnabled; + @Autowired(required = false) private DecryptionHelper decryptionHelper; @Autowired @@ -136,7 +142,9 @@ public class RegistryHelper { @Autowired private ObjectMapper objectMapper; - @Autowired + @Value("${filestorage.enabled}") + private boolean fileStorageEnabled; + @Autowired(required = false) private FileStorageService fileStorageService; @Value("${database.uuidPropertyName}") @@ -167,7 +175,7 @@ public class RegistryHelper { @Autowired private EntityTypeHandler entityTypeHandler; - @Autowired + @Autowired(required = false) private SignatureService signatureService; @Autowired @@ -200,13 +208,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; } @@ -250,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); + logger.error("Exception in controller while adding entity !, {}", ExceptionUtils.getStackTrace(e)); throw new Exception(e); } return recordId.toString(); @@ -295,6 +303,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); @@ -375,7 +386,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"; } @@ -386,7 +397,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 { @@ -431,8 +442,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) { @@ -443,7 +457,7 @@ private void updateGetFileUrl(JsonNode additionalInput) { } catch (ServerException | InternalException | XmlParserException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | IOException | ErrorResponseException | InsufficientDataException e) { - e.printStackTrace(); + logger.error("Fetching signed file url failed: {}", ExceptionUtils.getStackTrace(e)); } } ((ObjectNode)additionalInput).replace(FILE_URL, signedUrls); @@ -570,6 +584,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, @@ -615,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); + logger.error("Next level attestation policy not found: {}", ExceptionUtils.getStackTrace(e)); } } else if (attestationPolicy.getCompletionType() == FlowType.FUNCTION) { FunctionDefinition functionDefinition = definitionsManager.getDefinition(sourceEntity).getOsSchemaConfiguration() @@ -629,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); + 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()); @@ -656,6 +674,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(), @@ -663,8 +684,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: {}", ExceptionUtils.getStackTrace(e)); } fileUris.add(propertyURI); }); @@ -806,7 +826,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: {}", ExceptionUtils.getStackTrace(e)); } } JsonNode response = readEntity(userIdFromRequest, entityName, entityId, false, null, false); @@ -901,7 +921,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); @@ -1024,7 +1044,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; } @@ -1062,7 +1082,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: {}", ExceptionUtils.getStackTrace(e)); return Collections.emptyList(); } } @@ -1144,7 +1164,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) { @@ -1215,4 +1235,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/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/ElasticReadService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticReadService.java index a1ed5bc0b..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 @@ -1,15 +1,14 @@ 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.apache.commons.lang3.exception.ExceptionUtils; 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 +30,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); @@ -62,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); + 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 726c66d9d..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 @@ -1,13 +1,14 @@ package dev.sunbirdrc.registry.service; import java.io.IOException; -import java.util.ArrayList; 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; 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 +30,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); @@ -84,7 +86,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: {}", ExceptionUtils.getStackTrace(e)); } } @@ -92,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); + logger.error("Exception while auditing: {}", ExceptionUtils.getStackTrace(e)); } return resultNode; 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/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index a2541025b..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,11 +9,13 @@ 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; import org.slf4j.LoggerFactory; 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.Service; @@ -32,6 +34,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_FILE_STORAGE_SERVICE_NAME; @Service +@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; @@ -61,8 +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.printStackTrace(); + logger.error("Error has occurred while trying to save the file {}: {}", fileName, ExceptionUtils.getStackTrace(e)); } } return documentsResponse; @@ -88,8 +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()); - e.printStackTrace(); + logger.error("Error has occurred while fetching the delete error result {}", ExceptionUtils.getStackTrace(e)); } } return documentsResponse; @@ -106,8 +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()); - e.printStackTrace(); + logger.error("Error has occurred while fetching the document {} {}", objectName, ExceptionUtils.getStackTrace(e)); } return bytes; } @@ -118,7 +118,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/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 0); } catch (Exception e) { - logger.error("Kafka connection exception,", e); + 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 fdf00989e..92db600d2 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); + logger.error("search operation failed: {}", ExceptionUtils.getStackTrace(e)); } finally { continueSearch = !isSpecificSearch; } @@ -136,7 +137,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: {}", ExceptionUtils.getStackTrace(e)); } } 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/SignatureHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/SignatureHelper.java index 4bae26ecd..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 @@ -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; 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..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(), e); + 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/AuditDBImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/AuditDBImpl.java index 7892c603d..c36558b10 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 @@ -2,10 +2,12 @@ import java.io.IOException; +import org.apache.commons.lang3.exception.ExceptionUtils; 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.ConditionalOnExpression; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @@ -14,16 +16,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); @@ -59,10 +59,10 @@ public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) { JsonNode rootNode = convertAuditRecordToJson(auditRecord, entityType); auditToDB(rootNode, entityType, shard); - } catch (AuditFailedException ae) { - logger.error("Error in saving audit info: {}", ae); + } catch (AuditFailedException e) { + logger.error("Error in saving audit info: {}", ExceptionUtils.getStackTrace(e)); } catch (Exception e) { - logger.error("Generic error in saving audit info : {}", e); + logger.error("Generic error in saving audit info : {}", ExceptionUtils.getStackTrace(e)); } logger.debug("doAudit ends"); } 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..cc1950492 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 @@ -1,5 +1,6 @@ package dev.sunbirdrc.registry.service.impl; +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; @@ -59,8 +60,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 : {}", ExceptionUtils.getStackTrace(e)); throw new AuditFailedException("Audit failed : " + e.getMessage()); } finally { if (tx != null) { 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..495bb790a 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 @@ -1,8 +1,10 @@ package dev.sunbirdrc.registry.service.impl; +import dev.sunbirdrc.registry.exception.AuditFailedException; +import org.apache.commons.lang3.exception.ExceptionUtils; 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 +18,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); @@ -25,7 +28,7 @@ public class AuditFileImpl extends AuditServiceImpl { * This is starting of audit in the application, audit details of read, add, update, delete and search activities */ @Override - public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) { + public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) throws AuditFailedException { logger.debug("doAudit started"); try { // If the audit is stored as file, fetchAudit from audit entity will not come to this point. @@ -34,7 +37,8 @@ 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 : {}", ExceptionUtils.getStackTrace(e)); + throw new AuditFailedException("Audit failed: " + 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..dff4264c4 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,8 @@ import java.util.Arrays; import java.util.List; +import dev.sunbirdrc.registry.exception.AuditFailedException; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -107,7 +109,7 @@ public String isAuditAction(String entityType) { } @Override - public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) { + public void doAudit(AuditRecord auditRecord, JsonNode inputNode, Shard shard) throws AuditFailedException { auditProviderFactory.getAuditService(auditFrameStore).doAudit(auditRecord, inputNode, shard); } @@ -165,7 +167,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 : {}", ExceptionUtils.getStackTrace(e)); } 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 09ba766f7..ab69d457c 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 @@ -4,10 +4,12 @@ import dev.sunbirdrc.pojos.ComponentHealthInfo; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.service.ICertificateService; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; 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 +27,7 @@ import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_CERTIFICATE_SERVICE_NAME; @Component +@ConditionalOnProperty(name = "certificate.enabled", havingValue = "true") public class CertificateServiceImpl implements ICertificateService { private final String templateBaseUrl; private final String certificateUrl; @@ -47,25 +50,20 @@ public CertificateServiceImpl(@Value("${certificate.templateBaseUrl}") String te } @Override - public Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity) { - try { - String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl); + public Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity) throws RestClientException { + String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl); - 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); - } catch (Exception e) { - logger.error("Get certificate failed", e); - } - 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 @@ -101,7 +99,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: {}", 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 0bd5ade2d..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 @@ -6,10 +6,12 @@ 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; 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 +30,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 +44,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; @@ -67,10 +70,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 : {}", ExceptionUtils.getStackTrace(e)); + throw new EncryptionException("Exception while connecting encryption service! "); } catch (Exception e) { - logger.error("Exception in encryption service !: ", e); + logger.error("Exception in encryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service"); } } @@ -91,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 dcryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service ! "); + 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); + logger.error("Exception in decryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service ! "); } } @@ -120,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 enryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service! "); + 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 servie !: ", e); + logger.error("Exception in encryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service."); } } @@ -150,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 dcryption service : ", e); - throw new EncryptionException("Exception while connecting enryption service ! "); + 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); + logger.error("Exception in decryption service !: {}", ExceptionUtils.getStackTrace(e)); throw new EncryptionException("Exception in encryption service ! "); } } @@ -181,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 Sunbird encryption service: ", ex); + 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/RegistryServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/RegistryServiceImpl.java index cee15e2f7..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 @@ -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; @@ -56,16 +57,14 @@ public class RegistryServiceImpl implements RegistryService { @Autowired private EntityTypeHandler entityTypeHandler; - @Autowired - private EncryptionService encryptionService; - @Autowired + @Autowired(required = false) private SignatureService signatureService; @Autowired private IDefinitionsManager definitionsManager; - @Autowired + @Autowired(required = false) private EncryptionHelper encryptionHelper; - @Autowired + @Autowired(required = false) private SignatureHelper signatureHelper; @Autowired private EntityTransformer entityTransformer; @@ -128,26 +127,22 @@ public class RegistryServiceImpl implements RegistryService { @Autowired private SchemaService schemaService; - @Autowired - private IElasticService elasticService; - - @Autowired - private FileStorageService fileStorageService; - - @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.toArray().toString()); + logger.info("Heath Check : {}", checks.stream().map(ComponentHealthInfo::getName).collect(Collectors.toList())); return healthCheck; } 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..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,10 +6,12 @@ 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; 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 +28,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); @@ -44,7 +47,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 @@ -61,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); - 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"); @@ -72,6 +77,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 +99,14 @@ public Object sign(Map propertyValue) response = retryRestTemplate.postForEntity(signURL, propertyValue); result = objectMapper.readTree(response.getBody()); logger.info("Successfully generated signed credentials"); - } catch (RestClientException ex) { - logger.error("RestClientException when signing: ", ex); - 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("RestClientException when signing: ", e); + logger.error("SignatureException when signing: {}", ExceptionUtils.getStackTrace(e)); throw new SignatureException().new CreationException(e.getMessage()); } return result; @@ -117,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); - 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); + logger.error("RestClientException when verifying: {}", ExceptionUtils.getStackTrace(e)); throw new SignatureException().new VerificationException(e.getMessage()); } logger.debug("verify method ends with value {}",result); @@ -143,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); - 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); + 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/sink/DatabaseProvider.java b/java/registry/src/main/java/dev/sunbirdrc/registry/sink/DatabaseProvider.java index d46bbf048..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); - 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 783edc49f..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); + 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 e91e25ba0..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); + 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/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/java/dev/sunbirdrc/registry/util/Definition.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/Definition.java index 0e0ffb748..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); + 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 2eba53a0a..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); + 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); + 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 c6554103a..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); + logger.error("Can't ensure parents for definitions: {}", ExceptionUtils.getStackTrace(e)); } }); @@ -237,8 +238,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, ExceptionUtils.getStackTrace(e)); } } @@ -273,8 +274,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(), ExceptionUtils.getStackTrace(e)); } } else { 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..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) { - e.printStackTrace(); + 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 3db7d0e05..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 @@ -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; @@ -24,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 { @@ -34,9 +35,9 @@ public JsonNode getResolvedSchema(String rootDefinitionName, String rootContext) logger.info(JSONUtil.convertObjectJsonString(resolvedDefinitions)); return resolvedDefinitions; } catch (IOException e) { - e.printStackTrace(); + logger.error("Failed resolving schema definitions for {}: {}", rootDefinitionName, ExceptionUtils.getStackTrace(e)); + throw e; } - return null; } public JsonNode resolveDefinitions(String currentDefinitionName, JsonNode currentNode) { @@ -78,7 +79,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, 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 e700c0b1a..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); + 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); + 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 804eb686d..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); + logger.error("Bad request to create a view template, {}", ExceptionUtils.getStackTrace(e)); } return viewTemp; } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index aefd99c47..4ff75516a 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} @@ -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} @@ -315,11 +317,17 @@ 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} 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} --- 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 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 8bbb99a42..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 @@ -79,24 +80,27 @@ 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.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 0dbb8dd25..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,8 +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(failure.getMessage(), failure); - failure.printStackTrace(); + 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 5421f8dda..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) { - ioe.printStackTrace(); + } 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/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..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: ", e); + 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); + 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 d91d67a4d..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); + logger.error("Error while performing transformation: {}", ExceptionUtils.getStackTrace(e)); return ""; } } 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..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,12 +79,8 @@ private static String readFileContent(String fileName) { } return result.toString(StandardCharsets.UTF_8.name()); - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - + logger.error(ExceptionUtils.getStackTrace(e)); } return null; } diff --git a/scripts/index.js b/scripts/index.js index 9b71720ab..221f323d2 100644 --- a/scripts/index.js +++ b/scripts/index.js @@ -35,8 +35,8 @@ 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.log(" error for " + payload) + console.error(err?.message) + 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/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" \ diff --git a/services/certificate-api/src/routes/certificate_controller.js b/services/certificate-api/src/routes/certificate_controller.js index c84a346aa..eaf1b35b5 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; } } @@ -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) } } 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/ 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/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/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/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/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() +} 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..e20ba7819 100644 --- a/services/metrics/swagger_gen/restapi/server.go +++ b/services/metrics/swagger_gen/restapi/server.go @@ -304,6 +304,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) 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 } diff --git a/test_environments/test_with_asyncCreate_events_notifications.env b/test_environments/test_with_asyncCreate_events_notifications.env new file mode 100644 index 000000000..18e661aec --- /dev/null +++ b/test_environments/test_with_asyncCreate_events_notifications.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 diff --git a/test_environments/test_with_distributedDefManager_nativeSearch.env b/test_environments/test_with_distributedDefManager_nativeSearch.env new file mode 100644 index 000000000..d3d4c9204 --- /dev/null +++ b/test_environments/test_with_distributedDefManager_nativeSearch.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