diff --git a/.circleci/config.yml b/.circleci/config.yml index 75f34ddc6..57afb86df 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,46 +4,6 @@ orbs: aws-cli: circleci/aws-cli@4.1.1 commands: - deploy: - description: Deployment of server - parameters: - hostname: - type: string - default: "ssh.staging.openchs.org" - steps: - - attach_workspace: - at: ~/artifacts - - - run: sudo apt-get install make openssl - - - run: - name: Install dependencies - command: | - sudo apt-get -y -qq update - sudo apt-get -y -qq install python3-pip - sudo pip3 install awscli --upgrade - - - run: - name: Copy build to server - command: | - scp -o StrictHostKeyChecking=no ~/artifacts/avni-server-*.noarch.rpm ec2-user@<< parameters.hostname >>:/tmp/avni-server.rpm - - - run: - name: Deploy server - command: | - ssh -o StrictHostKeyChecking=no ec2-user@<< parameters.hostname >> \<< EOF - sudo service openchs stop 2>&1 >/dev/null - sleep 5 - sudo yum clean all 2>&1 >/dev/null - sudo rm -rf /var/cache/yum 2>&1 >/dev/null - sudo yum -y updateinfo 2>&1 >/dev/null - sudo yum -y remove avni-server openchs-server java-1.7.0-openjdk 2>&1 >/dev/null - sudo yum -y install /tmp/avni-server.rpm 2>&1 >/dev/null - sudo service openchs start 2>&1 >/dev/null - sleep 20 - sudo rm -rf /tmp/avni-server.rpm - EOF - deploy_as_service: description: Deployment of avni-server as a systemd service parameters: @@ -94,7 +54,7 @@ commands: jobs: test: docker: - - image: circleci/openjdk:8-jdk + - image: cimg/openjdk:21.0 - image: circleci/postgres:12.7 environment: @@ -133,7 +93,7 @@ jobs: destination: testReports build: docker: - - image: circleci/openjdk:8-jdk + - image: cimg/openjdk:21.0 resource_class: medium working_directory: ~/avni-server @@ -151,7 +111,7 @@ jobs: - run: sudo apt-get install make openssl - - run: make upload-rpm + - run: make build_server - save_cache: paths: @@ -162,20 +122,11 @@ jobs: - run: mkdir -p ~/artifacts; - - run: cp minor_version ~/artifacts/minor_version; - - - run: cp major_version ~/artifacts/major_version; - - - run: cp ~/avni-server/avni-server-api/build/distributions/avni-server-*.noarch.rpm ~/artifacts/; - - run: cp ~/avni-server/avni-server-api/build/libs/avni-server-*.jar ~/artifacts/; - persist_to_workspace: root: ~/artifacts paths: - - minor_version - - major_version - - avni-server-*.noarch.rpm - avni-server-*.jar - store_artifacts: @@ -242,14 +193,6 @@ jobs: - deploy_as_service: env: "staging" - UAT_deploy: - docker: - - image: circleci/openjdk:8-jdk - working_directory: ~/ - steps: - - deploy: - hostname: "ssh.uat.openchs.org" - PRERELEASE_deploy: docker: - image: cimg/deploy:2023.09 @@ -266,7 +209,7 @@ jobs: PERF_deploy: docker: - - image: circleci/openjdk:8-jdk + - image: cimg/deploy:2023.09 working_directory: ~/ steps: - aws-cli/setup: @@ -275,8 +218,8 @@ jobs: - setup_server_access: instance-id: "i-0f30399b30e24a49b" availability-zone: "ap-south-1a" - - deploy: - hostname: "ssh.perf.avniproject.org" + - deploy_as_service: + env: "prerelease" PROD_deploy: docker: @@ -334,7 +277,7 @@ workflows: - build: <<: *tags_filter requires: - - test + - test - build_docker_image: context: - dockerhub @@ -353,14 +296,6 @@ workflows: context: non-prod-deploy requires: - STAGING_approve - - UAT_approve: - type: approval - requires: - - build - - UAT_deploy: - context: non-prod-deploy - requires: - - UAT_approve - PRERELEASE_approve: type: approval requires: diff --git a/.java-version b/.java-version index 625934097..5f39e9144 100644 --- a/.java-version +++ b/.java-version @@ -1 +1 @@ -1.8 +21.0 diff --git a/Makefile b/Makefile index 14bc2d0ab..2d247eaa6 100644 --- a/Makefile +++ b/Makefile @@ -184,14 +184,6 @@ open_test_results: open avni-server-api/build/reports/tests/test/index.html open-test-results: open_test_results -build-rpm: - ./gradlew clean avni-server-api:buildRpm -x test --info --stacktrace - -upload-rpm: - @openssl aes-256-cbc -a -md md5 -in infra/rpm/keys/openchs.asc.enc -d -out infra/rpm/keys/openchs.asc -k ${ENCRYPTION_KEY} - -rm -rf avni-server-api/build - ./gradlew clean avni-server-api:uploadRpm -x test --info --stacktrace --rerun-tasks - # exec-sql: ## Usage: make exec-sql sqlfile= psql -Uopenchs -f $(sqlfile) @@ -200,3 +192,6 @@ exec-sql: ## Usage: make exec-sql sqlfile= # remote tail-prod: ssh avni-prod "tail -f /var/log/avni_server/chs.log" + +show-dependency-graph: + ./gradlew avni-server-api:dependencies diff --git a/avni-server-api/build.gradle b/avni-server-api/build.gradle index aedf8c3fd..593c69c4b 100644 --- a/avni-server-api/build.gradle +++ b/avni-server-api/build.gradle @@ -1,7 +1,7 @@ buildscript { ext { - springBootVersion = '2.0.0.RELEASE' - osPackageVersion = "6.2.1" + springBootVersion = '3.3.5' + osPackageVersion = "11.10.0" } repositories { mavenCentral() } dependencies { @@ -12,86 +12,104 @@ buildscript { plugins { id 'org.springframework.boot' version "${springBootVersion}" - id 'io.spring.dependency-management' version '1.0.8.RELEASE' - id "nebula.ospackage" version "6.2.1" + id 'io.spring.dependency-management' version '1.1.6' + id "com.netflix.nebula.ospackage" version "11.10.0" id 'java' } -ext { springBootVersion = '2.0.0.RELEASE' } +ext { springBootVersion = '3.3.5' } //todo: Remove when upgrading Spring version. This was introduced to use SameSiteCookies -ext['tomcat.version'] = '9.0.80' +//ext['tomcat.version'] = '9.0.80' apply plugin: 'java' apply plugin: 'org.springframework.boot' apply plugin: 'idea' -apply from: 'rpm.gradle' apply plugin: 'io.spring.dependency-management' -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} repositories { mavenCentral() } bootJar { - baseName = "avni-server" + archiveBaseName = "avni-server" version = "0.0.1-SNAPSHOT" - mainClassName = 'org.avni.Avni' + mainClass = 'org.avni.Avni' } configurations { dev + all*.exclude group: 'org.slf4j', module: 'slf4j-reload4j' all*.exclude group: 'org.slf4j', module: 'slf4j-simple' } dependencies { - compile group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: '8.5.46' - compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") - compile "org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}" - testCompile "org.springframework.boot:spring-boot-starter-test:${springBootVersion}" - compile "org.springframework.boot:spring-boot-starter-data-rest:${springBootVersion}" - compile("org.springframework.boot:spring-boot-starter-security:${springBootVersion}") + implementation group: 'org.apache.tomcat', name: 'tomcat-jdbc' + implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") + implementation "org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}" + testImplementation "org.springframework.boot:spring-boot-starter-test:${springBootVersion}" + implementation "org.springframework.boot:spring-boot-starter-data-rest:${springBootVersion}" + implementation("org.springframework.boot:spring-boot-starter-security:${springBootVersion}") testImplementation "com.github.tomakehurst:wiremock-jre8-standalone:2.34.0" - compile "org.postgresql:postgresql:9.4-1200-jdbc41" - implementation 'org.springframework.boot:spring-boot-starter-batch' - testImplementation 'org.springframework.batch:spring-batch-test' - compile "joda-time:joda-time:2.9.4" - compile group: 'org.jadira.usertype', name: 'usertype.core', version: '6.0.1.GA' - compile "org.flywaydb:flyway-core:4.0.3" - compile "org.flywaydb.flyway-test-extensions:flyway-spring-test:4.0" - compile "com.zaxxer:HikariCP:2.5.1" - compile "org.apache.poi:poi:3.16-beta2" - compile "org.apache.poi:poi-ooxml:3.16-beta2" - compile 'org.apache.httpcomponents:httpclient:4.5.9' - compile 'com.auth0:jwks-rsa:0.3.0' - compile 'com.auth0:java-jwt:3.3.0' - compile group: 'org.hibernate', name: 'hibernate-search-orm', version: '5.9.2.Final' - compile 'com.bugsnag:bugsnag:3.+' - compile 'com.amazonaws:aws-java-sdk-s3' - compile 'com.amazonaws:aws-java-sdk-cognitoidp' - compile 'commons-validator:commons-validator:1.4.1' - compile 'org.passay:passay:1.6.3' + implementation "org.postgresql:postgresql" + implementation("org.springframework.boot:spring-boot-starter-batch:${springBootVersion}") + testImplementation 'org.springframework.batch:spring-batch-test:5.1.2' + implementation "joda-time:joda-time:2.10.10" + implementation("org.hibernate:hibernate-java8:5.6.15.Final") { + exclude(group: 'org.hibernate', module: 'hibernate-core') + } + runtimeOnly("javax.transaction:jta:1.1") +// implementation(group: 'org.jadira.usertype', name: 'usertype.core', version: '7.0.0.CR1') { +// exclude(group: 'org.hibernate', module: 'hibernate-core') +// } + implementation "org.flywaydb:flyway-core:10.20.1" + runtimeOnly("org.flywaydb:flyway-database-postgresql:10.20.1") + implementation "org.flywaydb.flyway-test-extensions:flyway-spring6-test:10.0.0" + implementation "com.zaxxer:HikariCP" + implementation "org.apache.poi:poi:3.16-beta2" + implementation "org.apache.poi:poi-ooxml:3.16-beta2" + implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.3' + implementation 'com.auth0:jwks-rsa:0.3.0' + implementation 'com.auth0:java-jwt:3.3.0' +// implementation(group: 'org.hibernate', name: 'hibernate-search-orm', version: '5.9.2.Final') { +// exclude(group: 'org.hibernate', module: 'hibernate-core') +// } + implementation 'com.bugsnag:bugsnag:3.+' + implementation 'com.amazonaws:aws-java-sdk-s3' + implementation 'com.amazonaws:aws-java-sdk-cognitoidp' + implementation 'commons-validator:commons-validator:1.4.1' + implementation 'org.passay:passay:1.6.3' implementation 'org.springframework.boot:spring-boot-starter-cache' - implementation 'org.keycloak:keycloak-spring-boot-starter:21.0.2' - implementation 'org.keycloak:keycloak-admin-client:21.0.2' - implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.6' - implementation 'com.fasterxml.jackson.core:jackson-core:2.12.6' - implementation 'com.fasterxml.jackson.core:jackson-annotations:2.12.6' - implementation 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.12.6' - implementation 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.12.6' - implementation 'org.hibernate:hibernate-ehcache:5.2.14.Final' + implementation 'org.keycloak:keycloak-spring-boot-starter:24.0.4' + implementation 'org.keycloak:keycloak-admin-client:24.0.2' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.4' + implementation 'com.fasterxml.jackson.core:jackson-core:2.15.4' + implementation 'com.fasterxml.jackson.core:jackson-annotations:2.15.4' + implementation 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.15.2' + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.15.4' + implementation('org.hibernate:hibernate-ehcache:5.6.15.Final') { + exclude(group: 'org.hibernate', module: 'hibernate-core') + } + runtimeOnly("javax.xml.bind:jaxb-api:2.3.1") + runtimeOnly('org.ehcache:ehcache:3.10.8') + runtimeOnly("org.hibernate:hibernate-jcache:6.5.1.Final") implementation 'javax.cache:cache-api:1.1.1' dev "org.springframework.boot:spring-boot-devtools:${springBootVersion}" - testCompile "org.mockito:mockito-core:2.23.4" - testCompile 'org.powermock:powermock-core:2.0.9' - testCompile 'org.powermock:powermock-api-mockito2:2.0.9' - testCompile 'org.powermock:powermock-module-junit4:2.0.9' - runtime("org.springframework.boot:spring-boot-properties-migrator") + testImplementation "org.mockito:mockito-core:3.12.4" + testImplementation 'org.powermock:powermock-core:2.0.9' + testImplementation 'org.powermock:powermock-api-mockito2:2.0.9' + testImplementation 'org.powermock:powermock-module-junit4:2.0.9' + runtimeOnly("org.springframework.boot:spring-boot-properties-migrator") implementation 'org.apache.tika:tika-core:2.7.0' - compile 'org.owasp.encoder:encoder:1.2.3' + implementation 'org.owasp.encoder:encoder:1.2.3' implementation 'org.apache.commons:commons-csv:1.10.0' - compile 'com.googlecode.libphonenumber:libphonenumber:8.12.32' + implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.32' testImplementation 'org.slf4j:slf4j-reload4j:2.0.6' - compile 'com.google.guava:guava:33.2.1-jre' + implementation 'com.google.guava:guava:33.2.1-jre' + implementation 'org.codehaus.jettison:jettison:1.5.4' } bootRun { diff --git a/avni-server-api/rpm.gradle b/avni-server-api/rpm.gradle deleted file mode 100644 index 0c8a61f30..000000000 --- a/avni-server-api/rpm.gradle +++ /dev/null @@ -1,86 +0,0 @@ -import groovy.json.JsonSlurper - -apply plugin: "nebula.ospackage" - - -ospackage { - - packageName = 'avni-server' - release = System.env.CIRCLE_BUILD_NUM ?: 0 - version = "${project.version.replace('-SNAPSHOT', '')}" - arch = NOARCH - os = LINUX - user = 'root' - - signingKeyId("72845CB15D05862A") - signingKeyPassphrase("$System.env.KEY_PASSWORD") - - - conflicts("java-1.7.0-openjdk") - requires("java-1.8.0-openjdk") - preInstall file("${project.rootProject.rootDir}/infra/rpm/scripts/preInstall.sh") - postInstall file("${project.rootProject.rootDir}/infra/rpm/scripts/postInstall.sh") - preUninstall file("${project.rootProject.rootDir}/infra/rpm/scripts/preUninstall.sh") - postUninstall file("${project.rootProject.rootDir}/infra/rpm/scripts/postUninstall.sh") - - into '/opt/openchs' - - from(bootJar.outputs.files) { - rename { String fileName -> - fileName.replace("-${project.version}", "") - } - fileMode = 0644 - createDirectoryEntry = true - into 'bin/' - } - - from("${project.rootProject.rootDir}/infra/rpm/config/openchs.conf") { - createDirectoryEntry = true - into 'config' - include('openchs.conf') - } - - - from("${project.rootProject.rootDir}/infra/rpm/service/openchs.pid") { - fileMode = 0644 - createDirectoryEntry = true - into 'run' - } - - from("${project.rootProject.rootDir}/infra/rpm/service/openchs.log") { - fileMode = 0644 - createDirectoryEntry = true - into 'log' - } - - from("${project.rootProject.rootDir}/infra/rpm/service/openchs") { - fileMode = 0644 - createDirectoryEntry = true - into 'scripts' - } - - from("${project.rootProject.rootDir}/infra/rpm/service/start.sh") { - fileMode = 0644 - createDirectoryEntry = true - into 'scripts' - } -} - -buildRpm { - dependsOn 'build' -} - -task uploadRpm { - dependsOn buildRpm - def rpmName = buildRpm.assembleArchiveName() - def rpmVersion = buildRpm.release - def rpmFilePath = buildRpm.outputs.files.singleFile.getAbsolutePath() - doLast { - def minorVersionFile = new File("$project.rootProject.rootDir/minor_version") - def majorVersionFile = new File("$project.rootProject.rootDir/major_version") - minorVersionFile.createNewFile() - majorVersionFile.createNewFile() - minorVersionFile.text = "$buildRpm.release" - majorVersionFile.text = "$buildRpm.version" - } -} diff --git a/avni-server-api/src/main/java/org/avni/Avni.java b/avni-server-api/src/main/java/org/avni/Avni.java index c2ad6c491..84a6d4165 100644 --- a/avni-server-api/src/main/java/org/avni/Avni.java +++ b/avni-server-api/src/main/java/org/avni/Avni.java @@ -19,11 +19,10 @@ import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Bean; import org.springframework.context.event.EventListener; -import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; -import org.springframework.hateoas.ResourceProcessor; - import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.hateoas.EntityModel; +import org.springframework.hateoas.Link; +import org.springframework.hateoas.server.RepresentationModelProcessor; @SpringBootApplication @EnableJpaRepositories(repositoryBaseClass = CustomJpaRepositoryImpl.class) @@ -42,60 +41,60 @@ public static void main(String[] args) { } @Bean - public ResourceProcessor> DashboardFilterProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> DashboardFilterProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DashboardFilter content = resource.getContent(); resource.removeLinks(); - resource.add(new Link(content.getDashboard().getUuid(), "dashboardUUID")); + resource.add(Link.of(content.getDashboard().getUuid(), "dashboardUUID")); return resource; } }; } @Bean - public ResourceProcessor> TaskStatusProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> TaskStatusProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { TaskStatus taskStatus = resource.getContent(); resource.removeLinks(); - resource.add(new Link(taskStatus.getTaskType().getUuid(), "taskTypeUUID")); + resource.add(Link.of(taskStatus.getTaskType().getUuid(), "taskTypeUUID")); return resource; } }; } @Bean - public ResourceProcessor> DashboardSectionCardMappingProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> DashboardSectionCardMappingProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DashboardSectionCardMapping dashboardSectionCardMapping = resource.getContent(); resource.removeLinks(); - resource.add(new Link(dashboardSectionCardMapping.getCard().getUuid(), "cardUUID")); - resource.add(new Link(dashboardSectionCardMapping.getDashboardSection().getUuid(), "dashboardSectionUUID")); + resource.add(Link.of(dashboardSectionCardMapping.getCard().getUuid(), "cardUUID")); + resource.add(Link.of(dashboardSectionCardMapping.getDashboardSection().getUuid(), "dashboardSectionUUID")); return resource; } }; } @Bean - public ResourceProcessor> OperationalSubjectTypeProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> OperationalSubjectTypeProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { OperationalSubjectType operationalSubjectType = resource.getContent(); resource.removeLinks(); if (operationalSubjectType.getSubjectType().getSyncRegistrationConcept1() != null) { - resource.add(new Link(operationalSubjectType.getSubjectType().getSyncRegistrationConcept1(), "syncRegistrationConcept1")); + resource.add(Link.of(operationalSubjectType.getSubjectType().getSyncRegistrationConcept1(), "syncRegistrationConcept1")); } if (operationalSubjectType.getSubjectType().getSyncRegistrationConcept2() != null) { - resource.add(new Link(operationalSubjectType.getSubjectType().getSyncRegistrationConcept2(), "syncRegistrationConcept2")); + resource.add(Link.of(operationalSubjectType.getSubjectType().getSyncRegistrationConcept2(), "syncRegistrationConcept2")); } if (operationalSubjectType.getSubjectType().getNameHelpText() != null) { - resource.add(new Link(operationalSubjectType.getSubjectType().getNameHelpText(), "nameHelpText")); + resource.add(Link.of(operationalSubjectType.getSubjectType().getNameHelpText(), "nameHelpText")); } return resource; } @@ -103,46 +102,46 @@ public Resource process(Resource } @Bean - public ResourceProcessor> GroupDashboardProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> GroupDashboardProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { GroupDashboard groupDashboard = resource.getContent(); resource.removeLinks(); - resource.add(new Link(groupDashboard.getGroup().getUuid(), "groupUUID")); - resource.add(new Link(groupDashboard.getDashboard().getUuid(), "dashboardUUID")); + resource.add(Link.of(groupDashboard.getGroup().getUuid(), "groupUUID")); + resource.add(Link.of(groupDashboard.getDashboard().getUuid(), "dashboardUUID")); return resource; } }; } @Bean - public ResourceProcessor> EntityApprovalStatusProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> EntityApprovalStatusProcessor() { + return new RepresentationModelProcessor>() { @Autowired private EntityApprovalStatusService entityApprovalStatusService; @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { EntityApprovalStatus entityApprovalStatus = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entityApprovalStatusService.getEntityUuid(entityApprovalStatus), "entityUUID")); - resource.add(new Link(entityApprovalStatus.getApprovalStatus().getUuid(), "approvalStatusUUID")); + resource.add(Link.of(entityApprovalStatusService.getEntityUuid(entityApprovalStatus), "entityUUID")); + resource.add(Link.of(entityApprovalStatus.getApprovalStatus().getUuid(), "approvalStatusUUID")); return resource; } }; } @Bean - public ResourceProcessor> CardProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> CardProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ReportCard card = resource.getContent(); StandardReportCardType standardReportCardType = card.getStandardReportCardType(); resource.removeLinks(); if (standardReportCardType != null) { - resource.add(new Link(standardReportCardType.getUuid(), "standardReportCardUUID")); + resource.add(Link.of(standardReportCardType.getUuid(), "standardReportCardUUID")); } return resource; } @@ -150,28 +149,28 @@ public Resource process(Resource resource) { } @Bean - public ResourceProcessor> IndividualRelationshipTypeProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> IndividualRelationshipTypeProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { IndividualRelationshipType individualRelationshipType = resource.getContent(); resource.removeLinks(); - resource.add(new Link(individualRelationshipType.getIndividualAIsToB().getUuid(), "individualAIsToBRelationUUID")); - resource.add(new Link(individualRelationshipType.getIndividualBIsToA().getUuid(), "individualBIsToBRelationUUID")); + resource.add(Link.of(individualRelationshipType.getIndividualAIsToB().getUuid(), "individualAIsToBRelationUUID")); + resource.add(Link.of(individualRelationshipType.getIndividualBIsToA().getUuid(), "individualBIsToBRelationUUID")); return resource; } }; } @Bean - public ResourceProcessor> IndividualRelationGenderMappingProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> IndividualRelationGenderMappingProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { IndividualRelationGenderMapping individualRelationGenderMapping = resource.getContent(); resource.removeLinks(); - resource.add(new Link(individualRelationGenderMapping.getRelation().getUuid(), "relationUUID")); - resource.add(new Link(individualRelationGenderMapping.getGender().getUuid(), "genderUUID")); + resource.add(Link.of(individualRelationGenderMapping.getRelation().getUuid(), "relationUUID")); + resource.add(Link.of(individualRelationGenderMapping.getGender().getUuid(), "genderUUID")); return resource; } }; @@ -179,19 +178,19 @@ public Resource process(Resource> formElementProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> formElementProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { FormElement formElement = resource.getContent(); resource.removeLinks(); - resource.add(new Link(formElement.getFormElementGroup().getUuid(), "formElementGroupUUID")); - resource.add(new Link(formElement.getConcept().getUuid(), "conceptUUID")); + resource.add(Link.of(formElement.getFormElementGroup().getUuid(), "formElementGroupUUID")); + resource.add(Link.of(formElement.getConcept().getUuid(), "conceptUUID")); if (formElement.getGroup() != null) { - resource.add(new Link(formElement.getGroup().getUuid(), "groupQuestionUUID")); + resource.add(Link.of(formElement.getGroup().getUuid(), "groupQuestionUUID")); } if (formElement.getDocumentation() != null) { - resource.add(new Link(formElement.getDocumentation().getUuid(), "documentationUUID")); + resource.add(Link.of(formElement.getDocumentation().getUuid(), "documentationUUID")); } return resource; } @@ -199,72 +198,72 @@ public Resource process(Resource resource) { } @Bean - public ResourceProcessor> formElementGroupProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> formElementGroupProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { FormElementGroup formElementGroup = resource.getContent(); resource.removeLinks(); - resource.add(new Link(formElementGroup.getForm().getUuid(), "formUUID")); + resource.add(Link.of(formElementGroup.getForm().getUuid(), "formUUID")); return resource; } }; } @Bean - public ResourceProcessor> documentationItemsProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> documentationItemsProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DocumentationItem documentationItem = resource.getContent(); resource.removeLinks(); - resource.add(new Link(documentationItem.getDocumentation().getUuid(), "documentationUUID")); + resource.add(Link.of(documentationItem.getDocumentation().getUuid(), "documentationUUID")); return resource; } }; } @Bean - public ResourceProcessor> conceptAnswerProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> conceptAnswerProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ConceptAnswer conceptAnswer = resource.getContent(); resource.removeLinks(); - resource.add(new Link(conceptAnswer.getConcept().getUuid(), "conceptUUID")); - resource.add(new Link(conceptAnswer.getAnswerConcept().getUuid(), "conceptAnswerUUID")); + resource.add(Link.of(conceptAnswer.getConcept().getUuid(), "conceptUUID")); + resource.add(Link.of(conceptAnswer.getAnswerConcept().getUuid(), "conceptAnswerUUID")); return resource; } }; } @Bean - public ResourceProcessor> FormMappingProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> FormMappingProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { FormMapping formMapping = resource.getContent(); resource.removeLinks(); Form form = formMapping.getForm(); if (form != null) { - resource.add(new Link(formMapping.getForm().getUuid(), "formUUID")); + resource.add(Link.of(formMapping.getForm().getUuid(), "formUUID")); String programUuid = formMapping.getProgramUuid(); if (programUuid != null) { - resource.add(new Link(programUuid, "entityUUID")); + resource.add(Link.of(programUuid, "entityUUID")); } if (formMapping.getSubjectType() != null) { - resource.add(new Link(formMapping.getSubjectType().getUuid(), "subjectTypeUUID")); + resource.add(Link.of(formMapping.getSubjectType().getUuid(), "subjectTypeUUID")); } if (formMapping.getTaskType() != null) { - resource.add(new Link(formMapping.getTaskTypeUuid(), "taskTypeUUID")); + resource.add(Link.of(formMapping.getTaskTypeUuid(), "taskTypeUUID")); } String encounterTypeUuid = formMapping.getEncounterTypeUuid(); if (encounterTypeUuid != null) { - resource.add(new Link(encounterTypeUuid, "observationsTypeEntityUUID")); + resource.add(Link.of(encounterTypeUuid, "observationsTypeEntityUUID")); } return resource; @@ -275,10 +274,10 @@ public Resource process(Resource resource) { } @Bean - public ResourceProcessor> RuleProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> RuleProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Rule rule = resource.getContent(); resource.removeLinks(); RuledEntityType entityType = rule.getEntity().getType(); @@ -286,7 +285,7 @@ public Resource process(Resource resource) { String key = RuledEntityType.isForm(entityType) ? "formUUID" : RuledEntityType.isProgram(entityType) ? "programUUID" : null; if (entityUUID != null && key != null) { - resource.add(new Link(entityUUID, key)); + resource.add(Link.of(entityUUID, key)); } return resource; } @@ -294,18 +293,18 @@ public Resource process(Resource resource) { } @Bean - public ResourceProcessor> ChecklistItemDetailProcessor() { - return new ResourceProcessor>() { + public RepresentationModelProcessor> ChecklistItemDetailProcessor() { + return new RepresentationModelProcessor>() { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ChecklistItemDetail content = resource.getContent(); resource.removeLinks(); - resource.add(new Link(content.getChecklistDetail().getUuid(), "checklistDetailUUID")); - resource.add(new Link(content.getConcept().getUuid(), "conceptUUID")); - resource.add(new Link(content.getForm().getUuid(), "formUUID")); + resource.add(Link.of(content.getChecklistDetail().getUuid(), "checklistDetailUUID")); + resource.add(Link.of(content.getConcept().getUuid(), "conceptUUID")); + resource.add(Link.of(content.getForm().getUuid(), "formUUID")); ChecklistItemDetail leadChecklistItemDetail = content.getLeadChecklistItemDetail(); if (leadChecklistItemDetail != null) { - resource.add(new Link(leadChecklistItemDetail.getUuid(), "leadDetailUUID")); + resource.add(Link.of(leadChecklistItemDetail.getUuid(), "leadDetailUUID")); } return resource; } diff --git a/avni-server-api/src/main/java/org/avni/messaging/api/ManualMessageController.java b/avni-server-api/src/main/java/org/avni/messaging/api/ManualMessageController.java index 39f4ad9ac..b6bdb8be6 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/api/ManualMessageController.java +++ b/avni-server-api/src/main/java/org/avni/messaging/api/ManualMessageController.java @@ -4,6 +4,7 @@ import org.avni.messaging.service.MessagingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -18,6 +19,7 @@ public ManualMessageController(MessagingService messagingService) { } @RequestMapping(value = "/web/scheduleManualMessage", method = RequestMethod.POST) + @Transactional public ResponseEntity.BodyBuilder save(@RequestBody ManualMessageContract manualMessageContract) { messagingService.scheduleManualMessage(manualMessageContract.getReceiverId(), manualMessageContract.getReceiverType(), diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GetAllMessagesData.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GetAllMessagesData.java index d06510489..e6325c33f 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GetAllMessagesData.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GetAllMessagesData.java @@ -1,5 +1,6 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -11,6 +12,7 @@ @JsonPropertyOrder({ "messages" }) +@JsonIgnoreProperties(ignoreUnknown = true) public class GetAllMessagesData { @JsonProperty("messages") @@ -18,13 +20,13 @@ public class GetAllMessagesData { /** * No args constructor for use in serialization - * + * */ public GetAllMessagesData() { } /** - * + * * @param messages */ public GetAllMessagesData(List messages) { @@ -42,4 +44,4 @@ public void setMessages(List messages) { this.messages = messages; } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuth.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuth.java index b0be6abdd..d64c038dc 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuth.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuth.java @@ -1,7 +1,9 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificAuth { @JsonProperty("access_token") private String accessToken; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuthRequest.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuthRequest.java index 92752444c..ce4de7431 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuthRequest.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificAuthRequest.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificAuthRequest { private final GlificUser user; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactCountResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactCountResponse.java index 4a16af79a..2619b3ea0 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactCountResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactCountResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificContactGroupContactCountResponse { private int countContacts; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactsResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactsResponse.java index 6192735ef..893e31e24 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactsResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupContactsResponse.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificContactGroupContactsResponse { private List contacts; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupCountResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupCountResponse.java index 221951d1b..2cc06a045 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupCountResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupCountResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificContactGroupCountResponse { private int countGroups; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupsResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupsResponse.java index 9b5a2e334..10ba4a81c 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupsResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactGroupsResponse.java @@ -1,8 +1,11 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.io.Serializable; import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificContactGroupsResponse { private List groups; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactResponse.java index 7871a3e4d..f165d0469 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificContactResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificContactResponse { private String id; private String name; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificCreateContactGroupResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificCreateContactGroupResponse.java index ad574d318..804a78ffe 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificCreateContactGroupResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificCreateContactGroupResponse.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificCreateContactGroupResponse { private CreateGroupErrors createGroup; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificError.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificError.java index e3f00626c..eee6cd513 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificError.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificError.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificError { private List locations; private String message; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificErrorLocation.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificErrorLocation.java index 9a3a2f468..da6ce9728 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificErrorLocation.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificErrorLocation.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificErrorLocation { private int column; private int row; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetContactsResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetContactsResponse.java index 2efc7c1bc..8a6affff2 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetContactsResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetContactsResponse.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificGetContactsResponse { private List contacts; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetGroupResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetGroupResponse.java index de60f7f04..2056bd673 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetGroupResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificGetGroupResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificGetGroupResponse { private GlificGroupGroup group; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageResponse.java index 7b12c7871..4e3f143a2 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageResponse.java @@ -1,4 +1,7 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificMessageResponse { } diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplate.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplate.java index d490e17bf..3266eb783 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplate.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplate.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.io.Serializable; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificMessageTemplate implements Serializable { private String body; private String id; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplateResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplateResponse.java index 31cf6da0d..25aa962f1 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplateResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificMessageTemplateResponse.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificMessageTemplateResponse { private List sessionTemplates; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactResponse.java index d3ec18867..19213ab45 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificOptinContactResponse { private GlificOptinContactWithErrorsResponse optinContact; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactWithErrorsResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactWithErrorsResponse.java index 3b19fe872..3b69b510f 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactWithErrorsResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificOptinContactWithErrorsResponse.java @@ -1,5 +1,8 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificOptinContactWithErrorsResponse { private GlificContactResponse contact; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificResponse.java index 3bac28317..38ff19715 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificResponse.java @@ -1,7 +1,10 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificResponse { private T data; private List errors; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificSearchDataResponse.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificSearchDataResponse.java index 36cd6aea9..edb887ac8 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificSearchDataResponse.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificSearchDataResponse.java @@ -1,5 +1,6 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -11,6 +12,7 @@ @JsonPropertyOrder({ "search" }) +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificSearchDataResponse { @JsonProperty("search") @@ -18,13 +20,13 @@ public class GlificSearchDataResponse { /** * No args constructor for use in serialization - * + * */ public GlificSearchDataResponse() { } /** - * + * * @param search */ public GlificSearchDataResponse(List search) { @@ -42,4 +44,4 @@ public void setSearch(List search) { this.search = search; } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificUser.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificUser.java index 096dec74c..81e5cc294 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificUser.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/GlificUser.java @@ -1,10 +1,12 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.avni.messaging.domain.GlificSystemConfig; import org.springframework.util.Assert; import java.io.Serializable; +@JsonIgnoreProperties(ignoreUnknown = true) public class GlificUser implements Serializable { private final String phone; private final String password; diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Message.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Message.java index deb2702f7..727dabdc8 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Message.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Message.java @@ -1,5 +1,6 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -14,6 +15,7 @@ "receiver", "type" }) +@JsonIgnoreProperties(ignoreUnknown = true) public class Message { @JsonProperty("body") @@ -33,13 +35,13 @@ public class Message { /** * No args constructor for use in serialization - * + * */ public Message() { } /** - * + * * @param receiver * @param insertedAt * @param sender diff --git a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Search.java b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Search.java index ccf0becae..570549bfd 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Search.java +++ b/avni-server-api/src/main/java/org/avni/messaging/contract/glific/Search.java @@ -1,5 +1,6 @@ package org.avni.messaging.contract.glific; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -12,6 +13,7 @@ "contact", "messages" }) +@JsonIgnoreProperties(ignoreUnknown = true) public class Search { @JsonProperty("contact") @@ -21,13 +23,13 @@ public class Search { /** * No args constructor for use in serialization - * + * */ public Search() { } /** - * + * * @param contact * @param messages */ @@ -57,4 +59,4 @@ public void setMessages(List messages) { this.messages = messages; } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/messaging/domain/ManualMessage.java b/avni-server-api/src/main/java/org/avni/messaging/domain/ManualMessage.java index a19e0a145..56692c4e4 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/domain/ManualMessage.java +++ b/avni-server-api/src/main/java/org/avni/messaging/domain/ManualMessage.java @@ -1,12 +1,13 @@ package org.avni.messaging.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.ArrayUserType; +import org.avni.server.framework.hibernate.NextTriggerDetailsUserType; import org.hibernate.annotations.Type; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; - @Entity @Table(name = "manual_message") public class ManualMessage extends OrganisationAwareEntity { @@ -14,11 +15,11 @@ public class ManualMessage extends OrganisationAwareEntity { private String messageTemplateId; @Column(columnDefinition = "text[]") - @Type(type = "parameters") + @Type(value = ArrayUserType.class) private String[] parameters; @Column - @Type(type = "nextTriggerDetails") + @Type(value = NextTriggerDetailsUserType.class) private NextTriggerDetails nextTriggerDetails; public ManualMessage(String messageTemplateId, String[] parameters) { diff --git a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageReceiver.java b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageReceiver.java index 7a162bfe4..648ac0df9 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageReceiver.java +++ b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageReceiver.java @@ -1,10 +1,9 @@ package org.avni.messaging.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "message_receiver") public class MessageReceiver extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRequest.java b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRequest.java index b6229c0c2..53b9e6ddd 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRequest.java +++ b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRequest.java @@ -1,10 +1,12 @@ package org.avni.messaging.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "message_request_queue") @@ -28,7 +30,7 @@ public class MessageRequest extends OrganisationAwareEntity { @Column @NotNull - private DateTime scheduledDateTime; + private Instant scheduledDateTime; @Column @NotNull @@ -36,7 +38,7 @@ public class MessageRequest extends OrganisationAwareEntity { private MessageDeliveryStatus deliveryStatus; @Column - private DateTime deliveredDateTime; + private Instant deliveredDateTime; public void setMessageRule(MessageRule messageRule) { this.messageRule = messageRule; @@ -51,7 +53,7 @@ public void setEntityId(Long entityId) { } public void setScheduledDateTime(DateTime scheduledDateTime) { - this.scheduledDateTime = scheduledDateTime; + this.scheduledDateTime = DateTimeUtil.toInstant(scheduledDateTime); } public void setDeliveryStatus(MessageDeliveryStatus deliveryStatus) { @@ -59,7 +61,7 @@ public void setDeliveryStatus(MessageDeliveryStatus deliveryStatus) { } public void setDeliveredDateTime(DateTime deliveredDateTime) { - this.deliveredDateTime = deliveredDateTime; + this.deliveredDateTime = DateTimeUtil.toInstant(deliveredDateTime); } public MessageRequest() { @@ -69,20 +71,20 @@ public MessageRequest(MessageRule messageRule, MessageReceiver messageReceiverId this.messageRule = messageRule; this.messageReceiver = messageReceiverId; this.entityId = entityId; - this.scheduledDateTime = scheduledDateTime; + this.setScheduledDateTime(scheduledDateTime); this.deliveryStatus = MessageDeliveryStatus.NotSent; } public MessageRequest(ManualMessage manualMessage, MessageReceiver messageReceiver, DateTime scheduledDateTime) { this.manualMessage = manualMessage; this.messageReceiver = messageReceiver; - this.scheduledDateTime = scheduledDateTime; + this.setScheduledDateTime(scheduledDateTime); this.deliveryStatus = MessageDeliveryStatus.NotSent; } public void markComplete() { deliveryStatus = MessageDeliveryStatus.Sent; - deliveredDateTime = DateTime.now(); + setDeliveredDateTime(DateTime.now()); } public MessageRule getMessageRule() { @@ -98,7 +100,7 @@ public Long getEntityId() { } public DateTime getScheduledDateTime() { - return scheduledDateTime; + return DateTimeUtil.toJodaDateTime(scheduledDateTime); } public MessageDeliveryStatus getDeliveryStatus() { @@ -106,7 +108,7 @@ public MessageDeliveryStatus getDeliveryStatus() { } public DateTime getDeliveredDateTime() { - return deliveredDateTime; + return DateTimeUtil.toJodaDateTime(deliveredDateTime); } public boolean isDelivered() { diff --git a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRule.java b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRule.java index e3670aeb4..3d8cfb3cc 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRule.java +++ b/avni-server-api/src/main/java/org/avni/messaging/domain/MessageRule.java @@ -1,10 +1,9 @@ package org.avni.messaging.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "message_rule") public class MessageRule extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/messaging/domain/exception/GlificContactNotFoundError.java b/avni-server-api/src/main/java/org/avni/messaging/domain/exception/GlificContactNotFoundError.java index ec6e23c1f..76d56e584 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/domain/exception/GlificContactNotFoundError.java +++ b/avni-server-api/src/main/java/org/avni/messaging/domain/exception/GlificContactNotFoundError.java @@ -1,9 +1,9 @@ package org.avni.messaging.domain.exception; -import javax.ws.rs.NotFoundException; +import jakarta.ws.rs.NotFoundException; public class GlificContactNotFoundError extends NotFoundException { public GlificContactNotFoundError(String msg) { super(msg); } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/messaging/repository/MessageRequestQueueRepository.java b/avni-server-api/src/main/java/org/avni/messaging/repository/MessageRequestQueueRepository.java index e4a0e5ab4..6c114acab 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/repository/MessageRequestQueueRepository.java +++ b/avni-server-api/src/main/java/org/avni/messaging/repository/MessageRequestQueueRepository.java @@ -6,12 +6,14 @@ import org.avni.messaging.domain.MessageRule; import org.avni.server.dao.CHSRepository; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.joda.time.Duration; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.Date; import java.util.Optional; import java.util.stream.Stream; @@ -19,11 +21,12 @@ @Repository public interface MessageRequestQueueRepository extends CHSRepository { - Stream findAllByDeliveryStatusNotAndIsVoidedFalseAndScheduledDateTimeBetween(MessageDeliveryStatus messageDeliveryStatus, DateTime then, DateTime now); + Stream findAllByDeliveryStatusNotAndIsVoidedFalseAndScheduledDateTimeBetween(MessageDeliveryStatus messageDeliveryStatus, Instant then, Instant now); Optional findByEntityIdAndMessageRule(Long entityId, MessageRule messageRule); default Stream findDueMessageRequests(Duration duration) { - return findAllByDeliveryStatusNotAndIsVoidedFalseAndScheduledDateTimeBetween(MessageDeliveryStatus.Sent, DateTime.now().minus(duration), DateTime.now()); + return findAllByDeliveryStatusNotAndIsVoidedFalseAndScheduledDateTimeBetween(MessageDeliveryStatus.Sent, + DateTimeUtil.toInstant(DateTime.now().minus(duration)), DateTimeUtil.toInstant(DateTime.now())); } @Modifying(clearAutomatically = true, flushAutomatically=true) diff --git a/avni-server-api/src/main/java/org/avni/messaging/service/MessagingService.java b/avni-server-api/src/main/java/org/avni/messaging/service/MessagingService.java index a43b242c8..175c71993 100644 --- a/avni-server-api/src/main/java/org/avni/messaging/service/MessagingService.java +++ b/avni-server-api/src/main/java/org/avni/messaging/service/MessagingService.java @@ -126,7 +126,6 @@ public void onUserEntitySave(Long userId, User createdBy) throws RuleExecutionEx } } - @Transactional public Page findByEntityTypeAndEntityTypeId(EntityType entityType, Long entityTypeId, Pageable pageable) { return messageRuleRepository.findByEntityTypeAndEntityTypeId(entityType, entityTypeId, pageable); } @@ -162,7 +161,6 @@ public void sendMessages(Duration duration) { requests.forEach(this::sendMessage); } - @Transactional public void scheduleManualMessage(String receiverId, ReceiverType receiverType, String messageTemplateId, String[] parameters, DateTime scheduledDateTime) { ManualMessage manualMessage = new ManualMessage(messageTemplateId, parameters); manualMessage.assignUUIDIfRequired(); diff --git a/avni-server-api/src/main/java/org/avni/server/AvniSpringConfiguration.java b/avni-server-api/src/main/java/org/avni/server/AvniSpringConfiguration.java index d8ae01435..a73ec46ef 100644 --- a/avni-server-api/src/main/java/org/avni/server/AvniSpringConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/AvniSpringConfiguration.java @@ -1,14 +1,20 @@ package org.avni.server; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.cache.CacheBuilder; import org.avni.server.application.projections.CatchmentAddressProjection; import org.avni.server.domain.User; import org.avni.server.framework.jpa.CHSAuditorAware; -import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; +import org.avni.server.util.ObjectMapperSingleton; +import org.keycloak.adapters.KeycloakConfigResolver; +import org.keycloak.adapters.KeycloakDeployment; +import org.keycloak.adapters.KeycloakDeploymentBuilder; +import org.keycloak.representations.adapters.config.AdapterConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; @@ -16,6 +22,7 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.data.domain.AuditorAware; @@ -26,6 +33,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import javax.sql.DataSource; +import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; @@ -58,12 +66,46 @@ public class AvniSpringConfiguration extends WebMvcAutoConfiguration { @Value("${avni.custom.query.max.rows}") private int maxRows; + @Value("${avni.keycloak.realm}") + private String realm; + + @Value("${keycloak.resource}") + private String keycloakResource; + + @Value("${keycloak.auth-server-url}") + private String keycloakAuthServerUrl; + + @Value("${keycloak.ssl-required}") + private String sslRequired; + + @Value("${keycloak.credentials.secret}") + private String keycloakCredentialsSecret; + + @Value("${keycloak.use-resource-role-mappings}") + private boolean useResourceRoleMappings; + @Autowired public AvniSpringConfiguration(Environment environment, @Qualifier("dataSource") DataSource dataSource) { this.environment = environment; this.dataSource = dataSource; } + // https://stackoverflow.com/questions/62571413/spring-keycloak-adapter-loads-open-id-configuration-for-every-single-request + @Bean + public AdapterConfig adapterConfig() { + AdapterConfig adapterConfig = new AdapterConfig(); + adapterConfig.setRealm(realm); + adapterConfig.setResource(keycloakResource); + adapterConfig.setAuthServerUrl(keycloakAuthServerUrl); + adapterConfig.setSslRequired(sslRequired); + + HashMap credentials = new HashMap<>(); + credentials.put("secret", keycloakCredentialsSecret); + adapterConfig.setCredentials(credentials); + adapterConfig.setUseResourceRoleMappings(useResourceRoleMappings); + return adapterConfig; + } + @Bean public AuditorAware auditorProvider() { return new CHSAuditorAware(); @@ -96,8 +138,13 @@ public NamedParameterJdbcTemplate getExternalQueryJdbcTemplate() { } @Bean - public KeycloakSpringBootConfigResolver keycloakConfigResolver() { - return new KeycloakSpringBootConfigResolver(); + public KeycloakDeployment keycloakDeployment(AdapterConfig adapterConfig) { + return KeycloakDeploymentBuilder.build(adapterConfig); + } + + @Bean + public KeycloakConfigResolver keycloakConfigResolver(KeycloakDeployment keycloakDeployment) { + return request -> keycloakDeployment; } @Bean @@ -131,4 +178,23 @@ private ConcurrentMapCache getConcurrentMapCacheWithMaxEntriesConfig(String name } }; } + + @Bean + @Primary + public ObjectMapper objectMapper() { + ObjectMapper objectMapper = ObjectMapperSingleton.getObjectMapper(); + return objectMapper; + } + + @Bean + @Qualifier("customRestTemplateCustomizer") + public CustomRestTemplateCustomizer customRestTemplateCustomizer() { + return new CustomRestTemplateCustomizer(); + } + + @Bean + @DependsOn(value = {"customRestTemplateCustomizer"}) + public RestTemplateBuilder restTemplateBuilder() { + return new RestTemplateBuilder(customRestTemplateCustomizer()); + } } diff --git a/avni-server-api/src/main/java/org/avni/server/CustomClientHttpRequestInterceptor.java b/avni-server-api/src/main/java/org/avni/server/CustomClientHttpRequestInterceptor.java new file mode 100644 index 000000000..6132aedd9 --- /dev/null +++ b/avni-server-api/src/main/java/org/avni/server/CustomClientHttpRequestInterceptor.java @@ -0,0 +1,32 @@ +package org.avni.server; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import java.io.IOException; + +/** + * interceptor to log incoming requests + */ +public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + + logRequestDetails(request); + + return execution.execute(request, body); + } + + private void logRequestDetails(HttpRequest request) { + LOGGER.info("Request Headers: {}", request.getHeaders()); + LOGGER.info("Request Method: {}", request.getMethod()); + LOGGER.info("Request URI: {}", request.getURI()); + } +} \ No newline at end of file diff --git a/avni-server-api/src/main/java/org/avni/server/CustomRestTemplateCustomizer.java b/avni-server-api/src/main/java/org/avni/server/CustomRestTemplateCustomizer.java new file mode 100644 index 000000000..bde55a624 --- /dev/null +++ b/avni-server-api/src/main/java/org/avni/server/CustomRestTemplateCustomizer.java @@ -0,0 +1,14 @@ +package org.avni.server; + +import org.springframework.boot.web.client.RestTemplateCustomizer; +import org.springframework.web.client.RestTemplate; + +/** + * customize rest template with an interceptor + */ +public class CustomRestTemplateCustomizer implements RestTemplateCustomizer { + @Override + public void customize(RestTemplate restTemplate) { + restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor()); + } +} \ No newline at end of file diff --git a/avni-server-api/src/main/java/org/avni/server/StringToJodaDateTimeConverter.java b/avni-server-api/src/main/java/org/avni/server/StringToJodaDateTimeConverter.java new file mode 100644 index 000000000..826c972d8 --- /dev/null +++ b/avni-server-api/src/main/java/org/avni/server/StringToJodaDateTimeConverter.java @@ -0,0 +1,18 @@ +package org.avni.server; + +import org.joda.time.DateTime; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +public class StringToJodaDateTimeConverter implements Converter { + @Override + public DateTime convert(String source) { + return new DateTime(source); + } + + @Override + public Converter andThen(Converter after) { + return Converter.super.andThen(after); + } +} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvoker.java b/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvoker.java deleted file mode 100644 index 9e9a7a0d3..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvoker.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.avni.server.adapter; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.dao.ConceptRepository; -import org.avni.server.domain.Concept; -import org.avni.server.adapter.contract.DecisionRuleResponse; -import org.avni.server.web.request.ObservationRequest; - -import javax.script.ScriptEngine; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -public abstract class HealthModuleInvoker { - protected ScriptObjectMirror eval; - - public HealthModuleInvoker(ScriptEngine scriptEngine, InputStream inputStream) { - try { - scriptEngine.eval("var console = {log: function(x){}};"); - eval = (ScriptObjectMirror) scriptEngine.eval(new InputStreamReader(inputStream)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected Object invoke(String functionName, Object... args) { - try { - return eval.callMember(functionName, args); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected List getObservationRequests(ConceptRepository conceptRepository, List decisionRuleResponses) { - List observationRequests = new ArrayList<>(); - decisionRuleResponses.forEach(decisionRuleResponse -> { - ObservationRequest observationRequest = new ObservationRequest(); - observationRequest.setConceptName(decisionRuleResponse.getName()); - - if (decisionRuleResponse.getValue() instanceof List) { - List conceptUUIDs = (List) ((List) decisionRuleResponse.getValue()).stream().map(o -> { - Concept concept = conceptRepository.findByName((String) o); - return concept.getUuid(); - }).collect(Collectors.toList()); - if (conceptUUIDs.size() != 0) { - observationRequest.setValue(conceptUUIDs.toArray(new String[conceptUUIDs.size()])); - observationRequests.add(observationRequest); - } - } else { - observationRequest.setValue(decisionRuleResponse.getValue()); - observationRequests.add(observationRequest); - } - }); - return observationRequests; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvokerFactory.java b/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvokerFactory.java deleted file mode 100644 index bc053f0cf..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/HealthModuleInvokerFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.avni.server.adapter; - -import org.springframework.context.annotation.Lazy; -import org.springframework.core.io.ClassPathResource; -import org.springframework.stereotype.Component; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import java.io.IOException; -import java.io.InputStream; - -@Component -@Lazy -public class HealthModuleInvokerFactory { - private final ProgramEnrolmentModuleInvoker programEnrolmentInvoker; - private final ProgramEncounterRuleInvoker programEncounterInvoker; - - private InputStream getInputStreamForRule(String fileName) throws IOException { - return new ClassPathResource("rules/" + fileName).getInputStream(); - } - - public HealthModuleInvokerFactory() throws IOException { - ScriptEngine programEnrolmentEngine = new ScriptEngineManager().getEngineByName("nashorn"); - ScriptEngine programEncounterEngine = new ScriptEngineManager().getEngineByName("nashorn"); - this.programEnrolmentInvoker = new ProgramEnrolmentModuleInvoker(programEnrolmentEngine, getInputStreamForRule("programEnrolmentDecision.js")); - this.programEncounterInvoker = new ProgramEncounterRuleInvoker(programEncounterEngine, getInputStreamForRule("programEncounterDecision.js")); - } - - public ProgramEnrolmentModuleInvoker getProgramEnrolmentInvoker() { - return programEnrolmentInvoker; - } - - public ProgramEncounterRuleInvoker getProgramEncounterInvoker() { - return programEncounterInvoker; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEncounterRuleInvoker.java b/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEncounterRuleInvoker.java deleted file mode 100644 index 2f5c7fa8d..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEncounterRuleInvoker.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.avni.server.adapter; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.dao.ConceptRepository; -import org.avni.server.adapter.contract.DecisionRuleResponse; -import org.avni.server.adapter.contract.ProgramScheduledVisitsResponse; -import org.avni.server.adapter.contract.encounter.ProgramEncounterDecisionRuleResponse; -import org.avni.server.adapter.contract.encounter.ProgramEncounterRuleInput; -import org.avni.server.web.request.ObservationRequest; -import org.avni.server.web.request.ProgramEncounterRequest; - -import javax.script.ScriptEngine; -import java.io.InputStream; -import java.util.List; - -public class ProgramEncounterRuleInvoker extends HealthModuleInvoker { - public ProgramEncounterRuleInvoker(ScriptEngine scriptEngine, InputStream inputStream) { - super(scriptEngine, inputStream); - } - - public List getDecisions(ProgramEncounterRuleInput ruleInput, ConceptRepository conceptRepository) { - ScriptObjectMirror decision = (ScriptObjectMirror) this.invoke("getDecisions", ruleInput); - ProgramEncounterDecisionRuleResponse decisionRuleResponse = new ProgramEncounterDecisionRuleResponse(decision); - List decisionRuleResponses = decisionRuleResponse.getDecisionRuleResponses(); - return getObservationRequests(conceptRepository, decisionRuleResponses); - } - - public List getNextScheduledVisits(ProgramEncounterRuleInput ruleInput, String enrolmentUUID) { - ScriptObjectMirror nextScheduledVisits = (ScriptObjectMirror) this.invoke("getNextScheduledVisits", ruleInput); - ProgramScheduledVisitsResponse programEnrolmentNextScheduledVisitsResponse = new ProgramScheduledVisitsResponse(nextScheduledVisits); - return programEnrolmentNextScheduledVisitsResponse.getProgramEncounterRequests(enrolmentUUID); - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEnrolmentModuleInvoker.java b/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEnrolmentModuleInvoker.java deleted file mode 100644 index bb55f9d06..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/ProgramEnrolmentModuleInvoker.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.avni.server.adapter; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.dao.ConceptRepository; -import org.avni.server.adapter.contract.checklist.ChecklistRuleResponse; -import org.avni.server.adapter.contract.enrolment.ProgramEnrolmentDecisionRuleResponse; -import org.avni.server.adapter.contract.enrolment.ProgramEnrolmentRuleInput; -import org.avni.server.adapter.contract.validation.ValidationsRuleResponse; -import org.avni.server.adapter.contract.DecisionRuleResponse; -import org.avni.server.adapter.contract.ProgramScheduledVisitsResponse; -import org.avni.server.web.request.ObservationRequest; -import org.avni.server.web.request.ProgramEncounterRequest; - -import javax.script.ScriptEngine; -import java.io.InputStream; -import java.util.List; - -public class ProgramEnrolmentModuleInvoker extends HealthModuleInvoker { - public ProgramEnrolmentModuleInvoker(ScriptEngine scriptEngine, InputStream inputStream) { - super(scriptEngine, inputStream); - } - - public List getDecisions(ProgramEnrolmentRuleInput programEnrolmentRuleInput, ConceptRepository conceptRepository) { - ScriptObjectMirror decision = executeRule(programEnrolmentRuleInput, "getDecisions"); - ProgramEnrolmentDecisionRuleResponse programEnrolmentDecisionRuleResponse = new ProgramEnrolmentDecisionRuleResponse(decision); - List decisionRuleResponses = programEnrolmentDecisionRuleResponse.getDecisionRuleResponses(); - - return getObservationRequests(conceptRepository, decisionRuleResponses); - } - - private ScriptObjectMirror executeRule(ProgramEnrolmentRuleInput programEnrolmentRuleInput, String functionName) { - return (ScriptObjectMirror) this.invoke(functionName, programEnrolmentRuleInput, programEnrolmentRuleInput.getProgramEnrolmentRequest().getEnrolmentDateTime().toDate()); - } - - public List getNextScheduledVisits(ProgramEnrolmentRuleInput programEnrolmentRuleInput, String enrolmentUUID) { - ScriptObjectMirror nextScheduledVisits = executeRule(programEnrolmentRuleInput, "getNextScheduledVisits"); - ProgramScheduledVisitsResponse programEnrolmentNextScheduledVisitsResponse = new ProgramScheduledVisitsResponse(nextScheduledVisits); - return programEnrolmentNextScheduledVisitsResponse.getProgramEncounterRequests(enrolmentUUID); - } - - public ChecklistRuleResponse getChecklist(ProgramEnrolmentRuleInput programEnrolmentRuleInput) { - ScriptObjectMirror checklists = executeRule(programEnrolmentRuleInput, "getChecklists"); - if (checklists.containsKey("0")) { - return new ChecklistRuleResponse((ScriptObjectMirror) checklists.get("0")); - } else - return null; - } - - public ValidationsRuleResponse validate(ProgramEnrolmentRuleInput programEnrolmentRuleInput) { - ScriptObjectMirror validationResults = executeRule(programEnrolmentRuleInput, "validate"); - if (validationResults.containsKey("0")) { - return new ValidationsRuleResponse((ScriptObjectMirror) validationResults.get("0")); - } else - return null; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/DecisionRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/DecisionRuleResponse.java deleted file mode 100644 index 48a4c348d..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/DecisionRuleResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.avni.server.adapter.contract; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; - -public class DecisionRuleResponse extends RuleResponse { - private final String name; - private final Object value; - - public DecisionRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - name = (String) scriptObjectMirror.get("name"); - value = this.getUnderlyingValue("value", x -> x); - } - - public String getName() { - return name; - } - - public Object getValue() { - return value; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/IndividualRuleInput.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/IndividualRuleInput.java deleted file mode 100644 index cb442064b..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/IndividualRuleInput.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.avni.server.adapter.contract; - -import jdk.nashorn.internal.objects.NativeDate; -import org.avni.server.domain.Individual; -import org.joda.time.LocalDate; - -import java.util.Date; - -public class IndividualRuleInput { - private final Individual individual; - private LocalDate today; - - public IndividualRuleInput(Individual individual, LocalDate today) { - this.individual = individual; - this.today = today; - } - - public Date getDateOfBirth() { - return individual.getDateOfBirth().toDate(); - } - - public int getAgeInYears(NativeDate date) { - return this.getAgeInYears(new LocalDate((long)date.getTime(date))); - } - - private int getAgeInYears(LocalDate localDate) { - return localDate.getYear() - this.individual.getDateOfBirth().getYear(); - } - - public int getAgeInYears() { - return this.getAgeInYears(this.today); - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/ProgramScheduledVisitsResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/ProgramScheduledVisitsResponse.java deleted file mode 100644 index 850648be2..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/ProgramScheduledVisitsResponse.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.avni.server.adapter.contract; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.joda.time.DateTime; -import org.avni.server.web.request.ProgramEncounterRequest; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class ProgramScheduledVisitsResponse extends RuleResponse { - private List programScheduledVisitRuleResponseList = new ArrayList<>(); - - public ProgramScheduledVisitsResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - addToList(scriptObjectMirror, this.programScheduledVisitRuleResponseList, object -> new ProgramScheduledVisitRuleResponse((ScriptObjectMirror) object)); - } - - public List getProgramEncounterRequests(String enrolmentUUID) { - ArrayList programEncounterRequests = new ArrayList<>(); - this.programScheduledVisitRuleResponseList.stream().forEach(programScheduledVisitRuleResponse -> { - programEncounterRequests.add(programScheduledVisitRuleResponse.getProgramEncounterRequest(enrolmentUUID)); - }); - return programEncounterRequests; - } - - public class ProgramScheduledVisitRuleResponse extends RuleResponse { - private final String name; - private final String encounterType; - private final Date earliestDate; - private final Date maxDate; - - public ProgramScheduledVisitRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - this.name = (String) scriptObjectMirror.get("name"); - this.encounterType = (String) scriptObjectMirror.get("encounterType"); - this.earliestDate = this.getDate("earliestDate"); - this.maxDate = this.getDate("maxDate"); - } - - public ProgramEncounterRequest getProgramEncounterRequest(String enrolmentUUID) { - ProgramEncounterRequest programEncounterRequest = ProgramEncounterRequest.createSafeInstance(); - programEncounterRequest.setProgramEnrolmentUUID(enrolmentUUID); - programEncounterRequest.setName(name); - programEncounterRequest.setEncounterType(encounterType); - programEncounterRequest.setEarliestVisitDateTime(new DateTime(earliestDate)); - programEncounterRequest.setMaxDateTime(new DateTime(maxDate)); - return programEncounterRequest; - } - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/RuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/RuleResponse.java deleted file mode 100644 index 7cf233894..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/RuleResponse.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.avni.server.adapter.contract; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.joda.time.DateTime; -import org.avni.server.util.O; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class RuleResponse { - protected ScriptObjectMirror scriptObjectMirror; - - public RuleResponse(ScriptObjectMirror scriptObjectMirror) { - this.scriptObjectMirror = scriptObjectMirror; - } - - protected String getDateAsString(ScriptObjectMirror mirror, String name) { - return O.getDateInDbFormat(this.getDate(mirror, name)); - } - - protected Date getDate(ScriptObjectMirror mirror, String name) { - Object o = mirror.get(name); - if (o instanceof Date) return (Date) o; - - ScriptObjectMirror field = (ScriptObjectMirror) o; - double timestampLocalTime = (Double) field.callMember("getTime"); - return new Date((long) timestampLocalTime); - } - - protected Date getDate(String propertyName) { - return getDate(scriptObjectMirror, propertyName); - } - - protected DateTime getDateTime(String propertyName) { - return new DateTime(getDate(propertyName)); - } - - protected String getDateAsString(String name) { - return this.getDateAsString(scriptObjectMirror, name); - } - - protected boolean isDate(ScriptObjectMirror mirror, String name) { - if (!(mirror.get(name) instanceof ScriptObjectMirror)) return false; - ScriptObjectMirror field = (ScriptObjectMirror) mirror.get(name); - return field.hasMember("getTime"); - } - - protected boolean isDate(String name) { - return this.isDate(scriptObjectMirror, name); - } - - protected Object getUnderlyingValue(ScriptObjectMirror mirror, String name, ObjectCreator objectCreator) { - if (isDate(name)) return getDateAsString(name); - if (isList(name)) { - ArrayList list = new ArrayList(); - addToList((ScriptObjectMirror) mirror.get(name), list, objectCreator); - return list; - } - if (mirror.get(name) instanceof ScriptObjectMirror) - return new ArrayList(); - return mirror.get(name); - } - - protected Object getUnderlyingValue(String name, ObjectCreator objectCreator) { - return this.getUnderlyingValue(this.scriptObjectMirror, name, objectCreator); - } - - protected void addToList(ScriptObjectMirror array, List list, ObjectCreator objectCreator) { - int length = array.getOwnKeys(false).length; - for (int i = 0; i < length; i++) { - Object arrayElement = array.get(Integer.toString(i)); - list.add(objectCreator.create(arrayElement)); - } - } - - protected boolean isList(ScriptObjectMirror mirror, String name) { - if (!(mirror.get(name) instanceof ScriptObjectMirror)) return false; - ScriptObjectMirror field = (ScriptObjectMirror) mirror.get(name); - return field.get("0") != null; - } - - protected boolean isList(String name) { - return this.isList(scriptObjectMirror, name); - } - - protected String getString(String name) { - return (String) scriptObjectMirror.get(name); - } - - public interface ObjectCreator { - Object create(Object object); - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistItemRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistItemRuleResponse.java deleted file mode 100644 index 4e6b21da6..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistItemRuleResponse.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.avni.server.adapter.contract.checklist; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.dao.ConceptRepository; -import org.avni.server.domain.ChecklistItem; -import org.avni.server.domain.Concept; -import org.avni.server.adapter.contract.RuleResponse; -import org.avni.server.service.ChecklistService; -import org.avni.server.web.request.application.ChecklistItemRequest; - -import java.util.UUID; - -public class ChecklistItemRuleResponse extends RuleResponse { - private final String name; - - public ChecklistItemRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - this.name = getString("name"); - - } - - public ChecklistItemRequest getChecklistItemRequest(ChecklistService checklistService, String programEnrolmentUUID, ConceptRepository conceptRepository) { - ChecklistItem checklistItem = checklistService.findChecklistItem(programEnrolmentUUID, name); - - ChecklistItemRequest checklistItemRequest = new ChecklistItemRequest(); - Concept concept = conceptRepository.findByName(name); - if (concept == null) - throw new RuntimeException(String.format("Couldn't find concept with name=%s in checklist being created from the rule", name)); - checklistItemRequest.setUuid(checklistItem == null ? UUID.randomUUID().toString() : checklistItem.getUuid()); - return checklistItemRequest; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistRuleResponse.java deleted file mode 100644 index de21e81fa..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/checklist/ChecklistRuleResponse.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.avni.server.adapter.contract.checklist; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.dao.ConceptRepository; -import org.joda.time.DateTime; -import org.avni.server.adapter.contract.RuleResponse; -import org.avni.server.service.ChecklistService; -import org.avni.server.web.request.ChecklistRequest; -import org.avni.server.web.request.application.ChecklistItemRequest; - -import java.util.ArrayList; -import java.util.List; - -public class ChecklistRuleResponse extends RuleResponse { - private String name; - private DateTime baseDate; - private List items; - - public ChecklistRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - name = getString("name"); - baseDate = getDateTime("baseDate"); - ScriptObjectMirror responseItems = (ScriptObjectMirror) scriptObjectMirror.get("items"); - this.items = new ArrayList<>(); - this.addToList(responseItems, items, object -> new ChecklistItemRuleResponse((ScriptObjectMirror) object)); - } - - public List getItems(ChecklistService checklistService, String programEnrolmentUUID, ConceptRepository conceptRepository) { - ArrayList checklistItemRequests = new ArrayList<>(); - for (ChecklistItemRuleResponse checklistItemRuleResponse : items) { - checklistItemRequests.add(checklistItemRuleResponse.getChecklistItemRequest(checklistService, programEnrolmentUUID, conceptRepository)); - } - return checklistItemRequests; - } - - public ChecklistRequest getChecklistRequest() { - ChecklistRequest checklistRequest = new ChecklistRequest(); - checklistRequest.setBaseDate(baseDate); - return checklistRequest; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/encounter/ProgramEncounterDecisionRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/encounter/ProgramEncounterDecisionRuleResponse.java deleted file mode 100644 index fc6a20930..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/encounter/ProgramEncounterDecisionRuleResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.avni.server.adapter.contract.encounter; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.adapter.contract.DecisionRuleResponse; -import org.avni.server.adapter.contract.RuleResponse; - -import java.util.ArrayList; -import java.util.List; - -public class ProgramEncounterDecisionRuleResponse extends RuleResponse { - private List decisionRuleResponses = new ArrayList<>(); - - public ProgramEncounterDecisionRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - ScriptObjectMirror enrolmentDecisions = (ScriptObjectMirror) scriptObjectMirror.get("encounterDecisions"); - addToList(enrolmentDecisions, this.decisionRuleResponses, object -> new DecisionRuleResponse((ScriptObjectMirror) object)); - } - - public List getDecisionRuleResponses() { - return decisionRuleResponses; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentDecisionRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentDecisionRuleResponse.java deleted file mode 100644 index 025037661..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentDecisionRuleResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.avni.server.adapter.contract.enrolment; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.adapter.contract.DecisionRuleResponse; -import org.avni.server.adapter.contract.RuleResponse; - -import java.util.ArrayList; -import java.util.List; - -public class ProgramEnrolmentDecisionRuleResponse extends RuleResponse { - private List decisionRuleResponses = new ArrayList<>(); - - public ProgramEnrolmentDecisionRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - ScriptObjectMirror enrolmentDecisions = (ScriptObjectMirror) scriptObjectMirror.get("enrolmentDecisions"); - addToList(enrolmentDecisions, this.decisionRuleResponses, object -> new DecisionRuleResponse((ScriptObjectMirror) object)); - } - - public List getDecisionRuleResponses() { - return decisionRuleResponses; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentRuleInput.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentRuleInput.java deleted file mode 100644 index 28c31dfef..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/enrolment/ProgramEnrolmentRuleInput.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.avni.server.adapter.contract.enrolment; - -import org.avni.server.dao.ConceptRepository; -import org.avni.server.dao.IndividualRepository; -import org.avni.server.domain.Individual; -import org.avni.server.adapter.ObservationsHelper; -import org.avni.server.adapter.contract.IndividualRuleInput; -import org.avni.server.adapter.contract.ProgramRuleInput; -import org.avni.server.web.request.ProgramEnrolmentRequest; - -import java.util.Date; - -public class ProgramEnrolmentRuleInput { - private ProgramEnrolmentRequest programEnrolmentRequest; - private ConceptRepository conceptRepository; - private IndividualRuleInput individual; - private ProgramRuleInput program; - - public ProgramEnrolmentRuleInput(ProgramEnrolmentRequest programEnrolmentRequest, IndividualRepository individualRepository, ConceptRepository conceptRepository) { - this.programEnrolmentRequest = programEnrolmentRequest; - this.conceptRepository = conceptRepository; - Individual individual = individualRepository.findByUuid(programEnrolmentRequest.getIndividualUUID()); - this.individual = new IndividualRuleInput(individual, programEnrolmentRequest.getEnrolmentDateTime().toLocalDate()); - this.program = new ProgramRuleInput(programEnrolmentRequest.getProgram()); - } - - public IndividualRuleInput getIndividual() { - return individual; - } - - public void setIndividual(IndividualRuleInput individual) { - this.individual = individual; - } - - public ProgramRuleInput getProgram() { - return program; - } - - public void setProgram(ProgramRuleInput program) { - this.program = program; - } - - // In data migration this will never be called in edit mode, so it can assume that there are no encounters - public Object getObservationReadableValueInEntireEnrolment(String conceptName, Object programEncounter) { - return this.getObservationValue(conceptName); - } - - public Date getEnrolmentDateTime() { - return this.programEnrolmentRequest.getEnrolmentDateTime().toDate(); - } - - public Object findEncounter(String encounterTypeName, String encounterName) { - return null; - } - - public boolean hasEncounter(String encounterTypeName, String encounterName) { - return false; - } - - public Object[] getEncounters(Object... objects) { - return new Object[]{}; - } - // end - - public Object getObservationValue(String conceptName) { - return ObservationsHelper.getObservationValue(conceptName, programEnrolmentRequest.getObservations(), conceptRepository); - } - - public Object findObservation(String conceptName) { - return ObservationsHelper.getObservation(conceptName, programEnrolmentRequest.getObservations(), conceptRepository); - } - - public ProgramEnrolmentRequest getProgramEnrolmentRequest() { - return programEnrolmentRequest; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/RuleValidationResult.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/RuleValidationResult.java deleted file mode 100644 index 797c42f8d..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/RuleValidationResult.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.avni.server.adapter.contract.validation; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.adapter.contract.RuleResponse; - -public class RuleValidationResult extends RuleResponse { - private final String success; - private final String messageKey; - - public RuleValidationResult(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - this.success = this.getString("success"); - this.messageKey = this.getString("messageKey"); - } - - @Override - public String toString() { - return "{" + - "success='" + success + '\'' + - ", messageKey='" + messageKey + '\'' + - '}'; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/ValidationsRuleResponse.java b/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/ValidationsRuleResponse.java deleted file mode 100644 index 01dad7b00..000000000 --- a/avni-server-api/src/main/java/org/avni/server/adapter/contract/validation/ValidationsRuleResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.avni.server.adapter.contract.validation; - -import jdk.nashorn.api.scripting.ScriptObjectMirror; -import org.avni.server.adapter.contract.RuleResponse; - -import java.util.ArrayList; -import java.util.List; - -public class ValidationsRuleResponse extends RuleResponse { - private final List validationResults; - - public ValidationsRuleResponse(ScriptObjectMirror scriptObjectMirror) { - super(scriptObjectMirror); - - ScriptObjectMirror responseItems = (ScriptObjectMirror) scriptObjectMirror.get("items"); - this.validationResults = new ArrayList<>(); - this.addToList(responseItems, this.validationResults, object -> new RuleValidationResult((ScriptObjectMirror) object)); - } - - public List getValidationResults() { - return validationResults; - } - - @Override - public String toString() { - return "{" + - "validationResults=" + validationResults.stream().map(Object::toString) + - '}'; - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/application/DecisionConcept.java b/avni-server-api/src/main/java/org/avni/server/application/DecisionConcept.java index b32284b9c..87d925476 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/DecisionConcept.java +++ b/avni-server-api/src/main/java/org/avni/server/application/DecisionConcept.java @@ -1,10 +1,9 @@ package org.avni.server.application; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.Concept; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "decision_concept") public class DecisionConcept { diff --git a/avni-server-api/src/main/java/org/avni/server/application/Form.java b/avni-server-api/src/main/java/org/avni/server/application/Form.java index cf4a1b3ae..1fb15ac42 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/Form.java +++ b/avni-server-api/src/main/java/org/avni/server/application/Form.java @@ -5,10 +5,11 @@ import org.avni.server.domain.ConceptDataType; import org.avni.server.domain.DeclarativeRule; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import java.util.*; import java.util.stream.Collectors; @@ -41,22 +42,22 @@ public class Form extends OrganisationAwareEntity { private String checklistsRule; @Column(name = "validation_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule validationDeclarativeRule; @Column(name = "decision_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule decisionDeclarativeRule; @Column(name = "visit_schedule_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule visitScheduleDeclarativeRule; @Column(name = "task_schedule_rule") private String taskScheduleRule; @Column(name = "task_schedule_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule taskScheduleDeclarativeRule; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "form") diff --git a/avni-server-api/src/main/java/org/avni/server/application/FormElement.java b/avni-server-api/src/main/java/org/avni/server/application/FormElement.java index 351b91f0e..3d1e425d8 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/FormElement.java +++ b/avni-server-api/src/main/java/org/avni/server/application/FormElement.java @@ -1,16 +1,19 @@ package org.avni.server.application; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.Null; import org.avni.server.domain.*; import org.avni.server.common.ValidationResult; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; +import org.avni.server.framework.hibernate.KeyValuesUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import org.avni.server.web.validation.ValidationException; import org.springframework.util.StringUtils; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -35,7 +38,7 @@ public class FormElement extends OrganisationAwareEntity { private boolean isMandatory; @Column - @Type(type = "keyValues") + @Type(value = KeyValuesUserType.class) private KeyValues keyValues; @ManyToOne(fetch = FetchType.LAZY) @@ -61,7 +64,7 @@ public class FormElement extends OrganisationAwareEntity { private String rule; @Column(name = "declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule declarativeRule; @ManyToOne(fetch = FetchType.LAZY) diff --git a/avni-server-api/src/main/java/org/avni/server/application/FormElementGroup.java b/avni-server-api/src/main/java/org/avni/server/application/FormElementGroup.java index 6d0199e2b..0a6769c40 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/FormElementGroup.java +++ b/avni-server-api/src/main/java/org/avni/server/application/FormElementGroup.java @@ -2,11 +2,12 @@ import org.avni.server.domain.DeclarativeRule; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -34,7 +35,7 @@ public class FormElementGroup extends OrganisationAwareEntity { private String rule; @Column(name = "declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule declarativeRule; @Column diff --git a/avni-server-api/src/main/java/org/avni/server/application/FormMapping.java b/avni-server-api/src/main/java/org/avni/server/application/FormMapping.java index 733cf3917..41ea42163 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/FormMapping.java +++ b/avni-server-api/src/main/java/org/avni/server/application/FormMapping.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; +import jakarta.persistence.*; @Entity @Table(name = "form_mapping") diff --git a/avni-server-api/src/main/java/org/avni/server/application/Format.java b/avni-server-api/src/main/java/org/avni/server/application/Format.java index 6b0f9b288..3599fca9a 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/Format.java +++ b/avni-server-api/src/main/java/org/avni/server/application/Format.java @@ -1,19 +1,17 @@ package org.avni.server.application; -import javax.persistence.Column; -import javax.persistence.Embeddable; +import jakarta.persistence.*; @Embeddable public class Format { - @Column(name = "valid_format_regex", nullable = false) + @Column(name = "valid_format_regex") private String regex; - @Column(name = "valid_format_description_key", nullable = false) + @Column(name = "valid_format_description_key") private String descriptionKey; public Format(){ - } public Format(String regex, String descriptionKey){ diff --git a/avni-server-api/src/main/java/org/avni/server/application/NonApplicableFormElement.java b/avni-server-api/src/main/java/org/avni/server/application/NonApplicableFormElement.java index 01f6d3a9c..08e3d9fe3 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/NonApplicableFormElement.java +++ b/avni-server-api/src/main/java/org/avni/server/application/NonApplicableFormElement.java @@ -1,10 +1,9 @@ package org.avni.server.application; +import jakarta.persistence.*; import org.avni.server.domain.OrganisationAwareEntity; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; - @Entity @Table(name = "non_applicable_form_element") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/application/menu/MenuItem.java b/avni-server-api/src/main/java/org/avni/server/application/menu/MenuItem.java index 880748693..51609183a 100644 --- a/avni-server-api/src/main/java/org/avni/server/application/menu/MenuItem.java +++ b/avni-server-api/src/main/java/org/avni/server/application/menu/MenuItem.java @@ -1,9 +1,8 @@ package org.avni.server.application.menu; +import jakarta.persistence.*; import org.avni.server.domain.OrganisationAwareEntity; -import javax.persistence.*; - @Entity @Table(name = "menu_item") public class MenuItem extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/AddressLevelTypeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/AddressLevelTypeRepository.java index 84a385e71..c812ad9cc 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/AddressLevelTypeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/AddressLevelTypeRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.AddressLevelType; import org.avni.server.domain.AddressLevelTypes; import org.springframework.data.jpa.repository.Query; @@ -8,7 +9,6 @@ import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.stereotype.Repository; -import javax.validation.constraints.NotNull; import java.util.Collection; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ApprovalStatusRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ApprovalStatusRepository.java index 315db3dcc..f3d8b6fce 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ApprovalStatusRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ApprovalStatusRepository.java @@ -1,7 +1,6 @@ package org.avni.server.dao; import org.avni.server.domain.ApprovalStatus; -import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; @@ -10,19 +9,20 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; +import java.time.Instant; + @Repository @RepositoryRestResource(collectionResourceRel = "approvalStatus", path = "approvalStatus") public interface ApprovalStatusRepository extends AvniJpaRepository { - @RestResource(path = "lastModified", rel = "lastModified") Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); ApprovalStatus findByUuid(String uuid); ApprovalStatus findByStatus(ApprovalStatus.Status status); - boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/AvniJobRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/AvniJobRepository.java index 532bf189f..90fe75259 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/AvniJobRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/AvniJobRepository.java @@ -34,18 +34,18 @@ public Page getJobStatuses(User user, String jobFilterCondition, Page " bje.create_time create_time,\n" + " bje.start_time start_time,\n" + " bje.end_time end_time,\n" + - " string_agg(case when bjep.key_name = 'uuid' then bjep.string_val else '' end::text, '') uuid,\n" + - " string_agg(case when bjep.key_name = 'fileName' then bjep.string_val else '' end::text, '') fileName,\n" + - " sum(case when bjep.key_name = 'noOfLines' then bjep.long_val else 0 end) noOfLines,\n" + - " string_agg(case when bjep.key_name = 's3Key' then bjep.string_val else '' end::text, '') s3Key,\n" + - " sum(case when bjep.key_name = 'userId' then bjep.long_val else 0 end) userId,\n" + - " string_agg(case when bjep.key_name = 'type' then bjep.string_val::text else '' end::text, '') job_type,\n" + - " max(case when bjep.key_name = 'startDate' then bjep.date_val::timestamp else null::timestamp end::timestamp) startDate,\n" + - " max(case when bjep.key_name = 'endDate' then bjep.date_val::timestamp else null::timestamp end::timestamp) endDate,\n" + - " string_agg(case when bjep.key_name = 'subjectTypeUUID' then bjep.string_val::text else '' end::text, '') subjectTypeUUID,\n" + - " string_agg(case when bjep.key_name = 'programUUID' then bjep.string_val::text else '' end::text, '') programUUID,\n" + - " string_agg(case when bjep.key_name = 'encounterTypeUUID' then bjep.string_val::text else '' end::text, '') encounterTypeUUID,\n" + - " string_agg(case when bjep.key_name = 'reportType' then bjep.string_val::text else '' end::text, '') reportType,\n" + + " string_agg(case when bjep.parameter_name = 'uuid' then bjep.parameter_value else '' end::text, '') uuid,\n" + + " string_agg(case when bjep.parameter_name = 'fileName' then bjep.parameter_value else '' end::text, '') fileName,\n" + + " sum(case when bjep.parameter_name = 'noOfLines' then (case when bjep.parameter_value = '' then 0 else bjep.parameter_value::int end) else 0 end) noOfLines,\n" + + " string_agg(case when bjep.parameter_name = 's3Key' then bjep.parameter_value else '' end::text, '') s3Key,\n" + + " sum(case when bjep.parameter_name = 'userId' then (case when bjep.parameter_value = '' then 0 else bjep.parameter_value::int end) else 0 end) userId,\n" + + " string_agg(case when bjep.parameter_name = 'type' then bjep.parameter_value::text else '' end::text, '') job_type,\n" + + " max(case when bjep.parameter_name = 'startDate' then bjep.parameter_value::timestamp else null::timestamp end::timestamp) startDate,\n" + + " max(case when bjep.parameter_name = 'endDate' then bjep.parameter_value::timestamp else null::timestamp end::timestamp) endDate,\n" + + " string_agg(case when bjep.parameter_name = 'subjectTypeUUID' then bjep.parameter_value::text else '' end::text, '') subjectTypeUUID,\n" + + " string_agg(case when bjep.parameter_name = 'programUUID' then bjep.parameter_value::text else '' end::text, '') programUUID,\n" + + " string_agg(case when bjep.parameter_name = 'encounterTypeUUID' then bjep.parameter_value::text else '' end::text, '') encounterTypeUUID,\n" + + " string_agg(case when bjep.parameter_name = 'reportType' then bjep.parameter_value::text else '' end::text, '') reportType,\n" + " max(bse.read_count) read_count,\n" + " max(bse.write_count) write_count,\n" + " max(bse.write_skip_count) write_skip_count\n" + diff --git a/avni-server-api/src/main/java/org/avni/server/dao/CHSRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/CHSRepository.java index 16edf5733..1c30501a6 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/CHSRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/CHSRepository.java @@ -1,12 +1,14 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.Concept; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.repository.NoRepositoryBean; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -45,7 +47,7 @@ default Expression convertToDate(Path path, CriteriaBuilder cb) { return cb.function("TO_CHAR", String.class, path, cb.literal("yyyy-MM-dd")); } - default Specification lastModifiedBetween(Date lastModifiedDateTime, Date now) { + default Specification lastModifiedBetween(Instant lastModifiedDateTime, Instant now) { Specification spec = (Root root, CriteriaQuery query, CriteriaBuilder cb) -> { List predicates = new ArrayList<>(); @@ -60,6 +62,10 @@ default Specification lastModifiedBetween(Date lastModifiedDateTime, Date now) { return spec; } + default Specification lastModifiedBetween(Date lastModifiedDateTime, Date now) { + return this.lastModifiedBetween(DateTimeUtil.toInstant(lastModifiedDateTime), DateTimeUtil.toInstant(now)); + } + default Specification withConceptValues(Map concepts, String observationField) { Specification spec = (Root root, CriteriaQuery query, CriteriaBuilder cb) -> { List predicates = new ArrayList<>(); @@ -78,9 +84,9 @@ default void voidEntity(Long id) { this.save(entity); } - boolean existsByLastModifiedDateTimeGreaterThan(Date lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); default boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime) { - return existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime == null ? null : lastModifiedDateTime.toDate()); + return existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ChecklistItemRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ChecklistItemRepository.java index 488c629b1..ce6310339 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ChecklistItemRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ChecklistItemRepository.java @@ -1,19 +1,18 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Set; @@ -22,7 +21,7 @@ public interface ChecklistItemRepository extends TransactionalDataRepository, OperatingIndividualScopeAwareRepository, SubjectTreeItemRepository { Page findByChecklistProgramEnrolmentIndividualAddressLevelVirtualCatchmentsIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - long catchmentId, Date lastModifiedDateTime, Date now, Pageable pageable); + long catchmentId, Instant lastModifiedDateTime, Instant now, Pageable pageable); ChecklistItem findByChecklistUuidAndChecklistItemDetailUuid(String checklistUUID, String checklistItemDetailUUID); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ChecklistRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ChecklistRepository.java index ffc0f3b3c..55375f406 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ChecklistRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ChecklistRepository.java @@ -1,19 +1,18 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Set; @@ -22,7 +21,7 @@ public interface ChecklistRepository extends TransactionalDataRepository, OperatingIndividualScopeAwareRepository, SubjectTreeItemRepository { Page findByProgramEnrolmentIndividualAddressLevelVirtualCatchmentsIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - long catchmentId, Date lastModifiedDateTime, Date now, Pageable pageable); + long catchmentId, Instant lastModifiedDateTime, Instant now, Pageable pageable); Checklist findByProgramEnrolmentId(long programEnrolmentId); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/CommentRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/CommentRepository.java index dcce5e1bf..e13cf5363 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/CommentRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/CommentRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.Comment; import org.avni.server.domain.Individual; @@ -10,7 +11,6 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/CommentThreadRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/CommentThreadRepository.java index 0ab444c78..19fe60a97 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/CommentThreadRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/CommentThreadRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.Comment; import org.avni.server.domain.CommentThread; @@ -11,7 +12,6 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ConceptRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ConceptRepository.java index 6b0a1c0d4..ef2d9696d 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ConceptRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ConceptRepository.java @@ -1,13 +1,11 @@ package org.avni.server.dao; +import jakarta.persistence.QueryHint; import org.avni.server.domain.Concept; import org.avni.server.domain.ConceptDataType; import org.avni.server.domain.Organisation; import org.avni.server.domain.UserContext; import org.avni.server.framework.security.UserContextHolder; -import org.avni.server.web.response.ConceptNameUuidAndDatatype; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; @@ -15,10 +13,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.QueryHint; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; @Repository diff --git a/avni-server-api/src/main/java/org/avni/server/dao/CustomJpaRepositoryImpl.java b/avni-server-api/src/main/java/org/avni/server/dao/CustomJpaRepositoryImpl.java index fbb2d3a53..b62c3e3e3 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/CustomJpaRepositoryImpl.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/CustomJpaRepositoryImpl.java @@ -1,5 +1,7 @@ package org.avni.server.dao; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; import org.avni.server.domain.CHSEntity; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; @@ -8,13 +10,10 @@ import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; import java.io.Serializable; import java.util.List; public class CustomJpaRepositoryImpl extends SimpleJpaRepository implements CustomCHSJpaRepository { - public CustomJpaRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { super(entityInformation, entityManager); } @@ -25,6 +24,11 @@ public Slice findAllAsSlice(Specification specification, Pageable pageable return pageable.isUnpaged() ? new SliceImpl<>(query.getResultList()) : readSlice(query, pageable, specification); } + @Override + public void deleteInBatch(Iterable entities) { + entities.forEach(this::delete); + } + private Slice readSlice(TypedQuery query, Pageable pageable, Specification specification){ if (pageable.isPaged()){ query.setFirstResult((int) pageable.getOffset()); @@ -37,4 +41,4 @@ private Slice readSlice(TypedQuery query, Pageable pageable, Specification } return new SliceImpl<>(content, pageable, hasNextPage); } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/server/dao/EncounterRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/EncounterRepository.java index 41f2e150e..a077ef3e6 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/EncounterRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/EncounterRepository.java @@ -1,7 +1,9 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -11,7 +13,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -21,10 +23,10 @@ @RepositoryRestResource(collectionResourceRel = "encounter", path = "encounter", exported = false) public interface EncounterRepository extends TransactionalDataRepository, OperatingIndividualScopeAwareRepository, SubjectTreeItemRepository { Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - Date lastModifiedDateTime, Date now, Pageable pageable); + Instant lastModifiedDateTime, Instant now, Pageable pageable); Page findByIndividualAddressLevelVirtualCatchmentsIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - long catchmentId, Date lastModifiedDateTime, Date now, Pageable pageable); + long catchmentId, Instant lastModifiedDateTime, Instant now, Pageable pageable); @Override default Specification syncTypeIdSpecification(Long typeId) { @@ -80,12 +82,13 @@ default Specification withIndividualId(Long id) { default Specification withEncounterEarliestVisitDateTime(DateTime earliestVisitDateTime) { return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> - earliestVisitDateTime == null ? null : cb.equal(root.get("earliestVisitDateTime").as(java.sql.Date.class), earliestVisitDateTime.toDate()); + earliestVisitDateTime == null ? null : cb.equal(root.get("earliestVisitDateTime").as(Instant.class), DateTimeUtil.toInstant(earliestVisitDateTime)); } default Specification withEncounterDateTime(DateTime encounterDateTime) { return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> - encounterDateTime == null ? null : cb.equal(root.get("encounterDateTime").as(java.sql.Date.class), encounterDateTime.toDate()); + encounterDateTime == null ? null : cb.equal(root.get("encounterDateTime").as(Instant.class), + DateTimeUtil.toInstant(encounterDateTime)); } default Specification withNotNullEncounterDateTime() { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/EncounterSearchRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/EncounterSearchRepository.java index 0ee4cbddf..0f1aa06d3 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/EncounterSearchRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/EncounterSearchRepository.java @@ -1,15 +1,14 @@ package org.avni.server.dao; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; +import jakarta.transaction.Transactional; import org.avni.server.dao.search.EncounterSearchQueryBuilder; import org.avni.server.dao.search.SqlQuery; import org.avni.server.domain.Encounter; import org.avni.server.web.api.EncounterSearchRequest; import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.transaction.Transactional; -import java.math.BigInteger; import java.util.List; @Repository @@ -44,8 +43,7 @@ public long getCount(EncounterSearchRequest searchRequest) { query.getParameters().forEach((name, value) -> { sql.setParameter(name, value); }); - BigInteger count = (BigInteger) sql.getSingleResult(); - return count.longValue(); + return (Long) sql.getSingleResult(); } finally { setRoleBackToUser(); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/EndOfLife1EndpointRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/EndOfLife1EndpointRepository.java index 0763ae8b5..52c645528 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/EndOfLife1EndpointRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/EndOfLife1EndpointRepository.java @@ -8,7 +8,7 @@ import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.format.annotation.DateTimeFormat; -import java.util.Date; +import java.time.Instant; /* * This is a marker interface for all the repositories that are used to fetch entities with old endpoints that do not serve new data after configured date. @@ -20,7 +20,7 @@ public interface EndOfLife1EndpointRepository { @RestResource(path = "lastModified", rel = "lastModified") Page findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/EntityApprovalStatusRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/EntityApprovalStatusRepository.java index 7395c946b..3ce640f2a 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/EntityApprovalStatusRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/EntityApprovalStatusRepository.java @@ -1,7 +1,13 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; import org.avni.server.dao.sync.SyncEntityName; -import org.avni.server.domain.*; +import org.avni.server.domain.AddressLevel; +import org.avni.server.domain.CHSEntity; +import org.avni.server.domain.EntityApprovalStatus; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.web.request.EntitySyncStatusContract; import org.joda.time.DateTime; @@ -17,9 +23,8 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; @Repository @@ -30,8 +35,8 @@ public interface EntityApprovalStatusRepository extends TransactionalDataReposit @PreAuthorize("hasAnyAuthority('user')") @RestResource(path = "lastModified", rel = "lastModified") Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); default Page findEntityApprovalStatuses(EntityApprovalStatusSearchParams searchParams, Pageable pageable) { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/FindByLastModifiedDateTime.java b/avni-server-api/src/main/java/org/avni/server/dao/FindByLastModifiedDateTime.java index 76c842c9c..df0b19b16 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/FindByLastModifiedDateTime.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/FindByLastModifiedDateTime.java @@ -1,6 +1,7 @@ package org.avni.server.dao; import org.avni.server.domain.CHSEntity; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -8,19 +9,29 @@ import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.format.annotation.DateTimeFormat; +import java.time.Instant; import java.util.Date; public interface FindByLastModifiedDateTime { @RestResource(path = "lastModified", rel = "lastModified") Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); default Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, + Date lastModifiedDateTime, + Date now, Pageable pageable) { - return findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(CHSEntity.toDate(lastModifiedDateTime), CHSEntity.toDate(now), pageable); + return findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), + DateTimeUtil.toInstant(now), pageable); + } + + default Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( + DateTime lastModifiedDateTime, + DateTime now, + Pageable pageable) { + return findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), + DateTimeUtil.toInstant(now), pageable); } } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/GroupPrivilegeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/GroupPrivilegeRepository.java index a10972cca..80fce3f50 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/GroupPrivilegeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/GroupPrivilegeRepository.java @@ -1,6 +1,7 @@ package org.avni.server.dao; import org.avni.server.domain.accessControl.GroupPrivilege; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -11,7 +12,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -40,14 +41,14 @@ default GroupPrivilege findByNameIgnoreCase(String name) { @RestResource(path = "lastModified", rel = "lastModified") Page findBySubjectTypeIsNotNullAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); - boolean existsByLastModifiedDateTimeGreaterThan(@Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(@Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime); default boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime) { - return existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime == null ? null : lastModifiedDateTime.toDate()); + return existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } default GroupPrivilege saveGroupPrivilege(GroupPrivilege groupPrivilege) { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/GroupSubjectRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/GroupSubjectRepository.java index a93f17aa1..e3992ed11 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/GroupSubjectRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/GroupSubjectRepository.java @@ -1,9 +1,9 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.dao.sync.TransactionDataCriteriaBuilderUtil; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; -import org.joda.time.LocalDate; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; @@ -16,9 +16,8 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.stream.Stream; @@ -28,8 +27,8 @@ public interface GroupSubjectRepository extends TransactionalDataRepository findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); default GroupSubject findByName(String name) { @@ -76,7 +75,7 @@ Page findByMemberSubjectUuidOrderByLastModifiedDateTimeAscIdAsc( "and m.isVoided = false " + "and g.registrationDate between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR g.addressLevel.id in :locationIds)") - Stream findNonVoidedGroupSubjects(Long subjectTypeId, List locationIds, LocalDate startDateTime, LocalDate endDateTime); + Stream findNonVoidedGroupSubjects(Long subjectTypeId, List locationIds, Instant startDateTime, Instant endDateTime); @Query("select gs from GroupSubject gs " + "join gs.groupSubject g " + @@ -84,7 +83,7 @@ Page findByMemberSubjectUuidOrderByLastModifiedDateTimeAscIdAsc( "where g.subjectType.id = :subjectTypeId " + "and g.registrationDate between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR g.addressLevel.id in :locationIds)") - Stream findAllGroupSubjects(Long subjectTypeId, List locationIds, LocalDate startDateTime, LocalDate endDateTime); + Stream findAllGroupSubjects(Long subjectTypeId, List locationIds, Instant startDateTime, Instant endDateTime); default Specification syncStrategySpecification(SyncParameters syncParameters) { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/IdentifierAssignmentRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/IdentifierAssignmentRepository.java index a225fcc5b..f70815a05 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/IdentifierAssignmentRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/IdentifierAssignmentRepository.java @@ -9,16 +9,16 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; @Repository @RepositoryRestResource(collectionResourceRel = "identifierAssignment", path = "identifierAssignment") public interface IdentifierAssignmentRepository extends TransactionalDataRepository, FindByLastModifiedDateTime { - Page findByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEqualsOrderByAssignmentOrderAsc(User currentUser, Date lastModifiedDateTime, String deviceId, Pageable pageable); + Page findByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEqualsOrderByAssignmentOrderAsc(User currentUser, Instant lastModifiedDateTime, String deviceId, Pageable pageable); - Slice findSliceByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEqualsOrderByAssignmentOrderAsc(User currentUser, Date lastModifiedDateTime, String deviceId, Pageable pageable); + Slice findSliceByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEqualsOrderByAssignmentOrderAsc(User currentUser, Instant lastModifiedDateTime, String deviceId, Pageable pageable); Integer countIdentifierAssignmentByIdentifierSourceEqualsAndAssignedToEqualsAndIndividualIsNullAndProgramEnrolmentIsNullAndUsedIsFalseAndDeviceIdEquals(IdentifierSource identifierSource, User assignedTo, String deviceId); - boolean existsByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEquals(User currentUser, Date lastModifiedDateTime, String deviceId); + boolean existsByAssignedToAndLastModifiedDateTimeGreaterThanAndIsVoidedFalseAndIndividualIsNullAndProgramEnrolmentIsNullAndDeviceIdEquals(User currentUser, Instant lastModifiedDateTime, String deviceId); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/IdentifierSourceRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/IdentifierSourceRepository.java index 19946786a..d750cf15d 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/IdentifierSourceRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/IdentifierSourceRepository.java @@ -1,5 +1,5 @@ package org.avni.server.dao; -import java.util.Date; + import org.avni.server.domain.Catchment; import org.avni.server.domain.IdentifierSource; import org.springframework.data.domain.Page; @@ -7,10 +7,11 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.format.annotation.DateTimeFormat; import org.springframework.data.rest.core.annotation.RestResource; +import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.List; @Repository @@ -26,13 +27,13 @@ public interface IdentifierSourceRepository extends ReferenceDataRepository getAllAuthorisedIdentifierSources( @Param("catchment") Catchment catchment, - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); @Query("select isource from IdentifierSource isource " + "where isource.isVoided=false and (catchment is null or (:catchment is not null and catchment = :catchment)) ") List getAllAuthorisedIdentifierSources(@Param("catchment") Catchment catchment); - boolean existsByLastModifiedDateTimeGreaterThan(Date lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ImplementationRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ImplementationRepository.java index a58b79806..606ec24ca 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ImplementationRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ImplementationRepository.java @@ -3,26 +3,25 @@ import org.avni.server.application.projections.ReportingViewProjection; import org.avni.server.domain.Organisation; import org.springframework.data.jpa.repository.Query; -import org.springframework.data.jpa.repository.query.Procedure; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ImplementationRepository extends AvniCrudRepository { - @Procedure(value = "create_view") + @Query(value = "select create_view(:schemaName, :viewName, :sqlQuery)", nativeQuery = true) void createView(String schemaName, String viewName, String sqlQuery); @Query(value = "select viewname, definition from pg_views where schemaname = :schemaName", nativeQuery = true) List getAllViewsInSchema(String schemaName); - @Procedure(value = "drop_view") + @Query(value = "select drop_view(:viewName, :schemaName)", nativeQuery = true) void dropView(String viewName, String schemaName); - @Procedure(value = "create_db_user") + @Query(value = "select create_db_user(:name, :pass)", nativeQuery = true) void createDBUser(String name, String pass); - @Procedure(value = "create_implementation_schema") + @Query(value = "select create_implementation_schema(:schemaName, :dbUser)", nativeQuery = true) void createImplementationSchema(String schemaName, String dbUser); /** diff --git a/avni-server-api/src/main/java/org/avni/server/dao/IndividualRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/IndividualRepository.java index b4e26e3c1..d508e1abf 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/IndividualRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/IndividualRepository.java @@ -1,12 +1,11 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.application.projections.WebSearchResultProjection; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.projection.IndividualWebProjection; import org.avni.server.util.S; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; @@ -16,7 +15,7 @@ import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.stream.Stream; @@ -107,13 +106,13 @@ default Specification getFilterSpecForAddress(String locationName) { "and ind.subjectType.id = :subjectTypeId " + "and ind.registrationDate between :startDateTime and :endDateTime " + "and (coalesce(:locationIds,NULL) is null OR ind.addressLevel.id in :locationIds)") - Stream findNonVoidedIndividuals(Long subjectTypeId, List locationIds, LocalDate startDateTime, LocalDate endDateTime); + Stream findNonVoidedIndividuals(Long subjectTypeId, List locationIds, Instant startDateTime, Instant endDateTime); @Query("select ind from Individual ind " + "where ind.subjectType.id = :subjectTypeId " + "and ind.registrationDate between :startDateTime and :endDateTime " + "and (coalesce(:locationIds,NULL) is null OR ind.addressLevel.id in :locationIds)") - Stream findAllIndividuals(Long subjectTypeId, List locationIds, LocalDate startDateTime, LocalDate endDateTime); + Stream findAllIndividuals(Long subjectTypeId, List locationIds, Instant startDateTime, Instant endDateTime); //group by is added for distinct ind records @Query("select i from Individual i " + @@ -124,7 +123,7 @@ default Specification getFilterSpecForAddress(String locationName) { "and coalesce(enc.encounterDateTime, enc.cancelDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds)" + "group by i.id") - Stream findNonVoidedEncounters(List locationIds, DateTime startDateTime, DateTime endDateTime, Long encounterTypeId); + Stream findNonVoidedEncounters(List locationIds, Instant startDateTime, Instant endDateTime, Long encounterTypeId); @Query("select i from Individual i " + "join i.encounters enc " + @@ -132,7 +131,7 @@ default Specification getFilterSpecForAddress(String locationName) { "and coalesce(enc.encounterDateTime, enc.cancelDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds)" + "group by i.id") - Stream findAllEncounters(List locationIds, DateTime startDateTime, DateTime endDateTime, Long encounterTypeId); + Stream findAllEncounters(List locationIds, Instant startDateTime, Instant endDateTime, Long encounterTypeId); @Query("select i from Individual i where i.uuid =:id or i.legacyId = :id") diff --git a/avni-server-api/src/main/java/org/avni/server/dao/JobStatus.java b/avni-server-api/src/main/java/org/avni/server/dao/JobStatus.java index 550eb0685..e0055f512 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/JobStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/JobStatus.java @@ -1,8 +1,9 @@ package org.avni.server.dao; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + import java.util.Date; @Entity diff --git a/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingRepository.java index fdd90635d..271877a38 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingRepository.java @@ -3,13 +3,14 @@ import org.avni.server.domain.AddressLevel; import org.avni.server.domain.ParentLocationMapping; import org.avni.server.framework.security.UserContextHolder; -import org.springframework.data.domain.Pageable; +import org.avni.server.util.DateTimeUtil; import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -28,8 +29,8 @@ public interface LocationMappingRepository extends ReferenceDataRepository getSyncResults( long catchmentId, - Date lastModifiedDateTime, - Date now, + Instant lastModifiedDateTime, + Instant now, long organisationId, Pageable pageable ); @@ -42,17 +43,17 @@ Page getSyncResults( " inner join location_location_mapping llm on al1.id = llm.location_id\n" + "where c.id = :catchmentId \n" + " and llm.last_modified_date_time > :lastModifiedDateTime ;", nativeQuery = true) - Long getChangedRowCount(long catchmentId, Date lastModifiedDateTime); + Long getChangedRowCount(long catchmentId, Instant lastModifiedDateTime); @Override default Page getSyncResults(SyncParameters syncParameters) { Long organisationId = UserContextHolder.getOrganisation().getId(); - return getSyncResults(syncParameters.getCatchment().getId(), syncParameters.getLastModifiedDateTime().toDate(), syncParameters.getNow().toDate(), organisationId, syncParameters.getPageable()); + return getSyncResults(syncParameters.getCatchment().getId(), DateTimeUtil.toInstant(syncParameters.getLastModifiedDateTime()), DateTimeUtil.toInstant(syncParameters.getNow()), organisationId, syncParameters.getPageable()); } @Override default boolean isEntityChanged(SyncParameters syncParameters) { - return getChangedRowCount(syncParameters.getCatchment().getId(), syncParameters.getLastModifiedDateTime().toDate()) > 0; + return getChangedRowCount(syncParameters.getCatchment().getId(), DateTimeUtil.toInstant(syncParameters.getLastModifiedDateTime())) > 0; } default ParentLocationMapping findByName(String name) { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingSyncRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingSyncRepository.java index 1610ed038..645d0101f 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingSyncRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/LocationMappingSyncRepository.java @@ -1,14 +1,12 @@ package org.avni.server.dao; -import org.avni.server.domain.AddressLevel; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.avni.server.domain.ParentLocationMapping; import org.springframework.data.domain.Page; import org.springframework.data.domain.Slice; import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; - /** * LocationSyncRepository uses the postgres @> keyword for sync, which does not index well and creates poor plans. * This is a performance enhancement that temporarily switches out the role of the user before running this query. diff --git a/avni-server-api/src/main/java/org/avni/server/dao/LocationRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/LocationRepository.java index 45bbe7b57..6da75643f 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/LocationRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/LocationRepository.java @@ -1,11 +1,14 @@ package org.avni.server.dao; +import jakarta.persistence.QueryHint; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.projections.CatchmentAddressProjection; import org.avni.server.application.projections.LocationProjection; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.AddressLevelType; import org.avni.server.domain.Catchment; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; @@ -16,9 +19,10 @@ import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; -import javax.persistence.QueryHint; -import javax.validation.constraints.NotNull; -import java.util.*; +import java.time.Instant; +import java.util.Collection; +import java.util.List; +import java.util.Optional; @Repository @RepositoryRestResource(collectionResourceRel = "locations", path = "locations") @@ -41,7 +45,7 @@ public interface LocationRepository extends ReferenceDataRepository getSyncResults(long catchmentId, Date lastModifiedDateTime, Date now, long organisationId, Pageable pageable); + Page getSyncResults(long catchmentId, Instant lastModifiedDateTime, Instant now, long organisationId, Pageable pageable); @Query(value = "select count(*)\n" + "from catchment c\n" + @@ -50,7 +54,7 @@ public interface LocationRepository extends ReferenceDataRepository al1.lineage \n" + "where c.id = :catchmentId\n" + " and al1.last_modified_date_time > :lastModifiedDateTime\n", nativeQuery = true) - Long getChangedRowCount(long catchmentId, Date lastModifiedDateTime); + Long getChangedRowCount(long catchmentId, Instant lastModifiedDateTime); AddressLevel findByTitleAndCatchmentsUuid(String title, String uuid); @@ -95,19 +99,20 @@ public interface LocationRepository extends ReferenceDataRepository findByCatchments(Catchment catchment); - Page findByLastModifiedDateTimeAfterAndTypeIn(Date lastModifiedDateTime, Collection<@NotNull AddressLevelType> type, Pageable pageable); + Page findByLastModifiedDateTimeAfterAndTypeIn(Instant lastModifiedDateTime, Collection<@NotNull AddressLevelType> type, Pageable pageable); - boolean existsByLastModifiedDateTimeAfterAndTypeIn(Date lastModifiedDateTime, Collection<@NotNull AddressLevelType> type); + boolean existsByLastModifiedDateTimeAfterAndTypeIn(Instant lastModifiedDateTime, Collection<@NotNull AddressLevelType> type); @Override default Page getSyncResults(SyncParameters syncParameters) { Long organisationId = UserContextHolder.getOrganisation().getId(); - return getSyncResults(syncParameters.getCatchment().getId(), syncParameters.getLastModifiedDateTime().toDate(), syncParameters.getNow().toDate(), organisationId, syncParameters.getPageable()); + return getSyncResults(syncParameters.getCatchment().getId(), DateTimeUtil.toInstant(syncParameters.getLastModifiedDateTime()), + DateTimeUtil.toInstant(syncParameters.getNow()), organisationId, syncParameters.getPageable()); } @Override default boolean isEntityChanged(SyncParameters syncParameters) { - return getChangedRowCount(syncParameters.getCatchment().getId(), syncParameters.getLastModifiedDateTime().toDate()) > 0; + return getChangedRowCount(syncParameters.getCatchment().getId(), DateTimeUtil.toInstant(syncParameters.getLastModifiedDateTime())) > 0; } default AddressLevel findByName(String name) { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/LocationSyncRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/LocationSyncRepository.java index 923f9ff96..9148311b4 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/LocationSyncRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/LocationSyncRepository.java @@ -1,13 +1,12 @@ package org.avni.server.dao; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.avni.server.domain.AddressLevel; import org.springframework.data.domain.Page; import org.springframework.data.domain.Slice; import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; - @Repository public class LocationSyncRepository extends RoleSwitchableRepository implements SyncableRepository { private final LocationRepository locationRepository; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/NewsRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/NewsRepository.java index 6374095e1..66fe2a8bb 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/NewsRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/NewsRepository.java @@ -7,7 +7,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -18,10 +18,10 @@ public interface NewsRepository extends TransactionalDataRepository, FindB List findByPublishedDateNotNullAndIsVoidedFalse(); - Page findByPublishedDateNotNullAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(Date lastModifiedDateTime, Date now, Pageable pageable); + Page findByPublishedDateNotNullAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(Instant lastModifiedDateTime, Instant now, Pageable pageable); - Slice findSliceByPublishedDateNotNullAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(Date lastModifiedDateTime, Date now, Pageable pageable); + Slice findSliceByPublishedDateNotNullAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(Instant lastModifiedDateTime, Instant now, Pageable pageable); - boolean existsByPublishedDateNotNullAndLastModifiedDateTimeGreaterThan(Date lastModifiedDateTime); + boolean existsByPublishedDateNotNullAndLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/OperatingIndividualScopeAwareRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/OperatingIndividualScopeAwareRepository.java index dc76324e9..d9abb99ab 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/OperatingIndividualScopeAwareRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/OperatingIndividualScopeAwareRepository.java @@ -1,11 +1,16 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.application.Subject; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.dao.sync.TransactionDataCriteriaBuilderUtil; -import org.avni.server.domain.*; +import org.avni.server.domain.CHSEntity; +import org.avni.server.domain.JsonObject; +import org.avni.server.domain.SubjectType; +import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.exception.ConstraintViolationExceptionAcrossOrganisations; +import org.avni.server.util.DateTimeUtil; import org.avni.server.util.JsonObjectUtil; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataIntegrityViolationException; @@ -15,7 +20,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -61,7 +66,7 @@ default Specification getAuditSpecification(SyncParameters syncParameters) { return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> { List predicates = new ArrayList<>(); if (syncParameters.getSubjectType() == null || !syncParameters.getSubjectType().isDirectlyAssignable()) - predicates.add(cb.between(root.get("lastModifiedDateTime"), cb.literal(lastModifiedDateTime), cb.literal(now))); + predicates.add(cb.between(root.get("lastModifiedDateTime"), cb.literal(DateTimeUtil.toInstant(lastModifiedDateTime)), cb.literal(DateTimeUtil.toInstant(now)))); query.orderBy(cb.asc(root.get("lastModifiedDateTime")), cb.asc(root.get("id"))); return cb.and(predicates.toArray(new Predicate[0])); }; @@ -79,7 +84,7 @@ default Specification syncEntityChangedAuditSpecification(SyncParameters sync Date lastModifiedDateTime = syncParameters.getLastModifiedDateTime().toDate(); return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> { List predicates = new ArrayList<>(); - predicates.add(cb.greaterThan(root.get("lastModifiedDateTime"), cb.literal(lastModifiedDateTime))); + predicates.add(cb.greaterThan(root.get("lastModifiedDateTime"), cb.literal(DateTimeUtil.toInstant(lastModifiedDateTime)))); return cb.and(predicates.toArray(new Predicate[0])); }; } @@ -130,9 +135,9 @@ default void addSyncStrategyPredicate predicates.add(cb.equal(userSubjectAssignmentJoin.get("isVoided"), false)); Date lastModifiedDateTime = syncParameters.getLastModifiedDateTime().toDate(); - Path lastModifiedDateTimePath = userSubjectAssignmentJoin.get("lastModifiedDateTime"); + Path lastModifiedDateTimePath = userSubjectAssignmentJoin.get("lastModifiedDateTime"); Date now = syncParameters.getNow().toDate(); - predicates.add(cb.between(lastModifiedDateTimePath, cb.literal(lastModifiedDateTime), cb.literal(now))); + predicates.add(cb.between(lastModifiedDateTimePath, cb.literal(DateTimeUtil.toInstant(lastModifiedDateTime)), cb.literal(DateTimeUtil.toInstant(now)))); query.orderBy(cb.asc(lastModifiedDateTimePath), cb.asc(userSubjectAssignmentJoin.get("id"))); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/OperationalEncounterTypeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/OperationalEncounterTypeRepository.java index cc056fd27..76abbd99a 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/OperationalEncounterTypeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/OperationalEncounterTypeRepository.java @@ -11,7 +11,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -20,8 +20,8 @@ public interface OperationalEncounterTypeRepository extends ImplReferenceDataRep @RestResource(path = "lastModified", rel = "lastModified") @Query("select oet from OperationalEncounterType oet where oet.lastModifiedDateTime between :lastModifiedDateTime and :now or oet.encounterType.lastModifiedDateTime between :lastModifiedDateTime and :now order by CASE WHEN oet.encounterType.lastModifiedDateTime > oet.lastModifiedDateTime THEN oet.encounterType.lastModifiedDateTime ELSE oet.lastModifiedDateTime END") Page findByLastModifiedDateTimeIsBetweenOrEncounterTypeLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); OperationalEncounterType findByEncounterTypeAndOrganisationId(EncounterType encounterType, long organisationId); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/OperationalProgramRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/OperationalProgramRepository.java index 7193c54a6..b0ed0a533 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/OperationalProgramRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/OperationalProgramRepository.java @@ -11,7 +11,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -19,7 +19,7 @@ public interface OperationalProgramRepository extends ImplReferenceDataRepository { @RestResource(path = "lastModified", rel = "lastModified") @Query("select op from OperationalProgram op where op.lastModifiedDateTime > :lastModifiedDateTime or op.program.lastModifiedDateTime > :lastModifiedDateTime order by CASE WHEN op.program.lastModifiedDateTime > op.lastModifiedDateTime THEN op.program.lastModifiedDateTime ELSE op.lastModifiedDateTime END") - Page findByLastModifiedDateTimeGreaterThanOrProgramLastModifiedDateTimeGreaterThanOrderByLastModifiedDateTimeAscIdAsc(@Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, Pageable pageable); + Page findByLastModifiedDateTimeGreaterThanOrProgramLastModifiedDateTimeGreaterThanOrderByLastModifiedDateTimeAscIdAsc(@Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, Pageable pageable); OperationalProgram findByProgramAndOrganisationId(Program program, long organisationId); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/OperationalSubjectTypeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/OperationalSubjectTypeRepository.java index a80adaef5..a079f1f37 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/OperationalSubjectTypeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/OperationalSubjectTypeRepository.java @@ -10,8 +10,8 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.List; -import java.util.Date; @Repository @RepositoryRestResource(collectionResourceRel = "operationalSubjectType", path = "operationalSubjectType") @@ -19,8 +19,8 @@ public interface OperationalSubjectTypeRepository extends ImplReferenceDataRepos @RestResource(path = "lastModified", rel = "lastModified") @Query("select ost from OperationalSubjectType ost where ost.lastModifiedDateTime between :lastModifiedDateTime and :now or ost.subjectType.lastModifiedDateTime between :lastModifiedDateTime and :now order by CASE WHEN ost.subjectType.lastModifiedDateTime > ost.lastModifiedDateTime THEN ost.subjectType.lastModifiedDateTime ELSE ost.lastModifiedDateTime END") Page findByLastModifiedDateTimeIsBetweenOrSubjectTypeLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); @Query("select s.name from OperationalSubjectType s where s.isVoided = false") diff --git a/avni-server-api/src/main/java/org/avni/server/dao/PlatformTranslationRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/PlatformTranslationRepository.java index a274e6e57..8d9b61407 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/PlatformTranslationRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/PlatformTranslationRepository.java @@ -8,6 +8,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.Date; @Repository @@ -19,10 +20,10 @@ public interface PlatformTranslationRepository extends CustomCHSJpaRepository findByPlatformAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( Platform platform, - Date lastModifiedDateTime, - Date now, + Instant lastModifiedDateTime, + Instant now, Pageable pageable); - boolean existsByPlatformAndLastModifiedDateTimeGreaterThan(Platform platform, Date lastModifiedDateTime); + boolean existsByPlatformAndLastModifiedDateTimeGreaterThan(Platform platform, Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/PrivilegeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/PrivilegeRepository.java index be5799e03..42ff5e2fb 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/PrivilegeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/PrivilegeRepository.java @@ -12,6 +12,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.Collections; import java.util.List; @@ -20,15 +21,15 @@ public interface PrivilegeRepository extends AvniJpaRepository { @RestResource(path = "lastModified", rel = "lastModified") Page findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); Privilege findByUuid(String uuid); List findAllByIsVoidedFalse(); - boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); Privilege findByType(PrivilegeType privilegeType); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ProgramEncounterRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ProgramEncounterRepository.java index 00ced93fb..cce1e48c9 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ProgramEncounterRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ProgramEncounterRepository.java @@ -2,6 +2,7 @@ import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -13,7 +14,9 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import jakarta.persistence.criteria.*; + +import java.time.Instant; import java.util.Date; import java.util.Calendar; import java.util.List; @@ -26,7 +29,7 @@ public interface ProgramEncounterRepository extends TransactionalDataRepository, FindByLastModifiedDateTime, OperatingIndividualScopeAwareRepository, SubjectTreeItemRepository { Page findByProgramEnrolmentIndividualAddressLevelVirtualCatchmentsIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - long catchmentId, Date lastModifiedDateTime, Date now, Pageable pageable); + long catchmentId, Instant lastModifiedDateTime, Instant now, Pageable pageable); @Override default Specification syncTypeIdSpecification(Long typeId) { @@ -50,7 +53,7 @@ default boolean isEntityChanged(SyncParameters syncParameters){ "group by enc.program_enrolment_id " + "order by count desc " + "limit 1", nativeQuery = true) - Long getMaxProgramEncounterCountBetween(String programEncounterTypeUUID, Calendar startDate, Calendar endDate); + Long getMaxProgramEncounterCountBetween(String programEncounterTypeUUID, Instant startDate, Instant endDate); @Query(value = "select count(enc.id) as count " + "from program_encounter enc " + @@ -63,7 +66,7 @@ default boolean isEntityChanged(SyncParameters syncParameters){ default Long getMaxProgramEncounterCount(String encounterTypeUUID, Calendar startDate, Calendar endDate) { Long aLong = startDate == null ? getMaxProgramEncounterCount(encounterTypeUUID) : - getMaxProgramEncounterCountBetween(encounterTypeUUID, startDate, endDate); + getMaxProgramEncounterCountBetween(encounterTypeUUID, DateTimeUtil.toInstant(startDate), DateTimeUtil.toInstant(endDate)); return aLong == null ? 0 : aLong; } @@ -82,12 +85,14 @@ default Specification withProgramEncounterId(Long id) { default Specification withProgramEncounterEarliestVisitDateTime(DateTime earliestVisitDateTime) { return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> - earliestVisitDateTime == null ? null : cb.equal(root.get("earliestVisitDateTime").as(java.sql.Date.class), earliestVisitDateTime.toDate()); + earliestVisitDateTime == null ? null : cb.equal(root.get("earliestVisitDateTime").as(Instant.class), + DateTimeUtil.toInstant(earliestVisitDateTime)); } default Specification withProgramEncounterDateTime(DateTime encounterDateTime) { return (Root root, CriteriaQuery query, CriteriaBuilder cb) -> - encounterDateTime == null ? null : cb.equal(root.get("encounterDateTime").as(java.sql.Date.class), encounterDateTime.toDate()); + encounterDateTime == null ? null : cb.equal(root.get("encounterDateTime").as(Instant.class), + DateTimeUtil.toInstant(encounterDateTime)); } default Specification withNotNullEncounterDateTime() { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ProgramEnrolmentRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ProgramEnrolmentRepository.java index 625bef1ba..82606231a 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ProgramEnrolmentRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ProgramEnrolmentRepository.java @@ -1,10 +1,12 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.ProgramEnrolment; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.projection.SearchSubjectEnrolledProgram; -import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; @@ -14,12 +16,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import java.util.Date; +import java.time.Instant; import java.util.List; import java.util.stream.Stream; @@ -37,14 +35,14 @@ public interface ProgramEnrolmentRepository extends TransactionalDataRepository< "and i.isVoided = false " + "and coalesce(enl.enrolmentDateTime, enl.programExitDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds)") - Stream findNonVoidedEnrolments(Long programId, List locationIds, DateTime startDateTime, DateTime endDateTime); + Stream findNonVoidedEnrolments(Long programId, List locationIds, Instant startDateTime, Instant endDateTime); @Query("select enl from ProgramEnrolment enl " + "join enl.individual i " + "where enl.program.id = :programId " + "and coalesce(enl.enrolmentDateTime, enl.programExitDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds)") - Stream findAllEnrolments(Long programId, List locationIds, DateTime startDateTime, DateTime endDateTime); + Stream findAllEnrolments(Long programId, List locationIds, Instant startDateTime, Instant endDateTime); //group by is added for distinct enl records @Query("select enl from ProgramEnrolment enl " + @@ -58,7 +56,7 @@ public interface ProgramEnrolmentRepository extends TransactionalDataRepository< "and coalesce(enc.encounterDateTime, enc.cancelDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds) " + "group by enl.id") - Stream findNonVoidedProgramEncounters(List locationIds, DateTime startDateTime, DateTime endDateTime, Long encounterTypeId, Long programId); + Stream findNonVoidedProgramEncounters(List locationIds, Instant startDateTime, Instant endDateTime, Long encounterTypeId, Long programId); @Query("select enl from ProgramEnrolment enl " + "join enl.programEncounters enc " + @@ -68,11 +66,11 @@ public interface ProgramEnrolmentRepository extends TransactionalDataRepository< "and coalesce(enc.encounterDateTime, enc.cancelDateTime) between :startDateTime and :endDateTime " + "and (coalesce(:locationIds, null) is null OR i.addressLevel.id in :locationIds) " + "group by enl.id") - Stream findAllProgramEncounters(List locationIds, DateTime startDateTime, DateTime endDateTime, Long encounterTypeId, Long programId); + Stream findAllProgramEncounters(List locationIds, Instant startDateTime, Instant endDateTime, Long encounterTypeId, Long programId); Page findByLastModifiedDateTimeGreaterThanAndLastModifiedDateTimeLessThanAndProgramNameOrderByLastModifiedDateTimeAscIdAsc( - Date lastModifiedDateTime, - Date now, + Instant lastModifiedDateTime, + Instant now, String program, Pageable pageable); @@ -88,8 +86,8 @@ Page findByProgramNameAndIndividualUuidOrderByLastModifiedDate ProgramEnrolment findByLegacyId(String id); Page findByLastModifiedDateTimeGreaterThanAndLastModifiedDateTimeLessThanOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); @Override @@ -106,7 +104,6 @@ default boolean isEntityChanged(SyncParameters syncParameters) { ) > 0; } - @Transactional @Modifying(clearAutomatically = true) @Query(value = "update program_enrolment enl set " + "address_id = :addressId, " + diff --git a/avni-server-api/src/main/java/org/avni/server/dao/ResetSyncRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/ResetSyncRepository.java index ada64321b..e445eaeca 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/ResetSyncRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/ResetSyncRepository.java @@ -6,15 +6,15 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; @Repository public interface ResetSyncRepository extends TransactionalDataRepository { Page findAllByUserIsNullOrUserAndLastModifiedDateTimeBetweenOrderByLastModifiedDateTimeAscIdAsc( User user, - Date lastModifiedDateTime, - Date now, + Instant lastModifiedDateTime, + Instant now, Pageable pageable ); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/RoleSwitchableRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/RoleSwitchableRepository.java index 8db61ed58..28ca130d7 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/RoleSwitchableRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/RoleSwitchableRepository.java @@ -1,11 +1,10 @@ package org.avni.server.dao; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.avni.server.framework.security.UserContextHolder; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - public abstract class RoleSwitchableRepository { @PersistenceContext protected EntityManager entityManager; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/RuleDependencyRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/RuleDependencyRepository.java index 0031219a7..50d52d116 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/RuleDependencyRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/RuleDependencyRepository.java @@ -9,7 +9,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; @Repository @RepositoryRestResource(collectionResourceRel = "ruleDependency", path = "ruleDependency") @@ -18,8 +18,8 @@ public interface RuleDependencyRepository extends ImplReferenceDataRepository findByLastModifiedDateTimeIsBetween( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date now, Pageable pageable); + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); default RuleDependency findByName(String name) { throw new UnsupportedOperationException("No field 'name' in RuleDependency"); @@ -29,6 +29,6 @@ default RuleDependency findByNameIgnoreCase(String name) { throw new UnsupportedOperationException("No field 'name' in RuleDependency"); } - boolean existsByLastModifiedDateTimeGreaterThan(Date lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/StandardReportCardTypeRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/StandardReportCardTypeRepository.java index 9c29c4126..b29f7f0e9 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/StandardReportCardTypeRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/StandardReportCardTypeRepository.java @@ -2,8 +2,6 @@ import org.avni.server.domain.StandardReportCardType; import org.avni.server.domain.StandardReportCardTypeType; -import org.avni.server.domain.app.dashboard.DashboardFilter; -import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; @@ -12,6 +10,7 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.List; import java.util.Set; @@ -24,11 +23,11 @@ public interface StandardReportCardTypeRepository extends AvniJpaRepository findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, + @Param("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant lastModifiedDateTime, + @Param("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant now, Pageable pageable); - boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); List findAllByTypeIn(Set defaultDashboardStandardCardTypeTypes); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/SubjectMigrationRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/SubjectMigrationRepository.java index 5c5bd0356..ea6214570 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/SubjectMigrationRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/SubjectMigrationRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.persistence.criteria.*; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.util.JsonObjectUtil; @@ -8,7 +9,6 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/SubjectSearchRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/SubjectSearchRepository.java index 19993a203..7e6c79289 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/SubjectSearchRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/SubjectSearchRepository.java @@ -1,21 +1,20 @@ package org.avni.server.dao; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; +import jakarta.transaction.Transactional; import org.avni.server.dao.search.SearchBuilder; import org.avni.server.dao.search.SqlQuery; import org.avni.server.domain.SubjectType; import org.avni.server.web.request.webapp.search.SubjectSearchRequest; -import org.hibernate.query.internal.NativeQueryImpl; +import org.hibernate.query.sql.internal.NativeQueryImpl; import org.hibernate.transform.AliasToEntityMapResultTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.transaction.Transactional; -import java.math.BigInteger; import java.util.List; import java.util.Map; @@ -53,7 +52,7 @@ public List> search(SubjectSearchRequest searchRequest, Sear } @Transactional - public BigInteger getTotalCount(SubjectSearchRequest searchRequest, SearchBuilder searchBuilder) { + public Long getTotalCount(SubjectSearchRequest searchRequest, SearchBuilder searchBuilder) { SubjectType subjectType = StringUtils.isEmpty(searchRequest.getSubjectType()) ? null : subjectTypeRepository.findByUuid(searchRequest.getSubjectType()); SqlQuery query = searchBuilder.getSQLCountQuery(searchRequest, subjectType); try { @@ -63,7 +62,7 @@ public BigInteger getTotalCount(SubjectSearchRequest searchRequest, SearchBuilde sql.setParameter(name, value); }); - return (BigInteger) sql.getSingleResult(); + return (Long) sql.getSingleResult(); } finally { setRoleBackToUser(); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/SyncTelemetryRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/SyncTelemetryRepository.java index fc2e77654..188c6ce3a 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/SyncTelemetryRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/SyncTelemetryRepository.java @@ -1,12 +1,12 @@ package org.avni.server.dao; import org.avni.server.domain.SyncTelemetry; -import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.List; @Repository @@ -16,7 +16,7 @@ public interface SyncTelemetryRepository extends AvniJpaRepository findAllByUserIdInOrderByIdDesc(List userIds, Pageable pageable); - Page findAllBySyncStartTimeBetweenOrderByIdDesc(DateTime startDate, DateTime endDate, Pageable pageable); + Page findAllBySyncStartTimeBetweenOrderByIdDesc(Instant startDate, Instant endDate, Pageable pageable); - Page findAllByUserIdInAndSyncStartTimeBetweenOrderByIdDesc(List userIds, DateTime startDate, DateTime endDate, Pageable pageable); + Page findAllByUserIdInAndSyncStartTimeBetweenOrderByIdDesc(List userIds, Instant startDate, Instant endDate, Pageable pageable); } diff --git a/avni-server-api/src/main/java/org/avni/server/dao/UserGroupRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/UserGroupRepository.java index d6c14d170..b3e914a21 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/UserGroupRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/UserGroupRepository.java @@ -1,8 +1,7 @@ package org.avni.server.dao; -import java.util.Date; -import org.avni.server.domain.User; import org.avni.server.domain.Group; +import org.avni.server.domain.User; import org.avni.server.domain.UserGroup; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -10,9 +9,9 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Repository; +import java.time.Instant; import java.util.List; @@ -22,8 +21,8 @@ public interface UserGroupRepository extends ReferenceDataRepository Page findByUserIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( Long userId, - Date lastModifiedDateTime, - Date now, + Instant lastModifiedDateTime, + Instant now, Pageable pageable); default UserGroup findByName(String name) { @@ -47,7 +46,7 @@ default UserGroup findByNameIgnoreCase(String name) { @Query("DELETE FROM UserGroup ug where ug.group in (:groups)") int deleteAllByGroupIn(List groups); - boolean existsByUserIdAndLastModifiedDateTimeGreaterThan(Long userId, Date lastModifiedDateTime); + boolean existsByUserIdAndLastModifiedDateTimeGreaterThan(Long userId, Instant lastModifiedDateTime); List findByUserAndGroupHasAllPrivilegesTrueAndIsVoidedFalse(User user); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/UserRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/UserRepository.java index f6e955c13..467ccda3f 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/UserRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/UserRepository.java @@ -1,10 +1,11 @@ package org.avni.server.dao; +import jakarta.persistence.EntityNotFoundException; +import jakarta.persistence.QueryHint; import org.avni.server.domain.Catchment; import org.avni.server.domain.User; import org.avni.server.projection.UserWebProjection; import org.avni.server.web.request.api.RequestUtils; -import org.joda.time.DateTime; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -15,8 +16,7 @@ import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.stereotype.Repository; -import javax.persistence.EntityNotFoundException; -import javax.persistence.QueryHint; +import java.time.Instant; import java.util.List; import java.util.Optional; @@ -25,7 +25,6 @@ @Repository @RepositoryRestResource(collectionResourceRel = "user", path = "user") public interface UserRepository extends AvniJpaRepository, JpaSpecificationExecutor { - @QueryHints({@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")}) User findByUsername(String username); @@ -62,7 +61,7 @@ Page findByOrganisationIdAndIsVoidedFalse(@Param("organisationId") Long or "(((:organisationIds) is not null and u.organisationId in (:organisationIds) and u.isOrgAdmin = true) or aa.account.id in (:accountIds))") User getOne(Long id, List accountIds, List organisationIds); - boolean existsByLastModifiedDateTimeGreaterThan(DateTime lastModifiedDateTime); + boolean existsByLastModifiedDateTimeGreaterThan(Instant lastModifiedDateTime); List findByCatchment_IdInAndIsVoidedFalse(List catchmentIds); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/UserSubjectAssignmentRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/UserSubjectAssignmentRepository.java index ed6962a3f..dc318f8ad 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/UserSubjectAssignmentRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/UserSubjectAssignmentRepository.java @@ -9,7 +9,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; import java.util.List; @Repository @@ -22,19 +22,19 @@ public interface UserSubjectAssignmentRepository extends ReferenceDataRepository List findUserSubjectAssignmentBySubject_IdIn(List subjectIds); - boolean existsByUserAndIsVoidedTrueAndLastModifiedDateTimeGreaterThan(User user, Date lastModifiedDateTime); + boolean existsByUserAndIsVoidedTrueAndLastModifiedDateTimeGreaterThan(User user, Instant lastModifiedDateTime); Page findByUserAndIsVoidedTrueAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( User user, - Date lastModifiedDate, - Date now, + Instant lastModifiedDate, + Instant now, Pageable pageable ); Slice findSliceByUserAndIsVoidedTrueAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( User user, - Date lastModifiedDate, - Date now, + Instant lastModifiedDate, + Instant now, Pageable pageable ); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/individualRelationship/IndividualRelationshipRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/individualRelationship/IndividualRelationshipRepository.java index 283d6e85b..96a47fd2d 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/individualRelationship/IndividualRelationshipRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/individualRelationship/IndividualRelationshipRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao.individualRelationship; +import jakarta.persistence.criteria.*; import org.avni.server.dao.*; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.Individual; @@ -9,16 +10,14 @@ import org.avni.server.framework.security.UserContextHolder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Set; @@ -28,7 +27,7 @@ @RepositoryRestResource(collectionResourceRel = "individualRelationship", path = "individualRelationship", exported = false) public interface IndividualRelationshipRepository extends TransactionalDataRepository, FindByLastModifiedDateTime, OperatingIndividualScopeAwareRepository, SubjectTreeItemRepository { Page findByIndividualaAddressLevelVirtualCatchmentsIdAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc( - long catchmentId, Date lastModifiedDateTime, Date now, Pageable pageable); + long catchmentId, Instant lastModifiedDateTime, Instant now, Pageable pageable); @Query(value = "select ir from IndividualRelationship ir where ir.individuala = :individual or ir.individualB = :individual") Set findByIndividual(Individual individual); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/metabase/MetabaseConnector.java b/avni-server-api/src/main/java/org/avni/server/dao/metabase/MetabaseConnector.java index a644aea48..b8356bf86 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/metabase/MetabaseConnector.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/metabase/MetabaseConnector.java @@ -23,7 +23,7 @@ public class MetabaseConnector { protected String apiKey; public MetabaseConnector(RestTemplateBuilder restTemplateBuilder) { - this.restTemplate = restTemplateBuilder.additionalCustomizers(new RestTemplateStandardCookieCustomizer()).build(); + this.restTemplate = restTemplateBuilder.build(); } protected HttpHeaders getHeaders() { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/metabase/RestTemplateStandardCookieCustomizer.java b/avni-server-api/src/main/java/org/avni/server/dao/metabase/RestTemplateStandardCookieCustomizer.java deleted file mode 100644 index b494eaa28..000000000 --- a/avni-server-api/src/main/java/org/avni/server/dao/metabase/RestTemplateStandardCookieCustomizer.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.avni.server.dao.metabase; - -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.HttpClients; -import org.springframework.boot.web.client.RestTemplateCustomizer; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -public class RestTemplateStandardCookieCustomizer implements RestTemplateCustomizer { - - @Override - public void customize(final RestTemplate restTemplate) { - final HttpClient httpClient = HttpClients.custom() - .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()) - .build(); - restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); - } -} \ No newline at end of file diff --git a/avni-server-api/src/main/java/org/avni/server/dao/program/SubjectProgramEligibilityRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/program/SubjectProgramEligibilityRepository.java index b09d0efda..6abdb3cd8 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/program/SubjectProgramEligibilityRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/program/SubjectProgramEligibilityRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao.program; +import jakarta.persistence.criteria.*; import org.avni.server.dao.OperatingIndividualScopeAwareRepository; import org.avni.server.dao.SubjectTreeItemRepository; import org.avni.server.dao.SyncParameters; @@ -16,7 +17,6 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/dao/sync/TransactionDataCriteriaBuilderUtil.java b/avni-server-api/src/main/java/org/avni/server/dao/sync/TransactionDataCriteriaBuilderUtil.java index 2787d93a3..a3f29b456 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/sync/TransactionDataCriteriaBuilderUtil.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/sync/TransactionDataCriteriaBuilderUtil.java @@ -1,10 +1,9 @@ package org.avni.server.dao.sync; +import jakarta.persistence.criteria.From; +import jakarta.persistence.criteria.Join; import org.avni.server.dao.SyncParameters; -import javax.persistence.criteria.From; -import javax.persistence.criteria.Join; - public class TransactionDataCriteriaBuilderUtil { public static Join joinUserSubjectAssignment(From fromSubject) { return fromSubject.join("userSubjectAssignments"); diff --git a/avni-server-api/src/main/java/org/avni/server/dao/task/TaskRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/task/TaskRepository.java index 01eee2017..f355048de 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/task/TaskRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/task/TaskRepository.java @@ -1,5 +1,6 @@ package org.avni.server.dao.task; +import jakarta.persistence.criteria.*; import org.avni.server.dao.FindByLastModifiedDateTime; import org.avni.server.dao.TransactionalDataRepository; import org.avni.server.domain.Concept; @@ -16,9 +17,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.stereotype.Repository; -import javax.persistence.criteria.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.Map; @@ -26,11 +26,11 @@ @RepositoryRestResource(collectionResourceRel = "task", path = "task", exported = false) public interface TaskRepository extends TransactionalDataRepository, FindByLastModifiedDateTime { - Page findByAssignedToAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Date lastModifiedDateTime, Date now, Pageable pageable); + Page findByAssignedToAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Instant lastModifiedDateTime, Instant now, Pageable pageable); - Slice findSliceByAssignedToAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Date lastModifiedDateTime, Date now, Pageable pageable); + Slice findSliceByAssignedToAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Instant lastModifiedDateTime, Instant now, Pageable pageable); - boolean existsByAssignedToAndLastModifiedDateTimeGreaterThan(User user, Date lastModifiedDateTime); + boolean existsByAssignedToAndLastModifiedDateTimeGreaterThan(User user, Instant lastModifiedDateTime); default Page search(TaskSearchCriteria searchCriteria, boolean isUnassigned, Pageable pageable) { Specification spec = (Root root, CriteriaQuery query, CriteriaBuilder cb) -> { diff --git a/avni-server-api/src/main/java/org/avni/server/dao/task/TaskUnAssignmentRepository.java b/avni-server-api/src/main/java/org/avni/server/dao/task/TaskUnAssignmentRepository.java index 8acfcb75a..2540471ac 100644 --- a/avni-server-api/src/main/java/org/avni/server/dao/task/TaskUnAssignmentRepository.java +++ b/avni-server-api/src/main/java/org/avni/server/dao/task/TaskUnAssignmentRepository.java @@ -9,14 +9,14 @@ import org.springframework.data.domain.Slice; import org.springframework.stereotype.Repository; -import java.util.Date; +import java.time.Instant; @Repository public interface TaskUnAssignmentRepository extends TransactionalDataRepository, FindByLastModifiedDateTime { - Page findByUnassignedUserAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Date lastModifiedDateTime, Date now, Pageable pageable); + Page findByUnassignedUserAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Instant lastModifiedDateTime, Instant now, Pageable pageable); - Slice findSliceByUnassignedUserAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Date lastModifiedDateTime, Date now, Pageable pageable); + Slice findSliceByUnassignedUserAndLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(User user, Instant lastModifiedDateTime, Instant now, Pageable pageable); - boolean existsByUnassignedUserAndLastModifiedDateTimeGreaterThan(User user, Date lastModifiedDateTime); + boolean existsByUnassignedUserAndLastModifiedDateTimeGreaterThan(User user, Instant lastModifiedDateTime); } diff --git a/avni-server-api/src/main/java/org/avni/server/domain/AbstractEncounter.java b/avni-server-api/src/main/java/org/avni/server/domain/AbstractEncounter.java index 30291df73..f562a16fe 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/AbstractEncounter.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/AbstractEncounter.java @@ -1,13 +1,17 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.common.dbSchema.ColumnNames; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; import org.avni.server.geo.Point; +import org.avni.server.geo.PointType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.Objects; @MappedSuperclass @@ -21,30 +25,30 @@ public class AbstractEncounter extends SyncAttributeEntity { private EncounterType encounterType; @Column - private DateTime earliestVisitDateTime; + private Instant earliestVisitDateTime; @Column - private DateTime maxVisitDateTime; + private Instant maxVisitDateTime; @Column(name = ColumnNames.EncounterDateTime) - private DateTime encounterDateTime; + private Instant encounterDateTime; @Column(name = ColumnNames.EncounterObservations) - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; @Column(name = ColumnNames.EncounterCancelDateTime) - private DateTime cancelDateTime; + private Instant cancelDateTime; @Column(name = ColumnNames.EncounterCancelObservations) - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection cancelObservations; - @Type(type = "org.avni.server.geo.PointType") + @Type(value = PointType.class) @Column private Point encounterLocation; - @Type(type = "org.avni.server.geo.PointType") + @Type(value = PointType.class) @Column private Point cancelLocation; @@ -66,14 +70,14 @@ public void setEncounterType(EncounterType encounterType) { } public DateTime getEncounterDateTime() { - return encounterDateTime; + return DateTimeUtil.toJodaDateTime(encounterDateTime); } public void setEncounterDateTime(DateTime encounterDateTime, User currentUser) { if (this.encounterDateTime == null && encounterDateTime != null) { this.filledBy = currentUser; } - this.encounterDateTime = encounterDateTime; + this.encounterDateTime = DateTimeUtil.toInstant(encounterDateTime); } public ObservationCollection getObservations() { @@ -93,23 +97,23 @@ public void setName(String name) { } public DateTime getEarliestVisitDateTime() { - return earliestVisitDateTime; + return DateTimeUtil.toJodaDateTime(earliestVisitDateTime); } public void setEarliestVisitDateTime(DateTime earliestVisitDateTime) { - this.earliestVisitDateTime = earliestVisitDateTime; + this.earliestVisitDateTime = DateTimeUtil.toInstant(earliestVisitDateTime); } public DateTime getMaxVisitDateTime() { - return maxVisitDateTime; + return DateTimeUtil.toJodaDateTime(maxVisitDateTime); } public void setMaxVisitDateTime(DateTime maxVisitDateTime) { - this.maxVisitDateTime = maxVisitDateTime; + this.maxVisitDateTime = DateTimeUtil.toInstant(maxVisitDateTime); } public DateTime getCancelDateTime() { - return cancelDateTime; + return DateTimeUtil.toJodaDateTime(cancelDateTime); } public boolean isCancelled() { @@ -117,7 +121,7 @@ public boolean isCancelled() { } public void setCancelDateTime(DateTime cancelDateTime) { - this.cancelDateTime = cancelDateTime; + this.cancelDateTime = DateTimeUtil.toInstant(cancelDateTime); } public ObservationCollection getCancelObservations() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Account.java b/avni-server-api/src/main/java/org/avni/server/domain/Account.java index 65b7cde3b..4c96f657e 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Account.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Account.java @@ -1,9 +1,9 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/AccountAdmin.java b/avni-server-api/src/main/java/org/avni/server/domain/AccountAdmin.java index 831e87e23..ef3de26c1 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/AccountAdmin.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/AccountAdmin.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; - @Entity @Table(name = "account_admin") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/AddressLevel.java b/avni-server-api/src/main/java/org/avni/server/domain/AddressLevel.java index 7c8056d5c..bc0a93a84 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/AddressLevel.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/AddressLevel.java @@ -1,16 +1,20 @@ package org.avni.server.domain; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.projections.BaseProjection; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.geo.Point; +import org.avni.server.geo.PointType; +import org.avni.server.ltree.LTreeType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Type; -import org.avni.server.application.projections.BaseProjection; -import org.avni.server.geo.Point; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.*; import java.util.stream.Collectors; @@ -41,7 +45,7 @@ public class AddressLevel extends OrganisationAwareEntity { private Set subLocations = new HashSet<>(); @Column(unique = true) - @Type(type = "org.avni.server.ltree.LTreeType") + @Type(value = LTreeType.class) private String lineage; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "location") @@ -57,11 +61,11 @@ public class AddressLevel extends OrganisationAwareEntity { private Set virtualCatchments = new HashSet<>(); @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection locationProperties; - @Type(type = "org.avni.server.geo.PointType") @Column + @Type(value = PointType.class) private Point gpsCoordinates; private String legacyId; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/AddressLevelType.java b/avni-server-api/src/main/java/org/avni/server/domain/AddressLevelType.java index 15186678a..ab35d5566 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/AddressLevelType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/AddressLevelType.java @@ -2,14 +2,14 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hibernate.annotations.BatchSize; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.PositiveOrZero; import org.avni.server.application.projections.BaseProjection; +import org.hibernate.annotations.BatchSize; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.PositiveOrZero; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/AnswerConceptMigration.java b/avni-server-api/src/main/java/org/avni/server/domain/AnswerConceptMigration.java index 094600e48..d0387492c 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/AnswerConceptMigration.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/AnswerConceptMigration.java @@ -2,10 +2,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; - @Entity @Table(name = "answer_concept_migration") @JsonIgnoreProperties({"concept"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ApprovalStatus.java b/avni-server-api/src/main/java/org/avni/server/domain/ApprovalStatus.java index 7bf1c95f4..1c3de2ea9 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ApprovalStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ApprovalStatus.java @@ -1,12 +1,14 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; import org.joda.time.DateTime; +import java.time.Instant; + @Entity @BatchSize(size = 100) public class ApprovalStatus { @@ -25,9 +27,9 @@ public class ApprovalStatus { @Column private boolean isVoided; @Column - private DateTime createdDateTime; + private Instant createdDateTime; @Column - private DateTime lastModifiedDateTime; + private Instant lastModifiedDateTime; public Long getId() { return id; @@ -62,19 +64,19 @@ public void setVoided(boolean voided) { } public DateTime getCreatedDateTime() { - return createdDateTime; + return DateTimeUtil.toJodaDateTime(createdDateTime); } public void setCreatedDateTime(DateTime createdDateTime) { - this.createdDateTime = createdDateTime; + this.createdDateTime = DateTimeUtil.toInstant(createdDateTime); } public DateTime getLastModifiedDateTime() { - return lastModifiedDateTime; + return DateTimeUtil.toJodaDateTime(lastModifiedDateTime); } public void setLastModifiedDateTime(DateTime lastModifiedDateTime) { - this.lastModifiedDateTime = lastModifiedDateTime; + this.lastModifiedDateTime = DateTimeUtil.toInstant(lastModifiedDateTime); } public enum Status { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/CHSBaseEntity.java b/avni-server-api/src/main/java/org/avni/server/domain/CHSBaseEntity.java index b0b240545..4007de41e 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/CHSBaseEntity.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/CHSBaseEntity.java @@ -1,13 +1,16 @@ package org.avni.server.domain; -import org.hibernate.proxy.HibernateProxyHelper; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.domain.framework.IdHolder; +import org.hibernate.proxy.HibernateProxy; +import org.hibernate.proxy.LazyInitializer; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.util.Objects; import java.util.UUID; @MappedSuperclass -public class CHSBaseEntity { +public class CHSBaseEntity implements IdHolder { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) @Id @@ -58,13 +61,24 @@ public void assignUUIDIfRequired() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || HibernateProxyHelper.getClassWithoutInitializingProxy(this) != HibernateProxyHelper.getClassWithoutInitializingProxy(o)) return false; + return CHSBaseEntity.equals(this, o); + } + + public static boolean equals(IdHolder a, Object other) { + if (a == other) return true; + + LazyInitializer lazyInitializer2 = HibernateProxy.extractLazyInitializer(other); + + if (other == null) return false; + if (lazyInitializer2 != null && a.getClass() != lazyInitializer2.getImplementationClass()) return false; + if (lazyInitializer2 == null && a.getClass() != other.getClass()) return false; + + IdHolder otherIdHolder = lazyInitializer2 == null ? (IdHolder) other : (IdHolder) lazyInitializer2.getImplementation(); - CHSBaseEntity that = (CHSBaseEntity) o; + if (a.getId() != null && Objects.equals(a.getId(), otherIdHolder.getId())) return true; + if (a.getUuid() != null && Objects.equals(a.getUuid(), otherIdHolder.getUuid())) return true; - if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null) return false; - return getUuid() != null ? getUuid().equals(that.getUuid()) : that.getUuid() == null; + return false; } @Override diff --git a/avni-server-api/src/main/java/org/avni/server/domain/CHSEntity.java b/avni-server-api/src/main/java/org/avni/server/domain/CHSEntity.java index 6e4431d01..d9891abaa 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/CHSEntity.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/CHSEntity.java @@ -2,7 +2,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; @@ -10,8 +13,7 @@ import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.Date; @MappedSuperclass @@ -27,7 +29,7 @@ public class CHSEntity extends CHSBaseEntity implements Auditable { @CreatedDate @NotNull - private Date createdDateTime; + private Instant createdDateTime; @JsonIgnore @JoinColumn(name = "last_modified_by_id") @@ -38,7 +40,7 @@ public class CHSEntity extends CHSBaseEntity implements Auditable { @LastModifiedDate @NotNull - private Date lastModifiedDateTime; + private Instant lastModifiedDateTime; @JsonIgnore public User getCreatedBy() { @@ -50,11 +52,11 @@ public void setCreatedBy(User createdBy) { } public DateTime getCreatedDateTime() { - return new DateTime(createdDateTime); + return DateTimeUtil.toJodaDateTime(createdDateTime); } public void setCreatedDateTime(DateTime createdDateTime) { - this.createdDateTime = createdDateTime.toDate(); + this.createdDateTime = createdDateTime.toDate().toInstant(); } @JsonIgnore @@ -71,11 +73,11 @@ public DateTime getLastModifiedDateTime() { } private DateTime toJodaDateTime() { - return new DateTime(lastModifiedDateTime); + return DateTimeUtil.toJodaDateTime(lastModifiedDateTime); } public void setLastModifiedDateTime(DateTime lastModifiedDateTime) { - this.lastModifiedDateTime = lastModifiedDateTime.toDate(); + this.lastModifiedDateTime = lastModifiedDateTime.toDate().toInstant(); } @Column(name = "version") @@ -115,7 +117,15 @@ public String getLastModifiedByName() { return getLastModifiedBy().getUsername(); } - public static Date toDate(DateTime dateTime) { + public static Instant toDate(DateTime dateTime) { + return DateTimeUtil.toInstant(dateTime); + } + + public static Date toUtilDate(DateTime dateTime) { return dateTime == null ? null : dateTime.toDate(); } + + public static Date toUtilDate(Instant dateTime) { + return dateTime == null ? null : new Date(dateTime.toEpochMilli()); + } } diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Catchment.java b/avni-server-api/src/main/java/org/avni/server/domain/Catchment.java index 2b9df7e11..fb01cfb90 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Catchment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Catchment.java @@ -1,10 +1,10 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Checklist.java b/avni-server-api/src/main/java/org/avni/server/domain/Checklist.java index b82d2c5fa..9476a4150 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Checklist.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Checklist.java @@ -1,11 +1,13 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -29,7 +31,7 @@ public class Checklist extends OrganisationAwareEntity { @NotNull @Column - private DateTime baseDate; + private Instant baseDate; public ChecklistDetail getChecklistDetail() { return checklistDetail; @@ -48,11 +50,11 @@ public void setProgramEnrolment(ProgramEnrolment programEnrolment) { } public DateTime getBaseDate() { - return baseDate; + return DateTimeUtil.toJodaDateTime(baseDate); } public void setBaseDate(DateTime baseDate) { - this.baseDate = baseDate; + this.baseDate = DateTimeUtil.toInstant(baseDate); } public List getItems() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistDetail.java b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistDetail.java index b58db6a89..a1b529cd5 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistDetail.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistDetail.java @@ -1,11 +1,11 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.projections.BaseProjection; import org.hibernate.annotations.BatchSize; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItem.java b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItem.java index df64c4ff9..6803034c4 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItem.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItem.java @@ -1,12 +1,15 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "checklist_item") @@ -14,10 +17,10 @@ @BatchSize(size = 100) public class ChecklistItem extends OrganisationAwareEntity { @Column - private DateTime completionDate; + private Instant completionDate; @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; @ManyToOne(fetch = FetchType.LAZY) @@ -30,11 +33,11 @@ public class ChecklistItem extends OrganisationAwareEntity { private Checklist checklist; public DateTime getCompletionDate() { - return completionDate; + return DateTimeUtil.toJodaDateTime(completionDate); } public void setCompletionDate(DateTime completionDate) { - this.completionDate = completionDate; + this.completionDate = DateTimeUtil.toInstant(completionDate); } public Checklist getChecklist() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemDetail.java b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemDetail.java index 73551d566..1028da106 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemDetail.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemDetail.java @@ -1,11 +1,11 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.Form; +import org.avni.server.framework.hibernate.ChecklistItemUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import org.avni.server.application.Form; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; @Entity @Table(name = "checklist_item_detail") @@ -17,7 +17,7 @@ public class ChecklistItemDetail extends OrganisationAwareEntity { private Concept concept; @Column(name = "status") - @Type(type = "status") + @Type(value = ChecklistItemUserType.class) private ChecklistItemStatus checklistItemStatus; @JoinColumn(name = "dependent_on", nullable = true) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemStatus.java b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemStatus.java index 758d8a096..b20465053 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ChecklistItemStatus.java @@ -1,6 +1,7 @@ package org.avni.server.domain; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; + import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Comment.java b/avni-server-api/src/main/java/org/avni/server/domain/Comment.java index e681e6da5..f341d384f 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Comment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Comment.java @@ -1,11 +1,10 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hibernate.annotations.BatchSize; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.util.S; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import org.hibernate.annotations.BatchSize; @Entity @Table(name = "comment") diff --git a/avni-server-api/src/main/java/org/avni/server/domain/CommentThread.java b/avni-server-api/src/main/java/org/avni/server/domain/CommentThread.java index 25f6bea61..af92c8f1f 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/CommentThread.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/CommentThread.java @@ -2,11 +2,13 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; @@ -23,10 +25,10 @@ public class CommentThread extends OrganisationAwareEntity { @Column @NotNull - private DateTime openDateTime; + private Instant openDateTime; @Column - private DateTime resolvedDateTime; + private Instant resolvedDateTime; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "commentThread") private Set comments = new HashSet<>(); @@ -40,19 +42,19 @@ public void setStatus(CommentThreadStatus status) { } public DateTime getOpenDateTime() { - return openDateTime; + return DateTimeUtil.toJodaDateTime(openDateTime); } public void setOpenDateTime(DateTime openDateTime) { - this.openDateTime = openDateTime; + this.openDateTime = DateTimeUtil.toInstant(openDateTime); } public DateTime getResolvedDateTime() { - return resolvedDateTime; + return DateTimeUtil.toJodaDateTime(resolvedDateTime); } public void setResolvedDateTime(DateTime resolvedDateTime) { - this.resolvedDateTime = resolvedDateTime; + this.resolvedDateTime = DateTimeUtil.toInstant(resolvedDateTime); } public Set getComments() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Concept.java b/avni-server-api/src/main/java/org/avni/server/domain/Concept.java index 7008411a6..ae551b6bf 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Concept.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Concept.java @@ -1,23 +1,21 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.KeyValues; +import org.avni.server.framework.hibernate.KeyValuesUserType; +import org.avni.server.web.request.ConceptContract; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.Type; -import org.hibernate.search.annotations.Field; -import org.hibernate.search.annotations.Indexed; -import org.avni.server.application.KeyValues; -import org.avni.server.web.request.ConceptContract; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @Entity -@Indexed @Table(name = "concept") @BatchSize(size = 100) @DynamicInsert @@ -27,16 +25,14 @@ public class Concept extends OrganisationAwareEntity { private static final int POSTGRES_MAX_COLUMN_NAME_LENGTH = 63; private static final int NUMBER_OF_CHARACTERS_TO_ACCOMMODATE_HASHCODE = 14; - @Field @NotNull private String name; - @Field @NotNull private String dataType; @Column - @Type(type = "keyValues") + @Type(value = KeyValuesUserType.class) private KeyValues keyValues; private Boolean active; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ConceptAnswer.java b/avni-server-api/src/main/java/org/avni/server/domain/ConceptAnswer.java index 82b96f9d4..bd535cfeb 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ConceptAnswer.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ConceptAnswer.java @@ -1,16 +1,16 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.projections.BaseProjection; +import org.avni.server.projection.ConceptProjection; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import org.avni.server.application.projections.BaseProjection; -import org.avni.server.projection.ConceptProjection; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.Objects; @Entity diff --git a/avni-server-api/src/main/java/org/avni/server/domain/CustomQuery.java b/avni-server-api/src/main/java/org/avni/server/domain/CustomQuery.java index c6bd56030..615a65953 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/CustomQuery.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/CustomQuery.java @@ -1,9 +1,9 @@ package org.avni.server.domain; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.validation.constraints.NotNull; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.validation.constraints.NotNull; @Entity(name = "custom_query") public class CustomQuery extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Dashboard.java b/avni-server-api/src/main/java/org/avni/server/domain/Dashboard.java index 81ea279c9..0c273537a 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Dashboard.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Dashboard.java @@ -1,11 +1,11 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.app.dashboard.DashboardFilter; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/DashboardSection.java b/avni-server-api/src/main/java/org/avni/server/domain/DashboardSection.java index b86427e0e..63f3e09f7 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/DashboardSection.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/DashboardSection.java @@ -2,10 +2,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/DashboardSectionCardMapping.java b/avni-server-api/src/main/java/org/avni/server/domain/DashboardSectionCardMapping.java index 81e1c0f4a..3186f07f3 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/DashboardSectionCardMapping.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/DashboardSectionCardMapping.java @@ -1,11 +1,10 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "dashboard_section_card_mapping") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/DeclarativeRule.java b/avni-server-api/src/main/java/org/avni/server/domain/DeclarativeRule.java index 8d74c805e..178540fba 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/DeclarativeRule.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/DeclarativeRule.java @@ -1,6 +1,7 @@ package org.avni.server.domain; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; + import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Documentation.java b/avni-server-api/src/main/java/org/avni/server/domain/Documentation.java index 82c0b39ac..cbe5dff09 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Documentation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Documentation.java @@ -1,9 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/DocumentationItem.java b/avni-server-api/src/main/java/org/avni/server/domain/DocumentationItem.java index c03ad3097..ea53e6ae6 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/DocumentationItem.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/DocumentationItem.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "documentation_item") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ETLEntity.java b/avni-server-api/src/main/java/org/avni/server/domain/ETLEntity.java index 829e2e05c..80486d8d3 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ETLEntity.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ETLEntity.java @@ -1,7 +1,7 @@ package org.avni.server.domain; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class ETLEntity extends CHSBaseEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Encounter.java b/avni-server-api/src/main/java/org/avni/server/domain/Encounter.java index ad3b9a30f..432041f04 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Encounter.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Encounter.java @@ -2,16 +2,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.projections.BaseProjection; import org.avni.server.common.dbSchema.TableNames; +import org.avni.server.domain.EncounterType.EncounterTypeProjection; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import org.avni.server.application.projections.BaseProjection; -import org.avni.server.domain.EncounterType.EncounterTypeProjection; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = TableNames.Encounter) @JsonIgnoreProperties({"individual"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/EncounterType.java b/avni-server-api/src/main/java/org/avni/server/domain/EncounterType.java index 68bd36d89..f84fdf152 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/EncounterType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/EncounterType.java @@ -2,14 +2,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.projections.BaseProjection; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.DynamicInsert; -import org.avni.server.application.projections.BaseProjection; import org.hibernate.annotations.Type; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Objects; import java.util.Optional; @@ -36,7 +37,7 @@ public class EncounterType extends OrganisationAwareEntity implements NamedEntit private String encounterEligibilityCheckRule; @Column(name = "encounter_eligibility_check_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule encounterEligibilityCheckDeclarativeRule; private Boolean active; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/EntityApprovalStatus.java b/avni-server-api/src/main/java/org/avni/server/domain/EntityApprovalStatus.java index 34cc9d25a..ab81aca79 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/EntityApprovalStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/EntityApprovalStatus.java @@ -1,11 +1,13 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @BatchSize(size = 100) @@ -39,7 +41,7 @@ public class EntityApprovalStatus extends SyncAttributeEntity { @Column @NotNull - private DateTime statusDateTime; + private Instant statusDateTime; @Column(name = "address_id") private Long addressId; @@ -101,11 +103,11 @@ public void setAutoApproved(Boolean autoApproved) { } public DateTime getStatusDateTime() { - return statusDateTime; + return DateTimeUtil.toJodaDateTime(statusDateTime); } public void setStatusDateTime(DateTime statusDateTime) { - this.statusDateTime = statusDateTime; + this.statusDateTime = DateTimeUtil.toInstant(statusDateTime); } public String getEntityTypeUuid() { @@ -123,4 +125,4 @@ public Long getAddressId() { public void setAddressId(Long addressId) { this.addressId = addressId; } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ExportJobParameters.java b/avni-server-api/src/main/java/org/avni/server/domain/ExportJobParameters.java index fd7cef7aa..3b4c4759c 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ExportJobParameters.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ExportJobParameters.java @@ -1,10 +1,11 @@ package org.avni.server.domain; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; @Entity @Table(name = "export_job_parameters") @@ -17,7 +18,7 @@ public class ExportJobParameters extends OrganisationAwareEntity { private User user; @Column(name = "report_format") - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) @NotNull private JsonObject reportFormat; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Gender.java b/avni-server-api/src/main/java/org/avni/server/domain/Gender.java index 09443c42d..f76440202 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Gender.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Gender.java @@ -4,8 +4,8 @@ import org.hibernate.annotations.BatchSize; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; @Entity @Table(name = "gender") diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Group.java b/avni-server-api/src/main/java/org/avni/server/domain/Group.java index c2427c737..da217141d 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Group.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Group.java @@ -4,7 +4,7 @@ import org.avni.server.domain.accessControl.GroupPrivilege; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/GroupDashboard.java b/avni-server-api/src/main/java/org/avni/server/domain/GroupDashboard.java index 534ded11e..98d7f67d2 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/GroupDashboard.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/GroupDashboard.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @BatchSize(size = 100) public class GroupDashboard extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/GroupRole.java b/avni-server-api/src/main/java/org/avni/server/domain/GroupRole.java index 9e043ee7e..3a09dd562 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/GroupRole.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/GroupRole.java @@ -1,13 +1,12 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.projections.BaseProjection; import org.hibernate.annotations.BatchSize; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "group_role") @JsonIgnoreProperties({"groupSubjectType", "memberSubjectType"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/GroupSubject.java b/avni-server-api/src/main/java/org/avni/server/domain/GroupSubject.java index b17d38bfd..8af373b3a 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/GroupSubject.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/GroupSubject.java @@ -2,11 +2,13 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "group_subject") @@ -30,10 +32,10 @@ public class GroupSubject extends OrganisationAwareEntity { private GroupRole groupRole; @Column - private DateTime membershipStartDate; + private Instant membershipStartDate; @Column - private DateTime membershipEndDate; + private Instant membershipEndDate; @Column(name = "member_subject_address_id") private Long memberSubjectAddressId; @@ -72,19 +74,19 @@ public void setGroupRole(GroupRole groupRole) { } public DateTime getMembershipStartDate() { - return membershipStartDate; + return DateTimeUtil.toJodaDateTime(membershipStartDate); } public void setMembershipStartDate(DateTime membershipStartDate) { - this.membershipStartDate = membershipStartDate; + this.membershipStartDate = DateTimeUtil.toInstant(membershipStartDate); } public DateTime getMembershipEndDate() { - return membershipEndDate; + return DateTimeUtil.toJodaDateTime(membershipEndDate); } public void setMembershipEndDate(DateTime membershipEndDate) { - this.membershipEndDate = membershipEndDate; + this.membershipEndDate = DateTimeUtil.toInstant(membershipEndDate); } public String getGroupSubjectUUID() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierAssignment.java b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierAssignment.java index b48a638c5..b3d221089 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierAssignment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierAssignment.java @@ -1,11 +1,10 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "identifier_assignment") @JsonIgnoreProperties({"identifierSource", "assignedTo", "individual", "programEnrolment"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierSource.java b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierSource.java index 8e5bf6922..03930738d 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierSource.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierSource.java @@ -1,12 +1,12 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.identifier.IdentifierGeneratorType; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "identifier_source") @BatchSize(size = 100) @@ -32,7 +32,7 @@ public class IdentifierSource extends OrganisationAwareEntity { private Long batchGenerationSize; @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject options; @Column diff --git a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierUserAssignment.java b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierUserAssignment.java index 29f3dbc69..9ac78a480 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/IdentifierUserAssignment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/IdentifierUserAssignment.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; import org.avni.server.domain.identifier.IdentifierGeneratorType; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; - @Entity @Table(name = "identifier_user_assignment") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Individual.java b/avni-server-api/src/main/java/org/avni/server/domain/Individual.java index a4cc42664..f94033a81 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Individual.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Individual.java @@ -2,16 +2,20 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.common.dbSchema.ColumnNames; import org.avni.server.common.dbSchema.TableNames; import org.avni.server.domain.individualRelationship.IndividualRelationship; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; import org.avni.server.geo.Point; +import org.avni.server.geo.PointType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.LocalDate; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -39,7 +43,7 @@ public class Individual extends SyncAttributeEntity implements MessageableEntity private String profilePicture; - private LocalDate dateOfBirth; + private Instant dateOfBirth; private boolean dateOfBirthVerified; @@ -57,7 +61,7 @@ public class Individual extends SyncAttributeEntity implements MessageableEntity @NotNull @Column(name = ColumnNames.RegistrationDate) - private LocalDate registrationDate; + private Instant registrationDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "gender_id") @@ -77,10 +81,10 @@ public class Individual extends SyncAttributeEntity implements MessageableEntity private Set userSubjectAssignments = new HashSet<>(); @Column(name = ColumnNames.IndividualObservations) - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; - @Type(type = "org.avni.server.geo.PointType") + @Type(value = PointType.class) @Column private Point registrationLocation; @@ -92,20 +96,20 @@ public static Individual create(String firstName, String lastName, String profil individual.firstName = firstName; individual.lastName = lastName; individual.profilePicture = profilePicture; - individual.dateOfBirth = dateOfBirth; + individual.dateOfBirth = DateTimeUtil.toInstant(dateOfBirth); individual.dateOfBirthVerified = dateOfBirthVerified; individual.gender = gender; individual.addressLevel = address; - individual.registrationDate = registrationDate; + individual.registrationDate = DateTimeUtil.toInstant(registrationDate); return individual; } public LocalDate getDateOfBirth() { - return dateOfBirth; + return DateTimeUtil.toJodaDate(dateOfBirth); } public void setDateOfBirth(LocalDate dateOfBirth) { - this.dateOfBirth = dateOfBirth; + this.dateOfBirth = DateTimeUtil.toInstant(dateOfBirth); } public boolean isDateOfBirthVerified() { @@ -169,11 +173,11 @@ public void setObservations(ObservationCollection observations) { } public LocalDate getRegistrationDate() { - return registrationDate; + return DateTimeUtil.toJodaDate(registrationDate); } public void setRegistrationDate(LocalDate registrationDate) { - this.registrationDate = registrationDate; + this.registrationDate = DateTimeUtil.toInstant(registrationDate); } public void addEnrolment(ProgramEnrolment programEnrolment) { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Msg91Config.java b/avni-server-api/src/main/java/org/avni/server/domain/Msg91Config.java index 43013a8ee..1a504b6d9 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Msg91Config.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Msg91Config.java @@ -1,11 +1,10 @@ package org.avni.server.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; import org.hibernate.annotations.BatchSize; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; - @Entity @Table(name = "msg91_config") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/News.java b/avni-server-api/src/main/java/org/avni/server/domain/News.java index afae5f5ea..dacb5307f 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/News.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/News.java @@ -1,12 +1,14 @@ package org.avni.server.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "news") @@ -14,7 +16,7 @@ public class News extends OrganisationAwareEntity { @NotNull private String title; - private DateTime publishedDate; + private Instant publishedDate; private String heroImage; private String content; @Column(name = "contenthtml") @@ -29,11 +31,11 @@ public void setTitle(String title) { } public DateTime getPublishedDate() { - return publishedDate; + return DateTimeUtil.toJodaDateTime(publishedDate); } public void setPublishedDate(DateTime publishedDate) { - this.publishedDate = publishedDate; + this.publishedDate = DateTimeUtil.toInstant(publishedDate); } public String getHeroImage() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OperationalEncounterType.java b/avni-server-api/src/main/java/org/avni/server/domain/OperationalEncounterType.java index 2958c5bc1..f84ba43f8 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OperationalEncounterType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OperationalEncounterType.java @@ -1,11 +1,10 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "operational_encounter_type") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OperationalProgram.java b/avni-server-api/src/main/java/org/avni/server/domain/OperationalProgram.java index 859948dec..38c8ad238 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OperationalProgram.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OperationalProgram.java @@ -1,11 +1,10 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "operational_program") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OperationalSubjectType.java b/avni-server-api/src/main/java/org/avni/server/domain/OperationalSubjectType.java index 693293bec..0b365d162 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OperationalSubjectType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OperationalSubjectType.java @@ -1,13 +1,12 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.Format; import org.avni.server.application.Subject; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "operational_subject_type") @BatchSize(size = 100) @@ -80,7 +79,7 @@ public Format getValidFirstNameFormat() { return subjectType.getValidFirstNameFormat(); } - public Format getValidLastNameFormat(){ + public Format getValidLastNameFormat() { return subjectType.getValidLastNameFormat(); } @@ -88,24 +87,32 @@ public String getIconFileS3Key() { return subjectType.getIconFileS3Key(); } - public boolean isAllowProfilePicture() { return subjectType.isAllowProfilePicture(); } + public boolean isAllowProfilePicture() { + return subjectType.isAllowProfilePicture(); + } + + public boolean isAllowMiddleName() { + return subjectType.isAllowMiddleName(); + } - public boolean isAllowMiddleName() { return subjectType.isAllowMiddleName();} public boolean isLastNameOptional() { return subjectType.isLastNameOptional(); } - public Format getValidMiddleNameFormat() { return subjectType.getValidMiddleNameFormat();} + + public Format getValidMiddleNameFormat() { + return subjectType.getValidMiddleNameFormat(); + } @Override public DateTime getLastModifiedDateTime() { Auditable lastModified = getLastModified(getSubjectType()); - return lastModified.equals(this)?super.getLastModifiedDateTime(): lastModified.getLastModifiedDateTime(); + return lastModified.equals(this) ? super.getLastModifiedDateTime() : lastModified.getLastModifiedDateTime(); } @Override public User getLastModifiedBy() { Auditable lastModified = getLastModified(getSubjectType()); - return lastModified.equals(this)?super.getLastModifiedBy(): lastModified.getLastModifiedBy(); + return lastModified.equals(this) ? super.getLastModifiedBy() : lastModified.getLastModifiedBy(); } public boolean isDirectlyAssignable() { @@ -117,5 +124,7 @@ public boolean isVoided() { return subjectType.isVoided() || super.isVoided(); } - public JsonObject getSettings() { return subjectType.getSettings(); } + public JsonObject getSettings() { + return subjectType.getSettings(); + } } diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Organisation.java b/avni-server-api/src/main/java/org/avni/server/domain/Organisation.java index 7583e583b..7e0f7eea0 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Organisation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Organisation.java @@ -1,13 +1,12 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.organisation.OrganisationCategory; import org.avni.server.domain.organisation.OrganisationStatus; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "organisation") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationAwareEntity.java b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationAwareEntity.java index d68c03f6c..5cafc5dbe 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationAwareEntity.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationAwareEntity.java @@ -1,8 +1,8 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class OrganisationAwareEntity extends CHSEntity { @@ -19,7 +19,7 @@ public void setOrganisationId(Long organisationId) { @JsonIgnore public Auditable getLastModified(Auditable auditable) { - return super.getLastModifiedDateTime().isAfter(auditable.getLastModifiedDateTime()) ? this : auditable; + return super.getLastModifiedDateTime().isBefore(auditable.getLastModifiedDateTime()) ? auditable : this; } } diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationConfig.java b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationConfig.java index 6983ae58f..e73e748f8 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationConfig.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationConfig.java @@ -6,14 +6,14 @@ import org.avni.server.application.KeyType; import org.avni.server.application.OrganisationConfigSettingKey; import org.avni.server.domain.framework.BaseJsonObject; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.avni.server.util.ObjectMapperSingleton; import org.avni.server.web.request.webapp.SubjectTypeSetting; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.*; import java.util.*; import java.util.stream.Collectors; @@ -24,14 +24,14 @@ public class OrganisationConfig extends OrganisationAwareEntity { // Check keys in OrganisationConfigSettingKeys @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject settings; @Column(name = "worklist_updation_rule") private String worklistUpdationRule; @Column(name = "export_settings") - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject exportSettings; @Deprecated diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroup.java b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroup.java index 383418920..d32224afa 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroup.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroup.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; import java.util.UUID; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroupOrganisation.java b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroupOrganisation.java index 9b0b3b9a4..177291194 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroupOrganisation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/OrganisationGroupOrganisation.java @@ -2,7 +2,7 @@ import org.hibernate.annotations.BatchSize; -import javax.persistence.*; +import jakarta.persistence.*; @Entity @Table(name = "organisation_group_organisation") diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ParentLocationMapping.java b/avni-server-api/src/main/java/org/avni/server/domain/ParentLocationMapping.java index b0255947b..834637c86 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ParentLocationMapping.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ParentLocationMapping.java @@ -2,7 +2,7 @@ import org.hibernate.annotations.BatchSize; -import javax.persistence.*; +import jakarta.persistence.*; @Entity @Table(name = "location_location_mapping") diff --git a/avni-server-api/src/main/java/org/avni/server/domain/PlatformTranslation.java b/avni-server-api/src/main/java/org/avni/server/domain/PlatformTranslation.java index 0c0d77978..d35cf78ec 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/PlatformTranslation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/PlatformTranslation.java @@ -1,11 +1,12 @@ package org.avni.server.domain; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.avni.server.application.Platform; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; @Entity @Table(name = "platform_translation") @@ -13,7 +14,7 @@ public class PlatformTranslation extends CHSEntity { @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject translationJson; @NotNull diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Program.java b/avni-server-api/src/main/java/org/avni/server/domain/Program.java index f9418cfe1..3897ad978 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Program.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Program.java @@ -2,14 +2,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.DynamicInsert; import org.avni.server.application.projections.BaseProjection; import org.hibernate.annotations.Type; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import java.util.HashSet; import java.util.Objects; import java.util.Optional; @@ -37,7 +38,7 @@ public class Program extends OrganisationAwareEntity implements NamedEntity { private String enrolmentEligibilityCheckRule; @Column(name = "enrolment_eligibility_check_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule enrolmentEligibilityCheckDeclarativeRule; private Boolean active; @@ -52,7 +53,7 @@ public class Program extends OrganisationAwareEntity implements NamedEntity { private String manualEnrolmentEligibilityCheckRule; @Column(name = "manual_enrolment_eligibility_check_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule manualEnrolmentEligibilityCheckDeclarativeRule; public String getName() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ProgramEncounter.java b/avni-server-api/src/main/java/org/avni/server/domain/ProgramEncounter.java index d0b5f579d..362425813 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ProgramEncounter.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ProgramEncounter.java @@ -9,8 +9,8 @@ import org.avni.server.domain.EncounterType.EncounterTypeProjection; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; @Entity @Table(name = TableNames.ProgramEncounter) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ProgramEnrolment.java b/avni-server-api/src/main/java/org/avni/server/domain/ProgramEnrolment.java index 253b2b7d2..083d14c44 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ProgramEnrolment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ProgramEnrolment.java @@ -2,15 +2,19 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.common.dbSchema.ColumnNames; import org.avni.server.common.dbSchema.TableNames; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.geo.Point; +import org.avni.server.geo.PointType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import org.avni.server.geo.Point; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; @@ -38,25 +42,25 @@ public class ProgramEnrolment extends SyncAttributeEntity implements Messageable @Column(name = ColumnNames.EnrolmentDateTime) @NotNull - private DateTime enrolmentDateTime; + private Instant enrolmentDateTime; @Column(name = ProgramEnrolmentObservations) - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; @Column(name = ColumnNames.ProgramExitDateTime) - private DateTime programExitDateTime; + private Instant programExitDateTime; - @Type(type= "org.avni.server.geo.PointType") + @Type(value = PointType.class) @Column private Point enrolmentLocation; - @Type(type= "org.avni.server.geo.PointType") + @Type(value = PointType.class) @Column private Point exitLocation; @Column(name = ProgramEnrolmentExitObservations) - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection programExitObservations; @Column @@ -122,11 +126,11 @@ public void setProgramEncounters(Set programEncounters) { } public DateTime getEnrolmentDateTime() { - return enrolmentDateTime; + return DateTimeUtil.toJodaDateTime(enrolmentDateTime); } public void setEnrolmentDateTime(DateTime enrolmentDateTime) { - this.enrolmentDateTime = enrolmentDateTime; + this.enrolmentDateTime = DateTimeUtil.toInstant(enrolmentDateTime); } public ObservationCollection getObservations() { @@ -138,11 +142,11 @@ public void setObservations(ObservationCollection observations) { } public DateTime getProgramExitDateTime() { - return programExitDateTime; + return DateTimeUtil.toJodaDateTime(programExitDateTime); } public void setProgramExitDateTime(DateTime programExitDateTime) { - this.programExitDateTime = programExitDateTime; + this.programExitDateTime = DateTimeUtil.toInstant(programExitDateTime); } public ObservationCollection getProgramExitObservations() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ReportCard.java b/avni-server-api/src/main/java/org/avni/server/domain/ReportCard.java index 7b437c581..4694ecdad 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ReportCard.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ReportCard.java @@ -1,13 +1,14 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.avni.server.web.contract.ValueUnit; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.springframework.util.StringUtils; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.List; @@ -39,7 +40,7 @@ public class ReportCard extends OrganisationAwareEntity { private StandardReportCardType standardReportCardType; @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject standardReportCardInput = new JsonObject(new HashMap<>()); public String getName() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/ResetSync.java b/avni-server-api/src/main/java/org/avni/server/domain/ResetSync.java index 6c12a8742..9f08a1043 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/ResetSync.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/ResetSync.java @@ -1,9 +1,8 @@ package org.avni.server.domain; +import jakarta.persistence.*; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; - @Entity @Table(name = "reset_sync") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Rule.java b/avni-server-api/src/main/java/org/avni/server/domain/Rule.java index 2147371bb..ef3b6cdf2 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Rule.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Rule.java @@ -1,11 +1,12 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.application.RuleType; +import org.avni.server.framework.hibernate.RuleDataUserType; +import org.avni.server.framework.hibernate.RuledEntityUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import org.avni.server.application.RuleType; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; @Entity(name = "rule") @BatchSize(size = 100) @@ -13,7 +14,7 @@ public class Rule extends OrganisationAwareEntity { @NotNull @Column(name="entity") - @Type(type = "ruledEntity") + @Type(value = RuledEntityUserType.class) private RuledEntity entity; @NotNull @@ -30,7 +31,7 @@ public class Rule extends OrganisationAwareEntity { private String fnName; @Column - @Type(type = "ruleData") + @Type(value = RuleDataUserType.class) private RuleData data; @ManyToOne(fetch = FetchType.LAZY) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/RuleDependency.java b/avni-server-api/src/main/java/org/avni/server/domain/RuleDependency.java index 9b535051f..eb1bb437c 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/RuleDependency.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/RuleDependency.java @@ -1,9 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.Set; @Entity(name = "rule_dependency") diff --git a/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureLog.java b/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureLog.java index a62537c7d..929466389 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureLog.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureLog.java @@ -1,11 +1,11 @@ package org.avni.server.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; import java.io.PrintWriter; import java.io.StringWriter; import java.util.UUID; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureTelemetry.java b/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureTelemetry.java index b9e78b1e5..eb660a5c3 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureTelemetry.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/RuleFailureTelemetry.java @@ -1,9 +1,12 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.enums.ruleFailure.AppType; import org.avni.server.domain.enums.ruleFailure.EntityType; import org.avni.server.domain.enums.ruleFailure.SourceType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @@ -14,10 +17,7 @@ import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - -import java.util.Date; +import java.time.Instant; @Entity @Table(name = "rule_failure_telemetry") @@ -65,10 +65,10 @@ public class RuleFailureTelemetry { private String stacktrace; @Column - private DateTime closedDateTime; + private Instant closedDateTime; @Column - private DateTime errorDateTime; + private Instant errorDateTime; @Column private Boolean isClosed; @@ -85,7 +85,7 @@ public class RuleFailureTelemetry { private User createdBy; @CreatedDate - private Date createdDateTime; + private Instant createdDateTime; @JsonIgnore @JoinColumn(name = "last_modified_by_id") @@ -96,7 +96,7 @@ public class RuleFailureTelemetry { private User lastModifiedBy; @LastModifiedDate - private Date lastModifiedDateTime; + private Instant lastModifiedDateTime; @Column(name = "version") private int version; @@ -106,7 +106,7 @@ public User getCreatedBy() { } public DateTime getCreatedDateTime() { - return new DateTime(createdDateTime); + return DateTimeUtil.toJodaDateTime(createdDateTime); } public User getLastModifiedBy() { @@ -214,19 +214,19 @@ public void setStacktrace(String stacktrace) { } public DateTime getClosedDateTime() { - return closedDateTime; + return DateTimeUtil.toJodaDateTime(closedDateTime); } public void setClosedDateTime(DateTime closedDateTime) { - this.closedDateTime = closedDateTime; + this.closedDateTime = DateTimeUtil.toInstant(closedDateTime); } public DateTime getErrorDateTime() { - return errorDateTime; + return DateTimeUtil.toJodaDateTime(errorDateTime); } public void setErrorDateTime(DateTime errorDateTime) { - this.errorDateTime = errorDateTime; + this.errorDateTime = DateTimeUtil.toInstant(errorDateTime); } public Boolean getClosed() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/StandardReportCardType.java b/avni-server-api/src/main/java/org/avni/server/domain/StandardReportCardType.java index 1a46b5bd6..c472ad816 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/StandardReportCardType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/StandardReportCardType.java @@ -1,10 +1,12 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @BatchSize(size = 100) @@ -25,9 +27,9 @@ public class StandardReportCardType { @Column private boolean isVoided; @Column - private DateTime createdDateTime; + private Instant createdDateTime; @Column - private DateTime lastModifiedDateTime; + private Instant lastModifiedDateTime; @Column @NotNull @Enumerated(EnumType.STRING) @@ -74,19 +76,19 @@ public void setVoided(boolean voided) { } public DateTime getCreatedDateTime() { - return createdDateTime; + return DateTimeUtil.toJodaDateTime(createdDateTime); } public void setCreatedDateTime(DateTime createdDateTime) { - this.createdDateTime = createdDateTime; + this.createdDateTime = DateTimeUtil.toInstant(createdDateTime); } public DateTime getLastModifiedDateTime() { - return lastModifiedDateTime; + return DateTimeUtil.toJodaDateTime(lastModifiedDateTime); } public void setLastModifiedDateTime(DateTime lastModifiedDateTime) { - this.lastModifiedDateTime = lastModifiedDateTime; + this.lastModifiedDateTime = DateTimeUtil.toInstant(lastModifiedDateTime); } public @NotNull StandardReportCardTypeType getType() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/SubjectMigration.java b/avni-server-api/src/main/java/org/avni/server/domain/SubjectMigration.java index dcd878ae0..fe2cd0fcb 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/SubjectMigration.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/SubjectMigration.java @@ -1,11 +1,10 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.DynamicInsert; -import javax.persistence.*; - @Entity @Table(name = "subject_migration") @JsonIgnoreProperties({"individual", "oldAddressLevel", "newAddressLevel", "subjectType"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/SubjectType.java b/avni-server-api/src/main/java/org/avni/server/domain/SubjectType.java index 180bd001b..af72784da 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/SubjectType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/SubjectType.java @@ -2,17 +2,19 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hibernate.annotations.BatchSize; -import org.hibernate.annotations.DynamicInsert; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.Format; import org.avni.server.application.Subject; import org.avni.server.application.projections.BaseProjection; +import org.avni.server.framework.hibernate.DeclarativeRuleUserType; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.avni.server.web.request.GroupRoleContract; +import org.hibernate.annotations.BatchSize; +import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.Type; import org.springframework.data.rest.core.config.Projection; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.*; import java.util.stream.Collectors; @@ -58,7 +60,7 @@ public class SubjectType extends OrganisationAwareEntity implements NamedEntity // Check keys in SubjectTypeSettingKeys @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject settings; @Embedded @@ -116,7 +118,7 @@ public class SubjectType extends OrganisationAwareEntity implements NamedEntity private String programEligibilityCheckRule; @Column(name = "program_eligibility_check_declarative_rule") - @Type(type = "declarativeRule") + @Type(value = DeclarativeRuleUserType.class) private DeclarativeRule programEligibilityCheckDeclarativeRule; private String nameHelpText; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/SyncAttributeEntity.java b/avni-server-api/src/main/java/org/avni/server/domain/SyncAttributeEntity.java index 37b0fac01..b5f365fb5 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/SyncAttributeEntity.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/SyncAttributeEntity.java @@ -1,9 +1,8 @@ package org.avni.server.domain; import com.fasterxml.jackson.annotation.JsonIgnore; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; @MappedSuperclass public class SyncAttributeEntity extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/SyncTelemetry.java b/avni-server-api/src/main/java/org/avni/server/domain/SyncTelemetry.java index d0242389c..45a0b27f4 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/SyncTelemetry.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/SyncTelemetry.java @@ -1,11 +1,14 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.framework.hibernate.JSONObjectUserType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "sync_telemetry") @@ -21,14 +24,14 @@ public class SyncTelemetry extends OrganisationAwareEntity{ private String syncStatus; @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject entityStatus; @Column - private DateTime syncStartTime; + private Instant syncStartTime; @Column - private DateTime syncEndTime; + private Instant syncEndTime; @Column private String appVersion; @@ -40,7 +43,7 @@ public class SyncTelemetry extends OrganisationAwareEntity{ private String deviceName; @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject deviceInfo; @Column @@ -79,19 +82,19 @@ public void setEntityStatus(JsonObject entityStatus) { } public DateTime getSyncStartTime() { - return syncStartTime; + return DateTimeUtil.toJodaDateTime(syncStartTime); } public void setSyncStartTime(DateTime syncStartTime) { - this.syncStartTime = syncStartTime; + this.syncStartTime = DateTimeUtil.toInstant(syncStartTime); } public DateTime getSyncEndTime() { - return syncEndTime; + return DateTimeUtil.toJodaDateTime(syncEndTime); } public void setSyncEndTime(DateTime syncEndTime) { - this.syncEndTime = syncEndTime; + this.syncEndTime = DateTimeUtil.toInstant(syncEndTime); } public String getAppVersion() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Translation.java b/avni-server-api/src/main/java/org/avni/server/domain/Translation.java index 8a02455c2..a0404b7e1 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Translation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Translation.java @@ -1,17 +1,17 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "translation") @BatchSize(size = 100) public class Translation extends OrganisationAwareEntity { @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject translationJson; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/User.java b/avni-server-api/src/main/java/org/avni/server/domain/User.java index 55793c5fc..426802148 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/User.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/User.java @@ -2,7 +2,12 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.type.TypeReference; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.apache.commons.validator.routines.EmailValidator; +import org.avni.server.domain.framework.IdHolder; +import org.avni.server.framework.hibernate.JSONObjectUserType; +import org.avni.server.util.DateTimeUtil; import org.avni.server.util.ObjectMapperSingleton; import org.avni.server.util.ValidationUtil; import org.avni.server.web.request.syncAttribute.UserSyncSettings; @@ -10,21 +15,18 @@ import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; -import org.hibernate.proxy.HibernateProxyHelper; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; import java.util.*; import java.util.stream.Collectors; - @Entity @Table(name = "users") @BatchSize(size = 100) @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) -public class User { +public class User implements IdHolder { public static final String DEFAULT_SUPER_ADMIN = "5fed2907-df3a-4867-aef5-c87f4c78a31a"; @Column @@ -61,14 +63,15 @@ public class User { @ManyToOne(targetEntity = User.class) private User createdBy; - private DateTime createdDateTime; + @Column + private Instant createdDateTime; @JsonIgnore @JoinColumn(name = "last_modified_by_id") @ManyToOne(targetEntity = User.class) private User lastModifiedBy; - private DateTime lastModifiedDateTime; + private Instant lastModifiedDateTime; @Column private boolean isVoided; @@ -97,11 +100,11 @@ public class User { private OperatingIndividualScope operatingIndividualScope; @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject settings; @Column(name = "sync_settings") - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject syncSettings; @Column(name = "ignore_sync_settings_in_dea") @@ -234,13 +237,7 @@ public void setUserGroups(List userGroups) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || HibernateProxyHelper.getClassWithoutInitializingProxy(this) != HibernateProxyHelper.getClassWithoutInitializingProxy(o)) return false; - - User other = (User) o; - - if (getId() != null ? !getId().equals(other.getId()) : other.getId() != null) return false; - return getUuid() != null ? getUuid().equals(other.getUuid()) : other.getUuid() == null; + return CHSBaseEntity.equals(this, o); } @Override @@ -261,7 +258,7 @@ public void setCreatedBy(User createdBy) { } public void setCreatedDateTime(DateTime createdDateTime) { - this.createdDateTime = createdDateTime; + this.createdDateTime = DateTimeUtil.toInstant(createdDateTime); } public void setLastModifiedBy(User lastModifiedBy) { @@ -269,7 +266,7 @@ public void setLastModifiedBy(User lastModifiedBy) { } public void setLastModifiedDateTime(DateTime lastModifiedDateTime) { - this.lastModifiedDateTime = lastModifiedDateTime; + this.lastModifiedDateTime = DateTimeUtil.toInstant(lastModifiedDateTime); } public User getCreatedBy() { @@ -285,7 +282,7 @@ public String getLastModifiedByUserName() { } public DateTime getCreatedDateTime() { - return createdDateTime; + return DateTimeUtil.toJodaDateTime(createdDateTime); } public User getLastModifiedBy() { @@ -293,7 +290,7 @@ public User getLastModifiedBy() { } public DateTime getLastModifiedDateTime() { - return lastModifiedDateTime; + return DateTimeUtil.toJodaDateTime(lastModifiedDateTime); } public JsonObject getSyncSettings() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/UserGroup.java b/avni-server-api/src/main/java/org/avni/server/domain/UserGroup.java index 67d4eb69b..87276fa7b 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/UserGroup.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/UserGroup.java @@ -2,10 +2,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.UUID; @Entity diff --git a/avni-server-api/src/main/java/org/avni/server/domain/UserSubject.java b/avni-server-api/src/main/java/org/avni/server/domain/UserSubject.java index ee4f463a0..5aeeaa8ee 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/UserSubject.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/UserSubject.java @@ -1,7 +1,7 @@ package org.avni.server.domain; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; @Entity public class UserSubject extends OrganisationAwareEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/UserSubjectAssignment.java b/avni-server-api/src/main/java/org/avni/server/domain/UserSubjectAssignment.java index 811711a8c..5dd3853df 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/UserSubjectAssignment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/UserSubjectAssignment.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "user_subject_assignment") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/Video.java b/avni-server-api/src/main/java/org/avni/server/domain/Video.java index c82bf7680..6f7ec4b58 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/Video.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/Video.java @@ -1,10 +1,9 @@ package org.avni.server.domain; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; import org.hibernate.annotations.BatchSize; -import javax.persistence.Entity; -import javax.persistence.Table; - @Entity @Table(name = "video") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/VideoTelemetric.java b/avni-server-api/src/main/java/org/avni/server/domain/VideoTelemetric.java index 2487b9096..7dba9c4fe 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/VideoTelemetric.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/VideoTelemetric.java @@ -1,10 +1,12 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "video_telemetric") @@ -22,10 +24,10 @@ public class VideoTelemetric extends CHSBaseEntity { private Double videoEndTime; @Column(name = "player_close_time") - private DateTime playerCloseTime; + private Instant playerCloseTime; @Column(name = "player_open_time") - private DateTime playerOpenTime; + private Instant playerOpenTime; @ManyToOne(fetch = FetchType.LAZY) @NotNull @@ -41,7 +43,7 @@ public class VideoTelemetric extends CHSBaseEntity { private Long organisationId; @Column(name="created_datetime") - private DateTime createdDatetime; + private Instant createdDatetime; public Double getVideoStartTime() { return videoStartTime; @@ -60,19 +62,19 @@ public void setVideoEndTime(Double videoEndTime) { } public DateTime getPlayerCloseTime() { - return playerCloseTime; + return DateTimeUtil.toJodaDateTime(playerCloseTime); } public void setPlayerCloseTime(DateTime playerCloseTime) { - this.playerCloseTime = playerCloseTime; + this.playerCloseTime = DateTimeUtil.toInstant(playerCloseTime); } public DateTime getPlayerOpenTime() { - return playerOpenTime; + return DateTimeUtil.toJodaDateTime(playerOpenTime); } public void setPlayerOpenTime(DateTime playerOpenTime) { - this.playerOpenTime = playerOpenTime; + this.playerOpenTime = DateTimeUtil.toInstant(playerOpenTime); } public Video getVideo() { @@ -100,10 +102,10 @@ public void setOrganisationId(Long organisationId) { } public DateTime getCreatedDatetime() { - return createdDatetime; + return DateTimeUtil.toJodaDateTime(createdDatetime); } public void setCreatedDatetime(DateTime createdDatetime) { - this.createdDatetime = createdDatetime; + this.createdDatetime = DateTimeUtil.toInstant(createdDatetime); } } diff --git a/avni-server-api/src/main/java/org/avni/server/domain/VirtualCatchment.java b/avni-server-api/src/main/java/org/avni/server/domain/VirtualCatchment.java index 3d02835de..b24a649c5 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/VirtualCatchment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/VirtualCatchment.java @@ -1,10 +1,10 @@ package org.avni.server.domain; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.CacheConcurrencyStrategy; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.Objects; @Entity diff --git a/avni-server-api/src/main/java/org/avni/server/domain/accessControl/GroupPrivilege.java b/avni-server-api/src/main/java/org/avni/server/domain/accessControl/GroupPrivilege.java index b2a0e5275..c830401d2 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/accessControl/GroupPrivilege.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/accessControl/GroupPrivilege.java @@ -1,12 +1,11 @@ package org.avni.server.domain.accessControl; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.*; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "group_privilege") @JsonIgnoreProperties({"group", "privilege", "subjectType", "program", "programEncounterType", "encounterType", "checklistDetail"}) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/accessControl/Privilege.java b/avni-server-api/src/main/java/org/avni/server/domain/accessControl/Privilege.java index ac5376de8..738c959e5 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/accessControl/Privilege.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/accessControl/Privilege.java @@ -1,13 +1,16 @@ package org.avni.server.domain.accessControl; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.CHSBaseEntity; import org.avni.server.domain.PrivilegeEntityType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.joda.time.DateTime; +import java.time.Instant; + @Entity @Table(name = "privilege") @BatchSize(size = 100) @@ -29,25 +32,25 @@ public class Privilege extends CHSBaseEntity { private PrivilegeEntityType entityType; @Column - private DateTime createdDateTime; + private Instant createdDateTime; @Column - private DateTime lastModifiedDateTime; + private Instant lastModifiedDateTime; public DateTime getCreatedDateTime() { - return createdDateTime; + return DateTimeUtil.toJodaDateTime(createdDateTime); } public void setCreatedDateTime(DateTime createdDateTime) { - this.createdDateTime = createdDateTime; + this.createdDateTime = DateTimeUtil.toInstant(createdDateTime); } public DateTime getLastModifiedDateTime() { - return lastModifiedDateTime; + return DateTimeUtil.toJodaDateTime(lastModifiedDateTime); } public void setLastModifiedDateTime(DateTime lastModifiedDateTime) { - this.lastModifiedDateTime = lastModifiedDateTime; + this.lastModifiedDateTime = DateTimeUtil.toInstant(lastModifiedDateTime); } public String getName() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/app/dashboard/DashboardFilter.java b/avni-server-api/src/main/java/org/avni/server/domain/app/dashboard/DashboardFilter.java index 16b09c77e..2324c1f3e 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/app/dashboard/DashboardFilter.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/app/dashboard/DashboardFilter.java @@ -2,12 +2,15 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import org.avni.server.domain.*; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import org.avni.server.domain.Dashboard; +import org.avni.server.domain.JsonObject; +import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.util.List; import java.util.Map; @@ -20,7 +23,7 @@ public class DashboardFilter extends OrganisationAwareEntity { @JoinColumn(name = "dashboard_id") private Dashboard dashboard; - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject filterConfig; @Column diff --git a/avni-server-api/src/main/java/org/avni/server/domain/extenalSystem/ExternalSystemConfig.java b/avni-server-api/src/main/java/org/avni/server/domain/extenalSystem/ExternalSystemConfig.java index 91a5c8290..23a8902e9 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/extenalSystem/ExternalSystemConfig.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/extenalSystem/ExternalSystemConfig.java @@ -2,13 +2,11 @@ import org.avni.server.domain.JsonObject; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.JSONObjectUserType; import org.hibernate.annotations.Type; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.validation.constraints.NotNull; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; @Entity(name="external_system_config") public class ExternalSystemConfig extends OrganisationAwareEntity { @@ -20,7 +18,7 @@ public class ExternalSystemConfig extends OrganisationAwareEntity { @NotNull @Column - @Type(type = "jsonObject") + @Type(value = JSONObjectUserType.class) private JsonObject config; public SystemName getSystemName() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/framework/IdHolder.java b/avni-server-api/src/main/java/org/avni/server/domain/framework/IdHolder.java new file mode 100644 index 000000000..0f343cd76 --- /dev/null +++ b/avni-server-api/src/main/java/org/avni/server/domain/framework/IdHolder.java @@ -0,0 +1,6 @@ +package org.avni.server.domain.framework; + +public interface IdHolder { + Long getId(); + String getUuid(); +} diff --git a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelation.java b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelation.java index d3fa46537..32751c97d 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelation.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelation.java @@ -1,13 +1,13 @@ package org.avni.server.domain.individualRelationship; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; import org.hibernate.annotations.BatchSize; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationGenderMapping.java b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationGenderMapping.java index e5bac346d..8aad616d1 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationGenderMapping.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationGenderMapping.java @@ -1,12 +1,11 @@ package org.avni.server.domain.individualRelationship; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.Gender; import org.avni.server.domain.OrganisationAwareEntity; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "individual_relation_gender_mapping") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationship.java b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationship.java index 8759d0128..f1e4ff5d1 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationship.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationship.java @@ -1,15 +1,18 @@ package org.avni.server.domain.individualRelationship; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hibernate.annotations.BatchSize; -import org.hibernate.annotations.Type; -import org.joda.time.DateTime; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.Individual; import org.avni.server.domain.ObservationCollection; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.util.DateTimeUtil; +import org.hibernate.annotations.BatchSize; +import org.hibernate.annotations.Type; +import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "individual_relationship") @@ -33,13 +36,13 @@ public class IndividualRelationship extends OrganisationAwareEntity { private Individual individualB; @Column - private DateTime enterDateTime; + private Instant enterDateTime; @Column - private DateTime exitDateTime; + private Instant exitDateTime; @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection exitObservations; public IndividualRelationshipType getRelationship() { @@ -67,19 +70,19 @@ public void setIndividualB(Individual individualB) { } public DateTime getEnterDateTime() { - return enterDateTime; + return DateTimeUtil.toJodaDateTime(enterDateTime); } public void setEnterDateTime(DateTime enterDateTime) { - this.enterDateTime = enterDateTime; + this.enterDateTime = DateTimeUtil.toInstant(enterDateTime); } public DateTime getExitDateTime() { - return exitDateTime; + return DateTimeUtil.toJodaDateTime(exitDateTime); } public void setExitDateTime(DateTime exitDateTime) { - this.exitDateTime = exitDateTime; + this.exitDateTime = DateTimeUtil.toInstant(exitDateTime); } public ObservationCollection getExitObservations() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationshipType.java b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationshipType.java index 20b65a6a7..c62844330 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationshipType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/individualRelationship/IndividualRelationshipType.java @@ -1,11 +1,10 @@ package org.avni.server.domain.individualRelationship; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "individual_relationship_type") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationCategory.java b/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationCategory.java index c38282fe4..86c5c8eba 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationCategory.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationCategory.java @@ -1,9 +1,8 @@ package org.avni.server.domain.organisation; +import jakarta.persistence.Entity; import org.avni.server.domain.CHSEntity; -import javax.persistence.Entity; - @Entity public class OrganisationCategory extends CHSEntity { public static final String Production = "Production"; diff --git a/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationStatus.java b/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationStatus.java index eff982d21..bd1680b8a 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/organisation/OrganisationStatus.java @@ -2,7 +2,7 @@ import org.avni.server.domain.CHSEntity; -import javax.persistence.Entity; +import jakarta.persistence.*; @Entity public class OrganisationStatus extends CHSEntity { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/program/SubjectProgramEligibility.java b/avni-server-api/src/main/java/org/avni/server/domain/program/SubjectProgramEligibility.java index febd1446f..072642c94 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/program/SubjectProgramEligibility.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/program/SubjectProgramEligibility.java @@ -1,14 +1,17 @@ package org.avni.server.domain.program; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.Individual; import org.avni.server.domain.ObservationCollection; import org.avni.server.domain.OrganisationAwareEntity; import org.avni.server.domain.Program; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity(name = "subject_program_eligibility") public class SubjectProgramEligibility extends OrganisationAwareEntity { @@ -26,10 +29,10 @@ public class SubjectProgramEligibility extends OrganisationAwareEntity { private boolean isEligible; @Column - private DateTime checkDate; + private Instant checkDate; @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; public Individual getSubject() { @@ -57,11 +60,11 @@ public void setEligible(boolean eligible) { } public DateTime getCheckDate() { - return checkDate; + return DateTimeUtil.toJodaDateTime(checkDate); } public void setCheckDate(DateTime checkDate) { - this.checkDate = checkDate; + this.checkDate = DateTimeUtil.toInstant(checkDate); } public ObservationCollection getObservations() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/task/Task.java b/avni-server-api/src/main/java/org/avni/server/domain/task/Task.java index 218ae53bc..375a8975a 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/task/Task.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/task/Task.java @@ -1,15 +1,18 @@ package org.avni.server.domain.task; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.Individual; import org.avni.server.domain.ObservationCollection; import org.avni.server.domain.OrganisationAwareEntity; import org.avni.server.domain.User; +import org.avni.server.framework.hibernate.ObservationCollectionUserType; +import org.avni.server.util.DateTimeUtil; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; import org.joda.time.DateTime; -import javax.persistence.*; -import javax.validation.constraints.NotNull; +import java.time.Instant; @Entity @Table(name = "task") @@ -30,17 +33,17 @@ public class Task extends OrganisationAwareEntity { private TaskStatus taskStatus; @Column - private DateTime scheduledOn; + private Instant scheduledOn; @Column - private DateTime completedOn; + private Instant completedOn; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "assigned_user_id") private User assignedTo; @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection metadata; @ManyToOne(targetEntity = Individual.class, fetch = FetchType.LAZY) @@ -48,7 +51,7 @@ public class Task extends OrganisationAwareEntity { private Individual subject; @Column - @Type(type = "observations") + @Type(value = ObservationCollectionUserType.class) private ObservationCollection observations; @Column @@ -85,19 +88,19 @@ public void updateTaskStatus(TaskStatus taskStatus) { } public DateTime getScheduledOn() { - return scheduledOn; + return DateTimeUtil.toJodaDateTime(scheduledOn); } public void setScheduledOn(DateTime scheduledOn) { - this.scheduledOn = scheduledOn; + this.scheduledOn = DateTimeUtil.toInstant(scheduledOn); } public DateTime getCompletedOn() { - return completedOn; + return DateTimeUtil.toJodaDateTime(completedOn); } public void setCompletedOn(DateTime completedOn) { - this.completedOn = completedOn; + this.completedOn = DateTimeUtil.toInstant(completedOn); } public User getAssignedTo() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskStatus.java b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskStatus.java index 2d4b53930..de866b7bf 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskStatus.java @@ -1,11 +1,10 @@ package org.avni.server.domain.task; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "task_status") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskType.java b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskType.java index 3b5cab7ad..36c6eef32 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskType.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskType.java @@ -1,12 +1,12 @@ package org.avni.server.domain.task; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.hibernate.ArrayUserType; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Type; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "task_type") @BatchSize(size = 100) @@ -21,7 +21,7 @@ public class TaskType extends OrganisationAwareEntity { private TaskTypeName type; @Column(columnDefinition = "text[]") - @Type(type = "metadataSearchFields") + @Type(value = ArrayUserType.class) private String[] metadataSearchFields; public String getName() { diff --git a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskUnAssignment.java b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskUnAssignment.java index 72eaa65f8..411866dba 100644 --- a/avni-server-api/src/main/java/org/avni/server/domain/task/TaskUnAssignment.java +++ b/avni-server-api/src/main/java/org/avni/server/domain/task/TaskUnAssignment.java @@ -1,12 +1,11 @@ package org.avni.server.domain.task; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import org.avni.server.domain.OrganisationAwareEntity; import org.avni.server.domain.User; import org.hibernate.annotations.BatchSize; -import javax.persistence.*; -import javax.validation.constraints.NotNull; - @Entity @Table(name = "task_unassignment") @BatchSize(size = 100) diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/ExportBatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/exporter/ExportBatchConfiguration.java index e2a57cafc..a6ac80787 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/ExportBatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/ExportBatchConfiguration.java @@ -7,6 +7,7 @@ import org.avni.server.exporter.v2.LongitudinalExportV2TaskletImpl; import org.avni.server.framework.security.AuthService; import org.avni.server.service.ExportS3Service; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.external.request.export.ExportFilters; import org.avni.server.web.external.request.export.ExportOutput; import org.avni.server.web.external.request.export.ReportType; @@ -15,11 +16,11 @@ import org.joda.time.LocalDate; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.support.RunIdIncrementer; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -27,7 +28,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.Sort; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; +import org.springframework.transaction.PlatformTransactionManager; + import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -35,12 +38,10 @@ import static java.lang.String.format; @Configuration -@EnableBatchProcessing +//@EnableBatchProcessing public class ExportBatchConfiguration { private final int CHUNK_SIZE = 100; private final EntityManager entityManager; - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; private final ProgramEnrolmentRepository programEnrolmentRepository; private final IndividualRepository individualRepository; private final GroupSubjectRepository groupSubjectRepository; @@ -50,13 +51,13 @@ public class ExportBatchConfiguration { private final SubjectTypeRepository subjectTypeRepository; private final EncounterTypeRepository encounterTypeRepository; private final ProgramRepository programRepository; + private final JobRepository jobRepository; + private final PlatformTransactionManager platformTransactionManager; private final int longitudinalExportV2Limit; private final int legacyLongitudinalExportLimit; @Autowired - public ExportBatchConfiguration(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - ProgramEnrolmentRepository programEnrolmentRepository, + public ExportBatchConfiguration(ProgramEnrolmentRepository programEnrolmentRepository, IndividualRepository individualRepository, GroupSubjectRepository groupSubjectRepository, AuthService authService, @@ -66,11 +67,11 @@ public ExportBatchConfiguration(JobBuilderFactory jobBuilderFactory, EncounterTypeRepository encounterTypeRepository, ProgramRepository programRepository, EntityManager entityManager, + JobRepository jobRepository, + PlatformTransactionManager platformTransactionManager, @Value("${avni.longitudinal.export.v2.limit}") int longitudinalExportV2Limit, @Value("${avni.legacy.longitudinal.export.limit}") int legacyLongitudinalExportLimit ) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; this.programEnrolmentRepository = programEnrolmentRepository; this.individualRepository = individualRepository; this.groupSubjectRepository = groupSubjectRepository; @@ -81,14 +82,15 @@ public ExportBatchConfiguration(JobBuilderFactory jobBuilderFactory, this.encounterTypeRepository = encounterTypeRepository; this.programRepository = programRepository; this.entityManager = entityManager; + this.jobRepository = jobRepository; + this.platformTransactionManager = platformTransactionManager; this.longitudinalExportV2Limit = longitudinalExportV2Limit; this.legacyLongitudinalExportLimit = legacyLongitudinalExportLimit; } @Bean public Job exportVisitJob(JobCompletionNotificationListener listener, Step step1) { - return jobBuilderFactory - .get("exportVisitJob") + return new JobBuilder("exportVisitJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .start(step1) @@ -97,8 +99,7 @@ public Job exportVisitJob(JobCompletionNotificationListener listener, Step step1 @Bean public Job exportV2Job(JobCompletionNotificationListener listener, Step exportV2Step) { - return jobBuilderFactory - .get("exportVisitJob") + return new JobBuilder("exportV2Job", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .start(exportV2Step) @@ -108,8 +109,8 @@ public Job exportV2Job(JobCompletionNotificationListener listener, Step exportV2 @Bean public Step exportV2Step(Tasklet exportV2Tasklet, LongitudinalExportJobStepListener listener) { - return stepBuilderFactory.get("exportV2Step") - .tasklet(exportV2Tasklet) + return new StepBuilder("exportV2Step", jobRepository) + .tasklet(exportV2Tasklet, platformTransactionManager) .listener(listener) .build(); } @@ -143,8 +144,8 @@ private Stream truncateStream(Stream stream) { @Bean public Step step1(Tasklet tasklet, LongitudinalExportJobStepListener listener) { - return stepBuilderFactory.get("step1") - .tasklet(tasklet) + return new StepBuilder("step1", jobRepository) + .tasklet(tasklet, platformTransactionManager) .listener(listener) .build(); } @@ -204,32 +205,32 @@ public Tasklet tasklet(@Value("#{jobParameters['uuid']}") String uuid, private Stream getGroupSubjectStream(String subjectTypeUUID, List addressParam, LocalDate startDate, LocalDate endDate, Map sorts, boolean isVoidedIncluded) { SubjectType subjectType = subjectTypeRepository.findByUuid(subjectTypeUUID); - return isVoidedIncluded ? groupSubjectRepository.findAllGroupSubjects(subjectType.getId(), addressParam, startDate, endDate) : - groupSubjectRepository.findNonVoidedGroupSubjects(subjectType.getId(), addressParam, startDate, endDate); + return isVoidedIncluded ? groupSubjectRepository.findAllGroupSubjects(subjectType.getId(), addressParam, DateTimeUtil.toInstant(startDate), DateTimeUtil.toInstant(endDate)) : + groupSubjectRepository.findNonVoidedGroupSubjects(subjectType.getId(), addressParam, DateTimeUtil.toInstant(startDate), DateTimeUtil.toInstant(endDate)); } private Stream getEncounterStream(String programUUID, String encounterTypeUUID, List addressParam, DateTime startDateTime, DateTime endDateTime, boolean isVoidedIncluded) { EncounterType encounterType = encounterTypeRepository.findByUuid(encounterTypeUUID); if (programUUID == null) { - return isVoidedIncluded ? individualRepository.findAllEncounters(addressParam, startDateTime, endDateTime, encounterType.getId()) : - individualRepository.findNonVoidedEncounters(addressParam, startDateTime, endDateTime, encounterType.getId()); + return isVoidedIncluded ? individualRepository.findAllEncounters(addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime), encounterType.getId()) : + individualRepository.findNonVoidedEncounters(addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime), encounterType.getId()); } else { Program program = programRepository.findByUuid(programUUID); - return isVoidedIncluded ? programEnrolmentRepository.findAllProgramEncounters(addressParam, startDateTime, endDateTime, encounterType.getId(), program.getId()) : - programEnrolmentRepository.findNonVoidedProgramEncounters(addressParam, startDateTime, endDateTime, encounterType.getId(), program.getId()); + return isVoidedIncluded ? programEnrolmentRepository.findAllProgramEncounters(addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime), encounterType.getId(), program.getId()) : + programEnrolmentRepository.findNonVoidedProgramEncounters(addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime), encounterType.getId(), program.getId()); } } private Stream getEnrolmentStream(String programUUID, List addressParam, DateTime startDateTime, DateTime endDateTime, boolean isVoidedIncluded) { Program program = programRepository.findByUuid(programUUID); - return isVoidedIncluded ? programEnrolmentRepository.findAllEnrolments(program.getId(), addressParam, startDateTime, endDateTime) : - programEnrolmentRepository.findNonVoidedEnrolments(program.getId(), addressParam, startDateTime, endDateTime); + return isVoidedIncluded ? programEnrolmentRepository.findAllEnrolments(program.getId(), addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime)) : + programEnrolmentRepository.findNonVoidedEnrolments(program.getId(), addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime)); } private Stream getRegistrationStream(String subjectTypeUUID, List addressParam, LocalDate startDateTime, LocalDate endDateTime, boolean includeVoided) { SubjectType subjectType = subjectTypeRepository.findByUuid(subjectTypeUUID); - return includeVoided ? individualRepository.findAllIndividuals(subjectType.getId(), addressParam, startDateTime, endDateTime) : - individualRepository.findNonVoidedIndividuals(subjectType.getId(), addressParam, startDateTime, endDateTime); + return includeVoided ? individualRepository.findAllIndividuals(subjectType.getId(), addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime)) : + individualRepository.findNonVoidedIndividuals(subjectType.getId(), addressParam, DateTimeUtil.toInstant(startDateTime), DateTimeUtil.toInstant(endDateTime)); } private List getLocations(List locationIds) { diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/ExportCSVFieldExtractor.java b/avni-server-api/src/main/java/org/avni/server/exporter/ExportCSVFieldExtractor.java index 3b2ce8a83..d152cbf48 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/ExportCSVFieldExtractor.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/ExportCSVFieldExtractor.java @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.io.IOException; import java.io.Writer; import java.util.*; diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/ExportJobService.java b/avni-server-api/src/main/java/org/avni/server/exporter/ExportJobService.java index 3035ff44d..bb42786e2 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/ExportJobService.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/ExportJobService.java @@ -34,8 +34,8 @@ import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestBody; -import javax.transaction.Transactional; -import javax.validation.constraints.NotNull; +import jakarta.transaction.Transactional; +import jakarta.validation.constraints.NotNull; import java.util.UUID; @Service diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/ExportProcessor.java b/avni-server-api/src/main/java/org/avni/server/exporter/ExportProcessor.java index e05907145..9bb34d28e 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/ExportProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/ExportProcessor.java @@ -12,7 +12,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.Date; import java.util.Optional; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/LongitudinalExportTaskletImpl.java b/avni-server-api/src/main/java/org/avni/server/exporter/LongitudinalExportTaskletImpl.java index be9ef2d49..74b72a53d 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/LongitudinalExportTaskletImpl.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/LongitudinalExportTaskletImpl.java @@ -1,17 +1,18 @@ package org.avni.server.exporter; +import jakarta.persistence.EntityManager; import org.avni.server.service.ExportS3Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.DelimitedLineAggregator; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.core.io.FileSystemResource; -import javax.persistence.EntityManager; import java.io.File; import java.util.ArrayList; import java.util.Iterator; @@ -86,7 +87,8 @@ private void createFileWriter(String uuid, ExecutionContext executionContext) { private void writeToFile(List rows) throws Exception { if (rows.size() == 0) return; - writer.write(rows); + + writer.write(Chunk.of(rows.toArray(new ExportItemRow[0]))); } @Override diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2CSVFieldExtractor.java b/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2CSVFieldExtractor.java index 3d42660bf..68e36c818 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2CSVFieldExtractor.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2CSVFieldExtractor.java @@ -22,7 +22,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.io.IOException; import java.io.Writer; import java.util.*; diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2Processor.java b/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2Processor.java index 55dfb8502..5093e66d4 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2Processor.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/v2/ExportV2Processor.java @@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/exporter/v2/LongitudinalExportV2TaskletImpl.java b/avni-server-api/src/main/java/org/avni/server/exporter/v2/LongitudinalExportV2TaskletImpl.java index 99db8d021..661f8c29d 100644 --- a/avni-server-api/src/main/java/org/avni/server/exporter/v2/LongitudinalExportV2TaskletImpl.java +++ b/avni-server-api/src/main/java/org/avni/server/exporter/v2/LongitudinalExportV2TaskletImpl.java @@ -1,18 +1,19 @@ package org.avni.server.exporter.v2; +import jakarta.persistence.EntityManager; import org.avni.server.exporter.LongitudinalExportTasklet; import org.avni.server.service.ExportS3Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.DelimitedLineAggregator; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.core.io.FileSystemResource; -import javax.persistence.EntityManager; import java.io.File; import java.util.ArrayList; import java.util.Iterator; @@ -92,7 +93,7 @@ private void createFileWriter(String uuid, ExecutionContext executionContext) { private void writeToFile(List rows) throws Exception { if (rows.isEmpty()) return; - writer.write(rows); + writer.write(Chunk.of(rows.toArray(new LongitudinalExportItemRow[0]))); } @Override diff --git a/avni-server-api/src/main/java/org/avni/server/framework/api/ApiConfiguration.java b/avni-server-api/src/main/java/org/avni/server/framework/api/ApiConfiguration.java index aa7668359..a4a74c796 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/api/ApiConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/api/ApiConfiguration.java @@ -1,19 +1,18 @@ package org.avni.server.framework.api; import org.avni.server.framework.hibernate.DummyInterceptor; -import org.avni.server.framework.sync.MetadataResourceInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.handler.MappedInterceptor; @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) -public class ApiConfiguration extends WebMvcConfigurerAdapter { +public class ApiConfiguration implements WebMvcConfigurer { private final ApiResourceInterceptor apiResourceInterceptor; private DummyInterceptor dummyInterceptor; @@ -32,7 +31,6 @@ public MappedInterceptor mappedApiResourceInterceptor() { @Override public void addInterceptors(InterceptorRegistry registry) { - super.addInterceptors(registry); registry.addInterceptor(dummyInterceptor); } } diff --git a/avni-server-api/src/main/java/org/avni/server/framework/api/ApiResourceInterceptor.java b/avni-server-api/src/main/java/org/avni/server/framework/api/ApiResourceInterceptor.java index c6fdb2b8f..b8c27a04a 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/api/ApiResourceInterceptor.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/api/ApiResourceInterceptor.java @@ -1,15 +1,14 @@ package org.avni.server.framework.api; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.web.api.ApiRequestContext; import org.avni.server.web.api.ApiRequestContextHolder; import org.springframework.stereotype.Component; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import org.springframework.web.servlet.HandlerInterceptor; @Component -public class ApiResourceInterceptor extends HandlerInterceptorAdapter { +public class ApiResourceInterceptor implements HandlerInterceptor { public static final String ONE = new Integer(1).toString(); @Override diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractJsonbUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractJsonbUserType.java index 5bff0bea6..d5631a97f 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractJsonbUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractJsonbUserType.java @@ -6,24 +6,23 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.usertype.UserType; -import java.io.*; +import java.io.StringWriter; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; -public abstract class AbstractJsonbUserType extends AbstractUserType implements UserType { +public abstract class AbstractJsonbUserType extends AbstractUserType implements UserType { public final static ObjectMapper mapper = new ObjectMapper().registerModule(new JodaModule()); @Override - public int[] sqlTypes() { - return new int[]{Types.JAVA_OBJECT}; + public int getSqlType() { + return Types.JAVA_OBJECT; } @Override - public Object nullSafeGet(final ResultSet rs, final String[] names, final SharedSessionContractImplementor session, - final Object owner) throws HibernateException, SQLException { - final String cellContent = rs.getString(names[0]); + public T nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + final String cellContent = rs.getString(position); if (cellContent == null) { return null; } diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractUserType.java index bddf463cc..466730da0 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/AbstractUserType.java @@ -5,10 +5,9 @@ import java.io.*; -abstract class AbstractUserType implements UserType { - +abstract class AbstractUserType implements UserType { @Override - public Object deepCopy(final Object value) throws HibernateException { + public T deepCopy(final Object value) throws HibernateException { try { // use serialization to create a deep copy ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -19,7 +18,7 @@ public Object deepCopy(final Object value) throws HibernateException { bos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray()); - return new ObjectInputStream(bais).readObject(); + return (T) new ObjectInputStream(bais).readObject(); } catch (ClassNotFoundException | IOException ex) { throw new HibernateException(ex); } @@ -36,13 +35,13 @@ public Serializable disassemble(final Object value) throws HibernateException { } @Override - public Object assemble(final Serializable cached, final Object owner) throws HibernateException { - return this.deepCopy(cached); + public T assemble(final Serializable cached, final Object owner) throws HibernateException { + return (T) this.deepCopy(cached); } @Override - public Object replace(final Object original, final Object target, final Object owner) throws HibernateException { - return this.deepCopy(original); + public T replace(final Object original, final Object target, final Object owner) throws HibernateException { + return (T) this.deepCopy(original); } @Override @@ -51,11 +50,10 @@ public int hashCode(final Object obj) throws HibernateException { } @Override - public boolean equals(final Object obj1, final Object obj2) throws HibernateException { + public boolean equals(final T obj1, final T obj2) { if (obj1 == null) { return obj2 == null; } return obj1.equals(obj2); } - } diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ArrayUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ArrayUserType.java index 0bba80cff..2552ecbac 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ArrayUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ArrayUserType.java @@ -1,16 +1,13 @@ package org.avni.server.framework.hibernate; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.usertype.UserType; import java.sql.*; -public class ArrayUserType extends AbstractUserType implements UserType { - +public class ArrayUserType extends AbstractUserType { @Override - public int[] sqlTypes() { - return new int[]{Types.ARRAY}; + public int getSqlType() { + return Types.ARRAY; } @Override @@ -19,25 +16,24 @@ public Class returnedClass() { } @Override - public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) - throws HibernateException, SQLException { - Array array = rs.getArray(names[0]); - return array != null ? array.getArray() : null; + public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + Array array = rs.getArray(position); + return array != null ? (String[]) array.getArray() : null; } @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) - throws HibernateException, SQLException { + public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException { if (value != null && st != null) { - Array array = session.connection().createArrayOf("text", (String[]) value); + Connection connection = session.getJdbcConnectionAccess().obtainConnection(); + Array array = connection.createArrayOf("text", value); st.setArray(index, array); } else { - st.setNull(index, sqlTypes()[0]); + st.setNull(index, Types.ARRAY); } } @Override - public boolean equals(Object x, Object y) throws HibernateException { + public boolean equals(String[] x, String[] y) { if (x == null && y == null) { return true; } @@ -53,8 +49,8 @@ public boolean equals(Object x, Object y) throws HibernateException { return false; } - String[] xArray = (String[]) x; - String[] yArray = (String[]) y; + String[] xArray = x; + String[] yArray = y; if (xArray.length != yArray.length) { return false; } diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ChecklistItemUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ChecklistItemUserType.java index b3cd3731c..ac07f405d 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ChecklistItemUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ChecklistItemUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.ChecklistItemStatus; -public class ChecklistItemUserType extends AbstractJsonbUserType { +public class ChecklistItemUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return ChecklistItemStatus.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DeclarativeRuleUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DeclarativeRuleUserType.java index a2c0e2bb2..7cf4119d0 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DeclarativeRuleUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DeclarativeRuleUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.DeclarativeRule; -public class DeclarativeRuleUserType extends AbstractJsonbUserType { +public class DeclarativeRuleUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return DeclarativeRule.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DummyInterceptor.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DummyInterceptor.java index 598bcecb7..b94bb3436 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DummyInterceptor.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/DummyInterceptor.java @@ -1,15 +1,14 @@ package org.avni.server.framework.hibernate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.transaction.Transactional; import org.avni.server.dao.GenderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.Transactional; - @Component /** * Hack. Ensure a transactional data query is made at the end of a web request so that all dirty objects are flushed out. diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/JSONObjectUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/JSONObjectUserType.java index e5485f754..687b67dc7 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/JSONObjectUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/JSONObjectUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.JsonObject; -public class JSONObjectUserType extends AbstractJsonbUserType { +public class JSONObjectUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return JsonObject.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/KeyValuesUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/KeyValuesUserType.java index ae46afb3f..c01ed47bf 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/KeyValuesUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/KeyValuesUserType.java @@ -2,7 +2,7 @@ import org.avni.server.application.KeyValues; -public class KeyValuesUserType extends AbstractJsonbUserType { +public class KeyValuesUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return KeyValues.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/NextTriggerDetailsUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/NextTriggerDetailsUserType.java index 526d43a9c..6a2b51822 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/NextTriggerDetailsUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/NextTriggerDetailsUserType.java @@ -2,7 +2,7 @@ import org.avni.messaging.domain.NextTriggerDetails; -public class NextTriggerDetailsUserType extends AbstractJsonbUserType { +public class NextTriggerDetailsUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return NextTriggerDetails.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ObservationCollectionUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ObservationCollectionUserType.java index 1b9bc7d17..37bd8f1f0 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ObservationCollectionUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/ObservationCollectionUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.ObservationCollection; -public class ObservationCollectionUserType extends AbstractJsonbUserType { +public class ObservationCollectionUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return ObservationCollection.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuleDataUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuleDataUserType.java index 3616844aa..779a28859 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuleDataUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuleDataUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.RuleData; -public class RuleDataUserType extends AbstractJsonbUserType { +public class RuleDataUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return RuleData.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuledEntityUserType.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuledEntityUserType.java index 2ac55d9ba..35537e8b4 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuledEntityUserType.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/RuledEntityUserType.java @@ -2,7 +2,7 @@ import org.avni.server.domain.RuledEntity; -public class RuledEntityUserType extends AbstractJsonbUserType { +public class RuledEntityUserType extends AbstractJsonbUserType { @Override public Class returnedClass() { return RuledEntity.class; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/UpdateOrganisationHibernateInterceptor.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/UpdateOrganisationHibernateInterceptor.java index e4219deed..3262cab63 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/UpdateOrganisationHibernateInterceptor.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/UpdateOrganisationHibernateInterceptor.java @@ -2,16 +2,16 @@ import org.avni.server.domain.Organisation; import org.avni.server.domain.OrganisationAwareEntity; +import org.avni.server.framework.security.UserContextHolder; import org.hibernate.CallbackException; -import org.hibernate.EmptyInterceptor; +import org.hibernate.Interceptor; import org.hibernate.type.Type; -import org.avni.server.framework.security.UserContextHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; -public class UpdateOrganisationHibernateInterceptor extends EmptyInterceptor { +public class UpdateOrganisationHibernateInterceptor implements Interceptor, Serializable { private static final Logger logger = LoggerFactory.getLogger(UpdateOrganisationHibernateInterceptor.class.getName()); @Override diff --git a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/package-info.java b/avni-server-api/src/main/java/org/avni/server/framework/hibernate/package-info.java deleted file mode 100644 index 6ef2cef89..000000000 --- a/avni-server-api/src/main/java/org/avni/server/framework/hibernate/package-info.java +++ /dev/null @@ -1,15 +0,0 @@ -@org.hibernate.annotations.TypeDefs({ - @org.hibernate.annotations.TypeDef(name = "observations", typeClass = ObservationCollectionUserType.class), - @org.hibernate.annotations.TypeDef(name = "ruleData", typeClass = RuleDataUserType.class), - @org.hibernate.annotations.TypeDef(name = "keyValues", typeClass = KeyValuesUserType.class), - @org.hibernate.annotations.TypeDef(name = "status", typeClass = ChecklistItemUserType.class), - @org.hibernate.annotations.TypeDef(name = "jsonObject", typeClass = JSONObjectUserType.class), - @org.hibernate.annotations.TypeDef(name = "ruledEntity", typeClass = RuledEntityUserType.class), - @org.hibernate.annotations.TypeDef(name = "declarativeRule", typeClass = DeclarativeRuleUserType.class), - @org.hibernate.annotations.TypeDef(name = "metadataSearchFields", typeClass = ArrayUserType.class), - @org.hibernate.annotations.TypeDef(name = "parameters", typeClass = ArrayUserType.class), - @org.hibernate.annotations.TypeDef(name = "nextTriggerDetails", typeClass = NextTriggerDetailsUserType.class) -}) - -package org.avni.server.framework.hibernate; - diff --git a/avni-server-api/src/main/java/org/avni/server/framework/postgres/CHSPostgreSQL94Dialect.java b/avni-server-api/src/main/java/org/avni/server/framework/postgres/CHSPostgreSQL94Dialect.java deleted file mode 100644 index 6aa98e1f5..000000000 --- a/avni-server-api/src/main/java/org/avni/server/framework/postgres/CHSPostgreSQL94Dialect.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.avni.server.framework.postgres; - -import org.hibernate.dialect.PostgreSQL94Dialect; - -import java.sql.Types; - -public class CHSPostgreSQL94Dialect extends PostgreSQL94Dialect { - - private static final String JSONB = "jsonb"; - private static final String JSON = "json"; - - public CHSPostgreSQL94Dialect() { - super(); - this.registerColumnType(Types.JAVA_OBJECT, JSONB); - this.registerColumnType(Types.JAVA_OBJECT, JSON); - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/framework/rest/RepositoryConfig.java b/avni-server-api/src/main/java/org/avni/server/framework/rest/RepositoryConfig.java index 552fd26df..314473d93 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/rest/RepositoryConfig.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/rest/RepositoryConfig.java @@ -7,12 +7,13 @@ import org.avni.server.domain.organisation.OrganisationStatus; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; -import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; +import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; @Configuration -public class RepositoryConfig extends RepositoryRestConfigurerAdapter { +public class RepositoryConfig implements RepositoryRestConfigurer { @Override - public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { config.exposeIdsFor(User.class); config.exposeIdsFor(Organisation.class); config.exposeIdsFor(Catchment.class); diff --git a/avni-server-api/src/main/java/org/avni/server/framework/security/ApiSecurity.java b/avni-server-api/src/main/java/org/avni/server/framework/security/ApiSecurity.java index adaf506ee..5a294e1f8 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/security/ApiSecurity.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/security/ApiSecurity.java @@ -4,22 +4,24 @@ import org.avni.server.web.util.ErrorBodyBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity(debug = false) @Order(Ordered.LOWEST_PRECEDENCE) -public class ApiSecurity extends WebSecurityConfigurerAdapter { +public class ApiSecurity { private final AuthService authService; @Value("${avni.defaultUserName}") @@ -47,9 +49,8 @@ public ApiSecurity(AuthService authService, ErrorBodyBuilder errorBodyBuilder) { this.errorBodyBuilder = errorBodyBuilder; } - @Override - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { /* * Refer the following documents for CSP * https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP @@ -71,7 +72,7 @@ protected void configure(HttpSecurity http) throws Exception { CsrfConfigurer csrf = http.headers().frameOptions().sameOrigin().and().csrf(); HttpSecurity httpSecurity; if (csrfEnabled) - httpSecurity = csrf.ignoringAntMatchers("/api/**").csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and(); + httpSecurity = csrf.ignoringRequestMatchers("/api/**").csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and(); else httpSecurity = csrf.disable(); @@ -80,7 +81,8 @@ protected void configure(HttpSecurity http) throws Exception { .httpBasic().disable() .authorizeRequests().anyRequest().permitAll() .and() - .addFilter(new AuthenticationFilter(authenticationManager(), authService, idpType, defaultUserName, avniBlacklistedUrlsFile, errorBodyBuilder)) + .addFilterBefore(new AuthenticationFilter(authService, idpType, defaultUserName, avniBlacklistedUrlsFile, errorBodyBuilder), BasicAuthenticationFilter.class) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + return httpSecurity.build(); } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/server/framework/security/AuthTokenManager.java b/avni-server-api/src/main/java/org/avni/server/framework/security/AuthTokenManager.java index f6732dc05..539736a8a 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/security/AuthTokenManager.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/security/AuthTokenManager.java @@ -2,12 +2,12 @@ import com.auth0.jwt.JWT; import com.auth0.jwt.interfaces.DecodedJWT; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.web.LogoutController; import org.springframework.util.StringUtils; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.Date; import java.util.regex.Pattern; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/security/AuthenticationFilter.java b/avni-server-api/src/main/java/org/avni/server/framework/security/AuthenticationFilter.java index 1a00dcf83..63ca29966 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/security/AuthenticationFilter.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/security/AuthenticationFilter.java @@ -2,6 +2,10 @@ import com.fasterxml.jackson.core.type.TypeReference; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.config.IdpType; import org.avni.server.domain.UserContext; import org.avni.server.domain.accessControl.AvniAccessException; @@ -11,20 +15,15 @@ import org.avni.server.web.util.ErrorBodyBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import static org.avni.server.framework.security.ResourceProtectionStatus.isProtected; -public class AuthenticationFilter extends BasicAuthenticationFilter { +public class AuthenticationFilter extends OncePerRequestFilter { public static final String USER_NAME_HEADER = "USER-NAME"; public static final String AUTH_TOKEN_HEADER = "AUTH-TOKEN"; public static final String ORGANISATION_UUID = "ORGANISATION-UUID"; @@ -36,8 +35,8 @@ public class AuthenticationFilter extends BasicAuthenticationFilter { private final List blacklistedUrls; private final ErrorBodyBuilder errorBodyBuilder; - public AuthenticationFilter(AuthenticationManager authenticationManager, AuthService authService, IdpType idpType, String defaultUserName, String avniBlacklistedUrlsFile, ErrorBodyBuilder errorBodyBuilder) throws IOException { - super(authenticationManager); + public AuthenticationFilter(AuthService authService, IdpType idpType, String defaultUserName, String avniBlacklistedUrlsFile, ErrorBodyBuilder errorBodyBuilder) throws IOException { + super(); this.authService = authService; this.idpType = idpType; this.defaultUserName = defaultUserName; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/security/LimitHostNamesFilter.java b/avni-server-api/src/main/java/org/avni/server/framework/security/LimitHostNamesFilter.java index 4b3ed48a0..a933e4713 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/security/LimitHostNamesFilter.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/security/LimitHostNamesFilter.java @@ -1,5 +1,9 @@ package org.avni.server.framework.security; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -7,10 +11,6 @@ import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/security/ResourceProtectionStatus.java b/avni-server-api/src/main/java/org/avni/server/framework/security/ResourceProtectionStatus.java index b558e0053..483831b55 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/security/ResourceProtectionStatus.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/security/ResourceProtectionStatus.java @@ -1,8 +1,8 @@ package org.avni.server.framework.security; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/sync/MetadataResourceInterceptor.java b/avni-server-api/src/main/java/org/avni/server/framework/sync/MetadataResourceInterceptor.java index 128d2ca3d..d551128fd 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/sync/MetadataResourceInterceptor.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/sync/MetadataResourceInterceptor.java @@ -1,24 +1,24 @@ package org.avni.server.framework.sync; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.UserUtil; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; -import org.avni.server.util.UserUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.servlet.HandlerInterceptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; @Component -public class MetadataResourceInterceptor extends HandlerInterceptorAdapter { +public class MetadataResourceInterceptor implements HandlerInterceptor { private final UserUtil userUtil; private static final HashSet endOfLifeEndpoints1 = new HashSet() {{ diff --git a/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestFilter.java b/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestFilter.java index 475bc0d06..7b37f77be 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestFilter.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestFilter.java @@ -1,6 +1,9 @@ package org.avni.server.framework.sync; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; import org.avni.server.framework.json.JsonEncoder; import org.owasp.encoder.Encode; import org.slf4j.Logger; @@ -9,9 +12,6 @@ import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; import java.io.*; import java.util.HashMap; import java.util.Map; diff --git a/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestWrapper.java b/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestWrapper.java index 6530a96a1..556f6bdc7 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestWrapper.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/sync/MutableRequestWrapper.java @@ -1,7 +1,8 @@ package org.avni.server.framework.sync; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; + import java.util.*; public class MutableRequestWrapper extends HttpServletRequestWrapper { diff --git a/avni-server-api/src/main/java/org/avni/server/framework/sync/SyncConfiguration.java b/avni-server-api/src/main/java/org/avni/server/framework/sync/SyncConfiguration.java index 6444b8c28..b59299c24 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/sync/SyncConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/sync/SyncConfiguration.java @@ -7,14 +7,14 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.handler.MappedInterceptor; import java.util.stream.Stream; @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) -public class SyncConfiguration extends WebMvcConfigurerAdapter { +public class SyncConfiguration implements WebMvcConfigurer { private final TransactionalResourceInterceptor transactionalResourceInterceptor; private final MetadataResourceInterceptor metadataResourceInterceptor; private DummyInterceptor dummyInterceptor; @@ -108,7 +108,6 @@ public MappedInterceptor mappedMetadataResourceInterceptor() { @Override public void addInterceptors(InterceptorRegistry registry) { - super.addInterceptors(registry); registry.addInterceptor(dummyInterceptor); } } diff --git a/avni-server-api/src/main/java/org/avni/server/framework/sync/TransactionalResourceInterceptor.java b/avni-server-api/src/main/java/org/avni/server/framework/sync/TransactionalResourceInterceptor.java index 087ca9f91..c8cf1b165 100644 --- a/avni-server-api/src/main/java/org/avni/server/framework/sync/TransactionalResourceInterceptor.java +++ b/avni-server-api/src/main/java/org/avni/server/framework/sync/TransactionalResourceInterceptor.java @@ -1,23 +1,23 @@ package org.avni.server.framework.sync; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.UserUtil; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; -import org.avni.server.util.UserUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.servlet.HandlerInterceptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @Component -public class TransactionalResourceInterceptor extends HandlerInterceptorAdapter { +public class TransactionalResourceInterceptor implements HandlerInterceptor { private final Map nowMap = new HashMap() {{ put("live", 10); diff --git a/avni-server-api/src/main/java/org/avni/server/geo/PointType.java b/avni-server-api/src/main/java/org/avni/server/geo/PointType.java index f7a55906d..541e278da 100644 --- a/avni-server-api/src/main/java/org/avni/server/geo/PointType.java +++ b/avni-server-api/src/main/java/org/avni/server/geo/PointType.java @@ -4,6 +4,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -16,11 +17,10 @@ * @author Jesse Costello-Good * @version $Id$ */ -public class PointType implements UserType { - +public class PointType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{java.sql.Types.OTHER}; + public int getSqlType() { + return Types.OTHER; } @Override @@ -29,7 +29,7 @@ public Class returnedClass() { } @Override - public boolean equals(Object o, Object o1) throws HibernateException { + public boolean equals(Point o, Point o1) { if (o == null && o1 == null) return true; else if (o == null || o1 == null) @@ -38,11 +38,8 @@ else if (o == null || o1 == null) } @Override - public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor sessionImplementor, Object owner) throws HibernateException, SQLException { - if (names.length != 1) - throw new IllegalArgumentException("names.length != 1, names = " + names); - - PGpoint value = (PGpoint) resultSet.getObject(names[0]); + public Point nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + PGpoint value = (PGpoint) rs.getObject(position); if (value == null) { return null; @@ -52,21 +49,21 @@ public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionCont } @Override - public void nullSafeSet(PreparedStatement preparedStatement, Object value, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException { + public void nullSafeSet(PreparedStatement st, Point value, int index, SharedSessionContractImplementor session) throws SQLException { if (value == null) { - preparedStatement.setNull(i, java.sql.Types.OTHER); + st.setNull(index, java.sql.Types.OTHER); } else { - preparedStatement.setObject(i, new PGpoint(((Point) value).getX(), ((Point) value).getY())); + st.setObject(index, new PGpoint(value.getX(), value.getY())); } } @Override - public Object deepCopy(Object o) throws HibernateException { + public Point deepCopy(Point o) throws HibernateException { if (o == null) return null; try { - return ((Point) o).clone(); + return (Point) o.clone(); } catch (CloneNotSupportedException e) { throw new IllegalArgumentException(e); } @@ -78,22 +75,22 @@ public boolean isMutable() { } @Override - public int hashCode(Object o) throws HibernateException { + public int hashCode(Point o) throws HibernateException { return o.hashCode(); } @Override - public Serializable disassemble(Object o) throws HibernateException { + public Serializable disassemble(Point o) throws HibernateException { return (Serializable) o; } @Override - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; + public Point assemble(Serializable cached, Object owner) throws HibernateException { + return (Point) cached; } @Override - public Object replace(Object original, Object target, Object owner) throws HibernateException { + public Point replace(Point original, Point managed, Object owner) { return original; } } diff --git a/avni-server-api/src/main/java/org/avni/server/identifier/PrefixedUserPoolBasedIdentifierGenerator.java b/avni-server-api/src/main/java/org/avni/server/identifier/PrefixedUserPoolBasedIdentifierGenerator.java index 1eb005466..75508b8b5 100644 --- a/avni-server-api/src/main/java/org/avni/server/identifier/PrefixedUserPoolBasedIdentifierGenerator.java +++ b/avni-server-api/src/main/java/org/avni/server/identifier/PrefixedUserPoolBasedIdentifierGenerator.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Iterator; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/identifier/UserPoolBasedIdentifierGenerator.java b/avni-server-api/src/main/java/org/avni/server/identifier/UserPoolBasedIdentifierGenerator.java index 9ad99093d..20a6084b7 100644 --- a/avni-server-api/src/main/java/org/avni/server/identifier/UserPoolBasedIdentifierGenerator.java +++ b/avni-server-api/src/main/java/org/avni/server/identifier/UserPoolBasedIdentifierGenerator.java @@ -1,5 +1,6 @@ package org.avni.server.identifier; +import jakarta.transaction.Transactional; import org.avni.server.domain.IdentifierAssignment; import org.avni.server.domain.IdentifierSource; import org.avni.server.domain.User; @@ -7,8 +8,6 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; - import static org.avni.server.service.DeviceAwareService.WEB_DEVICE_ID; diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/JobService.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/JobService.java index fb2061823..3919d5a24 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/JobService.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/JobService.java @@ -1,10 +1,11 @@ package org.avni.server.importer.batch; +import jakarta.transaction.Transactional; +import jakarta.validation.constraints.NotNull; import org.avni.server.dao.AvniJobRepository; import org.avni.server.dao.JobStatus; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.ObjectInfo; -import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.*; @@ -19,10 +20,8 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; -import javax.validation.constraints.NotNull; +import java.time.LocalDateTime; import java.util.Arrays; -import java.util.Date; import static java.lang.String.format; import static org.springframework.batch.core.BatchStatus.*; @@ -50,16 +49,16 @@ public JobService(JobExplorer jobExplorer, JobRepository jobRepository, Job impo public void retryJobsFailedInLast2Hours() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { for (JobExecution jobExecution : jobExplorer.findRunningJobExecutions(importJob.getName())) { BatchStatus status = jobExecution.getStatus(); - Date lastUpdated = jobExecution.getLastUpdated(); - Date nowMinus2Hours = new DateTime().minusHours(2).toDate(); - if (nowMinus2Hours.before(lastUpdated) && Arrays.asList(STARTING, STARTED, UNKNOWN).contains(status)) { + LocalDateTime lastUpdated = jobExecution.getLastUpdated(); + LocalDateTime nowMinus2Hours = LocalDateTime.now().minusHours(2); + if (nowMinus2Hours.isBefore(lastUpdated) && Arrays.asList(STARTING, STARTED, UNKNOWN).contains(status)) { jobExecution.upgradeStatus(BatchStatus.FAILED); - jobExecution.setEndTime(new Date()); + jobExecution.setEndTime(LocalDateTime.now()); jobRepository.update(jobExecution); for (StepExecution stepExecution : jobExecution.getStepExecutions()) { if (Arrays.asList(STARTING, STARTED, UNKNOWN).contains(stepExecution.getStatus())) { stepExecution.upgradeStatus(BatchStatus.FAILED); - stepExecution.setEndTime(new Date()); + stepExecution.setEndTime(LocalDateTime.now()); jobRepository.update(stepExecution); } } diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/BatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/BatchConfiguration.java index 040ce4ad7..5844fc963 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/BatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/BatchConfiguration.java @@ -7,14 +7,13 @@ import org.avni.server.util.CollectionUtil; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.FlatFileParseException; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; @@ -29,6 +28,7 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; import java.io.*; import java.util.ArrayList; @@ -38,20 +38,19 @@ import static org.avni.server.service.ImportLocationsConstants.EXAMPLE; @Configuration -@EnableBatchProcessing +//@EnableBatchProcessing @EnableScheduling public class BatchConfiguration { - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; private final JobRepository jobRepository; + private final PlatformTransactionManager platformTransactionManager; private final S3Service s3Service; @Autowired - public BatchConfiguration(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository, + public BatchConfiguration(JobRepository jobRepository, + PlatformTransactionManager platformTransactionManager, @Qualifier("BatchS3Service") S3Service s3Service) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; this.jobRepository = jobRepository; + this.platformTransactionManager = platformTransactionManager; this.s3Service = s3Service; } @@ -75,7 +74,7 @@ public FlatFileItemReader csvFileItemReader(@Value("#{jobParameters['s3Key' @Bean public Job importJob(ErrorFileCreatorListener listener, Step importStep) { - return jobBuilderFactory.get("importJob") + return new JobBuilder("importJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .flow(importStep) @@ -87,8 +86,8 @@ public Job importJob(ErrorFileCreatorListener listener, Step importStep) { public Step importStep(FlatFileItemReader csvFileItemReader, CsvFileItemWriter csvFileItemWriter, ErrorFileWriterListener errorFileWriterListener) { - return stepBuilderFactory.get("importStep") - .chunk(1) + return new StepBuilder("importStep", jobRepository) + .chunk(1, platformTransactionManager) .reader(csvFileItemReader) .writer(csvFileItemWriter) .faultTolerant() @@ -104,7 +103,7 @@ public Step importStep(FlatFileItemReader csvFileItemReader, @Bean public JobLauncher bgJobLauncher() { - return new SimpleJobLauncher() {{ + return new TaskExecutorJobLauncher() {{ setJobRepository(jobRepository); setTaskExecutor(new ThreadPoolTaskExecutor() {{ setCorePoolSize(1); diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/ErrorFileCreatorListener.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/ErrorFileCreatorListener.java index 1413c1049..6a8d43781 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/ErrorFileCreatorListener.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/ErrorFileCreatorListener.java @@ -1,5 +1,6 @@ package org.avni.server.importer.batch.csv; +import jakarta.annotation.PostConstruct; import org.avni.server.framework.security.AuthService; import org.avni.server.service.BulkUploadS3Service; import org.avni.server.service.ObjectInfo; @@ -14,7 +15,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.io.*; import static java.lang.String.format; diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/AddressLevelCreator.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/AddressLevelCreator.java index 1146fff3d..4174ed43b 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/AddressLevelCreator.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/AddressLevelCreator.java @@ -5,10 +5,10 @@ import org.avni.server.domain.AddressLevelType; import org.avni.server.domain.AddressLevelTypes; import org.avni.server.importer.batch.model.Row; -import org.jadira.usertype.spi.utils.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/RuleServerInvoker.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/RuleServerInvoker.java index 32f9df280..ad0ee2484 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/RuleServerInvoker.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/creator/RuleServerInvoker.java @@ -1,7 +1,6 @@ package org.avni.server.importer.batch.csv.creator; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.joda.JodaModule; import org.avni.server.application.Form; import org.avni.server.domain.Encounter; import org.avni.server.domain.Individual; @@ -51,15 +50,13 @@ public RuleServerInvoker(RuleServiceClient restClient, private UploadRuleServerResponseContract invokeRuleServer(Row row, Form form, Object entity, List allErrorMsgs) throws Exception { ObjectMapper mapper = ObjectMapperSingleton.getObjectMapper(); - mapper.registerModule(new JodaModule()); UploadRuleServerRequestContract contract = UploadRuleServerRequestContract.buildRuleServerContract(row, form, entity); - String ruleResponse = restClient.post("/api/upload", contract); - UploadRuleServerResponseContract uploadRuleServerResponseContract = mapper.readValue(ruleResponse, UploadRuleServerResponseContract.class); - allErrorMsgs.addAll(uploadRuleServerResponseContract.getErrors()); + UploadRuleServerResponseContract ruleResponse = (UploadRuleServerResponseContract) restClient.post("/api/upload", contract, UploadRuleServerResponseContract.class); + allErrorMsgs.addAll(ruleResponse.getErrors()); if (allErrorMsgs.size() > 0) { throw new Exception(String.join(", ", allErrorMsgs)); } - return uploadRuleServerResponseContract; + return ruleResponse; } public UploadRuleServerResponseContract getRuleServerResult(Row row, Form form, Individual individual, List allErrorMsgs) throws Exception { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationCreator.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationCreator.java index b98dfbd13..69ca998d1 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationCreator.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationCreator.java @@ -1,6 +1,7 @@ package org.avni.server.importer.batch.csv.writer; import com.google.common.collect.Sets; +import jakarta.transaction.Transactional; import org.avni.server.builder.BuilderException; import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.dao.LocationRepository; @@ -20,7 +21,6 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditor.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditor.java index 3f31c5ceb..4ffb0d702 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditor.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditor.java @@ -1,5 +1,6 @@ package org.avni.server.importer.batch.csv.writer; +import jakarta.transaction.Transactional; import org.avni.server.dao.LocationRepository; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.AddressLevelType; @@ -12,7 +13,6 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/CsvFileItemWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/CsvFileItemWriter.java index 8998de45b..fdf280c21 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/CsvFileItemWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/CsvFileItemWriter.java @@ -3,13 +3,13 @@ import org.avni.server.framework.security.AuthService; import org.avni.server.importer.batch.model.Row; import org.springframework.batch.core.configuration.annotation.JobScope; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashMap; -import java.util.List; import java.util.Map; import static java.lang.String.format; @@ -57,9 +57,9 @@ private ItemWriter getWriter() { } @Override - public void write(List rows) throws Exception { + public void write(Chunk chunk) throws Exception { authService.authenticateByUserId(userId, organisationUUID); - getWriter().write(rows); + getWriter().write(chunk); } public Long getUserId() { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/EncounterWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/EncounterWriter.java index 2a5bdea8d..f831b264a 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/EncounterWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/EncounterWriter.java @@ -9,12 +9,13 @@ import org.avni.server.domain.EntityApprovalStatus; import org.avni.server.domain.Individual; import org.avni.server.importer.batch.csv.contract.UploadRuleServerResponseContract; +import org.avni.server.importer.batch.csv.creator.*; import org.avni.server.importer.batch.csv.writer.header.EncounterHeaders; import org.avni.server.importer.batch.model.Row; -import org.avni.server.importer.batch.csv.creator.*; import org.avni.server.service.EncounterService; import org.avni.server.service.ObservationService; import org.avni.server.service.OrganisationConfigService; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -66,8 +67,8 @@ public EncounterWriter(EncounterRepository encounterRepository, } @Override - public void write(List rows) throws Exception { - for (Row row : rows) write(row); + public void write(Chunk chunk) throws Exception { + for (Row row : chunk.getItems()) write(row); } private void write(Row row) throws Exception { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/GroupSubjectWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/GroupSubjectWriter.java index 34a56d412..6d74d7ab0 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/GroupSubjectWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/GroupSubjectWriter.java @@ -17,6 +17,7 @@ import org.avni.server.service.GroupSubjectService; import org.avni.server.service.HouseholdService; import org.joda.time.LocalDate; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -55,8 +56,8 @@ public GroupSubjectWriter(GroupSubjectRepository groupSubjectRepository, } @Override - public void write(List rows) throws Exception { - for (Row row : rows) write(row); + public void write(Chunk chunk) throws Exception { + for (Row row : chunk.getItems()) write(row); } private void write(Row row) throws Exception { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/LocationWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/LocationWriter.java index ca96e7b50..79e0562d0 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/LocationWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/LocationWriter.java @@ -2,14 +2,12 @@ import org.avni.server.importer.batch.model.Row; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import java.util.*; - @StepScope @Component public class LocationWriter implements ItemWriter { @@ -27,11 +25,11 @@ public LocationWriter(BulkLocationCreator bulkLocationCreator, BulkLocationEdito } @Override - public void write(List rows) { + public void write(Chunk chunk) throws Exception { if (LocationUploadMode.isCreateMode(locationUploadMode)) { - this.bulkLocationCreator.write(rows, locationHierarchy); + this.bulkLocationCreator.write(chunk.getItems(), locationHierarchy); } else { - this.bulkLocationEditor.write(rows); + this.bulkLocationEditor.write(chunk.getItems()); } } diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEncounterWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEncounterWriter.java index 7206ca5cb..c1423ba13 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEncounterWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEncounterWriter.java @@ -10,12 +10,13 @@ import org.avni.server.domain.ProgramEnrolment; import org.avni.server.domain.SubjectType; import org.avni.server.importer.batch.csv.contract.UploadRuleServerResponseContract; +import org.avni.server.importer.batch.csv.creator.*; import org.avni.server.importer.batch.csv.writer.header.ProgramEncounterHeaders; import org.avni.server.importer.batch.model.Row; -import org.avni.server.importer.batch.csv.creator.*; import org.avni.server.service.ObservationService; import org.avni.server.service.OrganisationConfigService; import org.avni.server.service.ProgramEncounterService; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -70,8 +71,8 @@ public ProgramEncounterWriter(ProgramEncounterRepository programEncounterReposit } @Override - public void write(List rows) throws Exception { - for (Row row : rows) write(row); + public void write(Chunk chunk) throws Exception { + for (Row row : chunk.getItems()) write(row); } private void write(Row row) throws Exception { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEnrolmentWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEnrolmentWriter.java index b78982aef..3c04ac4b5 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEnrolmentWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/ProgramEnrolmentWriter.java @@ -16,6 +16,7 @@ import org.avni.server.service.OrganisationConfigService; import org.avni.server.service.ProgramEnrolmentService; import org.joda.time.LocalDate; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -69,8 +70,8 @@ public ProgramEnrolmentWriter(ProgramEnrolmentRepository programEnrolmentReposit } @Override - public void write(List rows) throws Exception { - for (Row row : rows) write(row); + public void write(Chunk chunk) throws Exception { + for (Row row : chunk.getItems()) write(row); } private void write(Row row) throws Exception { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/SubjectWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/SubjectWriter.java index 1dfd9a776..4a13a8734 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/SubjectWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/SubjectWriter.java @@ -12,13 +12,14 @@ import org.avni.server.importer.batch.csv.writer.header.SubjectHeaders; import org.avni.server.importer.batch.model.Row; import org.avni.server.service.*; -import org.jadira.usertype.spi.utils.lang.StringUtils; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; import java.io.Serializable; import java.util.ArrayList; @@ -76,8 +77,8 @@ public SubjectWriter(IndividualRepository individualRepository, } @Override - public void write(List rows) throws Exception { - for (Row row : rows) write(row); + public void write(Chunk chunk) throws Exception { + for (Row row : chunk.getItems()) write(row); } private void write(Row row) throws Exception { @@ -136,10 +137,10 @@ private void write(Row row) throws Exception { private void setProfilePicture(SubjectType subjectType, Individual individual, Row row, List errorMsgs) { try { String profilePicUrl = row.get(SubjectHeaders.profilePicture); - if(StringUtils.isNotEmpty(profilePicUrl) && subjectType.isAllowProfilePicture()) { + if(!StringUtils.isEmpty(profilePicUrl) && subjectType.isAllowProfilePicture()) { individual.setProfilePicture(s3Service .uploadProfilePic(profilePicUrl, null)); - } else if(StringUtils.isNotEmpty(profilePicUrl)) { + } else if(!StringUtils.isEmpty(profilePicUrl)) { errorMsgs.add(String.format("Not allowed to set '%s'", SubjectHeaders.profilePicture)); } } catch (Exception e) { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriter.java index 4ccc3843e..b0dd58b5b 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriter.java @@ -1,6 +1,7 @@ package org.avni.server.importer.batch.csv.writer; import com.google.common.collect.Sets; +import jakarta.transaction.Transactional; import org.avni.server.dao.LocationRepository; import org.avni.server.dao.UserRepository; import org.avni.server.domain.Locale; @@ -14,13 +15,13 @@ import org.avni.server.util.RegionUtil; import org.avni.server.util.S; import org.avni.server.web.request.syncAttribute.UserSyncSettings; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import javax.transaction.Transactional; import java.io.Serializable; import java.util.*; import java.util.regex.Matcher; @@ -79,7 +80,8 @@ public UserAndCatchmentWriter(CatchmentService catchmentService, @Transactional(Transactional.TxType.REQUIRES_NEW) @Override - public void write(List rows) throws IDPException { + public void write(Chunk chunk) throws IDPException { + List rows = chunk.getItems(); if (!CollectionUtils.isEmpty(rows)) { validateHeaders(rows.get(0).getHeaders()); for (Row row : rows) write(row); diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/model/CustomJobParameter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/model/CustomJobParameter.java index bf82a24ce..ba256372a 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/model/CustomJobParameter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/model/CustomJobParameter.java @@ -4,13 +4,13 @@ import java.io.Serializable; -public class CustomJobParameter extends JobParameter { +public class CustomJobParameter extends JobParameter { private final T customParam; public CustomJobParameter(T customParam){ - super(""); + super(customParam, (Class) customParam.getClass()); this.customParam = customParam; } public T getValue(){ return customParam; } -} \ No newline at end of file +} diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/SyncAttributesBatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/SyncAttributesBatchConfiguration.java index e7c50dd61..f1c0a8d9f 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/SyncAttributesBatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/SyncAttributesBatchConfiguration.java @@ -2,37 +2,33 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; @Configuration -@EnableBatchProcessing +//@EnableBatchProcessing public class SyncAttributesBatchConfiguration { - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; private final JobRepository jobRepository; + private final PlatformTransactionManager platformTransactionManager; @Autowired - public SyncAttributesBatchConfiguration(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - JobRepository jobRepository) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; + public SyncAttributesBatchConfiguration(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) { this.jobRepository = jobRepository; + this.platformTransactionManager = platformTransactionManager; } @Bean public JobLauncher syncAttributesJobLauncher() { - return new SimpleJobLauncher() {{ + return new TaskExecutorJobLauncher() {{ setJobRepository(jobRepository); setTaskExecutor(new ThreadPoolTaskExecutor() {{ setCorePoolSize(1); @@ -45,8 +41,7 @@ public JobLauncher syncAttributesJobLauncher() { @Bean public Job syncAttributesJob(SyncAttributesJobListener listener, Step updateSyncAttributesStep) { - return jobBuilderFactory - .get("syncAttributesJob") + return new JobBuilder("syncAttributesJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .start(updateSyncAttributesStep) @@ -55,10 +50,8 @@ public Job syncAttributesJob(SyncAttributesJobListener listener, Step updateSync @Bean public Step updateSyncAttributesStep(UpdateSyncAttributesTasklet tasklet) { - return stepBuilderFactory.get("updateSyncAttributesStep") - .tasklet(tasklet) + return new StepBuilder("updateSyncAttributesStep", jobRepository) + .tasklet(tasklet, platformTransactionManager) .build(); } } - - diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationBatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationBatchConfiguration.java index cc800bfc3..476696f29 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationBatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationBatchConfiguration.java @@ -2,35 +2,33 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; @Configuration -@EnableBatchProcessing +//@EnableBatchProcessing public class BulkSubjectMigrationBatchConfiguration { - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; private final JobRepository jobRepository; + private final PlatformTransactionManager platformTransactionManager; @Autowired - public BulkSubjectMigrationBatchConfiguration(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; + public BulkSubjectMigrationBatchConfiguration(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) { this.jobRepository = jobRepository; + this.platformTransactionManager = platformTransactionManager; } @Bean public JobLauncher bulkSubjectMigrationJobLauncher() { - return new SimpleJobLauncher() {{ + return new TaskExecutorJobLauncher() {{ setJobRepository(jobRepository); setTaskExecutor(new ThreadPoolTaskExecutor() {{ setCorePoolSize(1); @@ -43,8 +41,7 @@ public JobLauncher bulkSubjectMigrationJobLauncher() { @Bean public Job bulkSubjectMigrationJob(BulkSubjectMigrationJobListener bulkSubjectMigrationJobListener, Step bulkSubjectMigrationStep) { - return jobBuilderFactory - .get("bulkSubjectMigrationJob") + return new JobBuilder("bulkSubjectMigrationJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(bulkSubjectMigrationJobListener) .start(bulkSubjectMigrationStep) @@ -53,8 +50,8 @@ public Job bulkSubjectMigrationJob(BulkSubjectMigrationJobListener bulkSubjectMi @Bean public Step bulkSubjectMigrationStep(BulkSubjectMigrationTasklet bulkSubjectMigrationTasklet) { - return stepBuilderFactory.get("bulkSubjectMigrationStep") - .tasklet(bulkSubjectMigrationTasklet) + return new StepBuilder("bulkSubjectMigrationStep", jobRepository) + .tasklet(bulkSubjectMigrationTasklet, platformTransactionManager) .build(); } } diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationJobListener.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationJobListener.java index 923d70c2f..f6236abd7 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationJobListener.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/sync/attributes/bulkmigration/BulkSubjectMigrationJobListener.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.avni.server.framework.security.AuthService; import org.avni.server.service.BulkUploadS3Service; +import org.avni.server.util.DateTimeUtil; import org.avni.server.util.ObjectMapperSingleton; import org.avni.server.web.request.BulkSubjectMigrationRequest; import org.slf4j.Logger; @@ -61,7 +62,9 @@ public void beforeJob(JobExecution jobExecution) { public void afterJob(JobExecution jobExecution) { Map failedMigrations = (Map) jobExecution.getExecutionContext().get("failedMigrations"); logger.info("Finished Bulk Subject Migration Job {} mode: {} failedCount: {} exitStatus: {} waitTime: {}ms processingTime: {}ms fileName: {}", - uuid, mode, failedMigrations.size(), jobExecution.getExitStatus(), jobExecution.getStartTime().getTime() - jobExecution.getCreateTime().getTime(), jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime(), fileName); + uuid, mode, failedMigrations.size(), jobExecution.getExitStatus(), + DateTimeUtil.getMilliSecondsDuration(jobExecution.getCreateTime(), jobExecution.getEndTime()), + DateTimeUtil.getMilliSecondsDuration(jobExecution.getStartTime(), jobExecution.getEndTime()), fileName); try { writeFailuresToFileAndUploadToS3(failedMigrations); } catch (Exception e) { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateBatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateBatchConfiguration.java index 415f487b0..2c85130c1 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateBatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateBatchConfiguration.java @@ -2,39 +2,35 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableScheduling -@EnableBatchProcessing +//@EnableBatchProcessing public class UserSubjectTypeCreateBatchConfiguration { - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; private final JobRepository jobRepository; + private final PlatformTransactionManager platformTransactionManager; @Autowired - public UserSubjectTypeCreateBatchConfiguration(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - JobRepository jobRepository) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; + public UserSubjectTypeCreateBatchConfiguration(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) { this.jobRepository = jobRepository; + this.platformTransactionManager = platformTransactionManager; } @Bean public JobLauncher userSubjectTypeCreateJobLauncher() { - return new SimpleJobLauncher() {{ + return new TaskExecutorJobLauncher() {{ setJobRepository(jobRepository); setTaskExecutor(new ThreadPoolTaskExecutor() {{ setCorePoolSize(1); @@ -47,8 +43,7 @@ public JobLauncher userSubjectTypeCreateJobLauncher() { @Bean public Job userSubjectTypeCreateJob(UserSubjectTypeCreateJobListener listener, Step userSubjectTypeCreateStep) { - return jobBuilderFactory - .get("userSubjectTypeCreateJob") + return new JobBuilder("userSubjectTypeCreateJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .start(userSubjectTypeCreateStep) @@ -57,8 +52,8 @@ public Job userSubjectTypeCreateJob(UserSubjectTypeCreateJobListener listener, S @Bean public Step userSubjectTypeCreateStep(UserSubjectTypeCreateTasklet tasklet) { - return stepBuilderFactory.get("userSubjectTypeCreateStep") - .tasklet(tasklet) + return new StepBuilder("userSubjectTypeCreateStep", jobRepository) + .tasklet(tasklet, platformTransactionManager) .build(); } } diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateTasklet.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateTasklet.java index c23f0d93d..64a34778e 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateTasklet.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/userSubjectType/UserSubjectTypeCreateTasklet.java @@ -1,5 +1,6 @@ package org.avni.server.importer.batch.userSubjectType; +import jakarta.transaction.Transactional; import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.domain.SubjectType; import org.avni.server.service.UserService; @@ -14,8 +15,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.transaction.Transactional; - @Component @JobScope public class UserSubjectTypeCreateTasklet implements Tasklet { diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/BundleZipFileImporter.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/BundleZipFileImporter.java index b7e3afa81..ef647e59c 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/BundleZipFileImporter.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/BundleZipFileImporter.java @@ -1,6 +1,7 @@ package org.avni.server.importer.batch.zip; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.PostConstruct; import org.avni.messaging.contract.MessageRuleContract; import org.avni.messaging.service.MessagingService; import org.avni.server.builder.FormBuilderException; @@ -32,13 +33,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.configuration.annotation.JobScope; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; @@ -210,7 +211,8 @@ public void authenticateUser() { } @Override - public void write(List bundleFiles) throws Exception { + public void write(Chunk chunk) throws Exception { + List bundleFiles = chunk.getItems(); BundleZip bundleZip = new BundleZip(bundleFiles.stream().collect(Collectors.toMap(BundleFile::getName, BundleFile::getContent))); for (String filename : fileSequence) { Optional fromFileName = BundleFolder.getFromFileName(filename); diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipErrorFileWriterListener.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipErrorFileWriterListener.java index 8ce7ec3b6..e25ea9707 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipErrorFileWriterListener.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipErrorFileWriterListener.java @@ -5,16 +5,17 @@ import org.avni.server.util.ExceptionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.batch.core.annotation.*; +import org.springframework.batch.core.annotation.OnProcessError; +import org.springframework.batch.core.annotation.OnReadError; +import org.springframework.batch.core.annotation.OnSkipInWrite; +import org.springframework.batch.core.annotation.OnWriteError; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.item.Chunk; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.FileWriter; import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; import static java.lang.String.format; @@ -49,7 +50,7 @@ public void onReadError(Exception e) { } @OnWriteError - public void onWriteError(Exception e, List o) { + public void onWriteError(Exception e, Chunk o) { logger.error("onWriteError", e); } diff --git a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipJobBatchConfiguration.java b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipJobBatchConfiguration.java index 4feae5c0f..e043f6912 100644 --- a/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipJobBatchConfiguration.java +++ b/avni-server-api/src/main/java/org/avni/server/importer/batch/zip/ZipJobBatchConfiguration.java @@ -4,11 +4,11 @@ import org.avni.server.service.S3Service; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.support.RunIdIncrementer; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.file.FlatFileParseException; import org.springframework.batch.item.file.transform.FlatFileFormatException; @@ -24,18 +24,16 @@ import java.io.IOException; @Configuration -@EnableBatchProcessing +//@EnableBatchProcessing @EnableScheduling public class ZipJobBatchConfiguration { - private final JobBuilderFactory jobBuilderFactory; - private final StepBuilderFactory stepBuilderFactory; + private final JobRepository jobRepository; private final S3Service s3Service; @Autowired - public ZipJobBatchConfiguration(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, + public ZipJobBatchConfiguration(JobRepository jobRepository, @Qualifier("BatchS3Service") S3Service s3Service) { - this.jobBuilderFactory = jobBuilderFactory; - this.stepBuilderFactory = stepBuilderFactory; + this.jobRepository = jobRepository; this.s3Service = s3Service; } @@ -47,7 +45,7 @@ public ItemReader zipItemReader(@Value("#{jobParameters['s3Key']}") @Bean public Job importZipJob(Step importZipStep, ZipJobCompletionNotificationListener zipJobCompletionNotificationListener) { - return jobBuilderFactory.get("importZipJob") + return new JobBuilder("importZipJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(zipJobCompletionNotificationListener) .flow(importZipStep) @@ -57,8 +55,8 @@ public Job importZipJob(Step importZipStep, ZipJobCompletionNotificationListener @Bean public Step importZipStep(ZipErrorFileWriterListener zipErrorFileWriterListener, ItemReader zipItemReader, BundleZipFileImporter bundleZipFileImporter, PlatformTransactionManager platformTransactionManager) { - return stepBuilderFactory.get("importZipStep") - .chunk(1) + return new StepBuilder("importZipStep", jobRepository) + .chunk(1, platformTransactionManager) .reader(zipItemReader) .writer(bundleZipFileImporter) .faultTolerant() diff --git a/avni-server-api/src/main/java/org/avni/server/ltree/LTreeType.java b/avni-server-api/src/main/java/org/avni/server/ltree/LTreeType.java index d1814322f..4d67ac306 100644 --- a/avni-server-api/src/main/java/org/avni/server/ltree/LTreeType.java +++ b/avni-server-api/src/main/java/org/avni/server/ltree/LTreeType.java @@ -1,7 +1,11 @@ package org.avni.server.ltree; import org.hibernate.HibernateException; +import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.type.descriptor.converter.spi.BasicValueConverter; +import org.hibernate.type.descriptor.jdbc.JdbcType; +import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.usertype.UserType; import java.io.Serializable; @@ -12,21 +16,19 @@ //https://stackoverflow.com/a/41381946/5737375 -public class LTreeType implements UserType { - - +public class LTreeType implements UserType { @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; + public Class returnedClass() { + return String.class; } @Override - public Class returnedClass() { - return String.class; + public int getSqlType() { + return Types.OTHER; } @Override - public boolean equals(Object o, Object o1) throws HibernateException { + public boolean equals(String o, String o1) { if (o == o1) return true; if (o == null || o1 == null) return false; @@ -34,23 +36,28 @@ public boolean equals(Object o, Object o1) throws HibernateException { } @Override - public int hashCode(Object o) throws HibernateException { + public int hashCode(String o) { return o.hashCode(); } @Override - public Object nullSafeGet(ResultSet resultSet, String[] strings, SharedSessionContractImplementor sessionImplementor, Object o) throws HibernateException, SQLException { - return resultSet.getString(strings[0]); + public String nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + return rs.getString(position); } @Override - public void nullSafeSet(PreparedStatement preparedStatement, Object o, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException { - preparedStatement.setObject(i, o, Types.OTHER); + public void nullSafeSet(PreparedStatement st, String value, int index, SharedSessionContractImplementor session) throws SQLException { + st.setObject(index, value, Types.OTHER); } @Override - public Object deepCopy(Object o) throws HibernateException { - return o != null ? new String((String) o) : null; + public String deepCopy(String o) { + return o; + } + + @Override + public Serializable disassemble(String o) { + return (Serializable) o; } @Override @@ -59,17 +66,37 @@ public boolean isMutable() { } @Override - public Serializable disassemble(Object o) throws HibernateException { - return (Serializable) o; + public String replace(String detached, String managed, Object owner) { + return deepCopy(detached); + } + + @Override + public long getDefaultSqlLength(Dialect dialect, JdbcType jdbcType) { + return UserType.super.getDefaultSqlLength(dialect, jdbcType); + } + + @Override + public int getDefaultSqlPrecision(Dialect dialect, JdbcType jdbcType) { + return UserType.super.getDefaultSqlPrecision(dialect, jdbcType); + } + + @Override + public int getDefaultSqlScale(Dialect dialect, JdbcType jdbcType) { + return UserType.super.getDefaultSqlScale(dialect, jdbcType); + } + + @Override + public JdbcType getJdbcType(TypeConfiguration typeConfiguration) { + return UserType.super.getJdbcType(typeConfiguration); } @Override - public Object assemble(Serializable serializable, Object o) throws HibernateException { - return serializable; + public BasicValueConverter getValueConverter() { + return UserType.super.getValueConverter(); } @Override - public Object replace(Object o, Object o1, Object o2) throws HibernateException { - return deepCopy(o); + public String assemble(Serializable serializable, Object o) throws HibernateException { + return (String) serializable; } } diff --git a/avni-server-api/src/main/java/org/avni/server/report/ReportHelper.java b/avni-server-api/src/main/java/org/avni/server/report/ReportHelper.java index 09d29898d..ad7da0bf6 100644 --- a/avni-server-api/src/main/java/org/avni/server/report/ReportHelper.java +++ b/avni-server-api/src/main/java/org/avni/server/report/ReportHelper.java @@ -1,5 +1,6 @@ package org.avni.server.report; +import jakarta.persistence.EntityNotFoundException; import org.avni.server.application.FormMapping; import org.avni.server.domain.EncounterType; import org.avni.server.domain.Program; @@ -7,7 +8,6 @@ import org.avni.server.util.S; import org.springframework.stereotype.Component; -import javax.persistence.EntityNotFoundException; import java.util.List; import static java.lang.String.format; diff --git a/avni-server-api/src/main/java/org/avni/server/service/AddressLevelCache.java b/avni-server-api/src/main/java/org/avni/server/service/AddressLevelCache.java index c65401db2..cfce57c35 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/AddressLevelCache.java +++ b/avni-server-api/src/main/java/org/avni/server/service/AddressLevelCache.java @@ -1,5 +1,7 @@ package org.avni.server.service; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.avni.server.application.projections.CatchmentAddressProjection; import org.avni.server.dao.LocationRepository; import org.avni.server.dao.RoleSwitchableRepository; @@ -8,8 +10,6 @@ import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; import java.util.List; @Component diff --git a/avni-server-api/src/main/java/org/avni/server/service/ApprovalStatusService.java b/avni-server-api/src/main/java/org/avni/server/service/ApprovalStatusService.java index b7df917e9..cddba68a4 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ApprovalStatusService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ApprovalStatusService.java @@ -1,11 +1,11 @@ package org.avni.server.service; import org.avni.server.dao.ApprovalStatusRepository; +import org.avni.server.util.DateTimeUtil; +import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.joda.time.DateTime; - @Service public class ApprovalStatusService implements NonScopeAwareService { @@ -17,7 +17,7 @@ public ApprovalStatusService(ApprovalStatusRepository approvalStatusRepository) @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return approvalStatusRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime); + return approvalStatusRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/CatchmentService.java b/avni-server-api/src/main/java/org/avni/server/service/CatchmentService.java index 2aa6c7925..03235f8cd 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/CatchmentService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/CatchmentService.java @@ -1,5 +1,7 @@ package org.avni.server.service; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.avni.server.builder.BuilderException; import org.avni.server.dao.CatchmentRepository; import org.avni.server.dao.LocationRepository; @@ -16,8 +18,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.HashSet; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/service/ChecklistService.java b/avni-server-api/src/main/java/org/avni/server/service/ChecklistService.java index 3ae0e8969..b48106506 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ChecklistService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ChecklistService.java @@ -1,16 +1,20 @@ package org.avni.server.service; -import org.avni.server.dao.*; +import org.avni.server.dao.ChecklistDetailRepository; +import org.avni.server.dao.ChecklistItemRepository; +import org.avni.server.dao.ChecklistRepository; +import org.avni.server.dao.OperatingIndividualScopeAwareRepository; import org.avni.server.dao.sync.SyncEntityName; -import org.avni.server.domain.*; +import org.avni.server.domain.Checklist; +import org.avni.server.domain.ChecklistDetail; +import org.avni.server.domain.Individual; +import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; import org.joda.time.DateTime; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.transaction.Transactional; import java.util.Set; @Component @@ -30,16 +34,6 @@ public Set findChecklistsByIndividual(Individual individual) { return checklistRepository.findByProgramEnrolmentIndividual(individual); } - @Transactional(Transactional.TxType.REQUIRED) - public ChecklistItem findChecklistItem(String checklistUUID, String checklistItemDetailUUID) { - return checklistItemRepository.findByChecklistUuidAndChecklistItemDetailUuid(checklistUUID, checklistItemDetailUUID); - } - - @Transactional(Transactional.TxType.REQUIRED) - public void saveItem(ChecklistItem checklistItem) { - checklistItemRepository.saveEntity(checklistItem); - } - @Override public boolean isScopeEntityChanged(DateTime lastModifiedDateTime, String checklistDetailUuid) { ChecklistDetail checklistDetail = checklistDetailRepository.findByUuid(checklistDetailUuid); diff --git a/avni-server-api/src/main/java/org/avni/server/service/CognitoIdpService.java b/avni-server-api/src/main/java/org/avni/server/service/CognitoIdpService.java index b06716dee..cb0be8831 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/CognitoIdpService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/CognitoIdpService.java @@ -6,6 +6,7 @@ import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider; import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClientBuilder; import com.amazonaws.services.cognitoidp.model.*; +import jakarta.annotation.PostConstruct; import org.avni.messaging.domain.EntityType; import org.avni.server.common.Messageable; import org.avni.server.domain.OrganisationConfig; @@ -20,7 +21,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; import java.util.Optional; import static org.avni.server.application.OrganisationConfigSettingKey.donotRequirePasswordChangeOnFirstLogin; diff --git a/avni-server-api/src/main/java/org/avni/server/service/ConceptService.java b/avni-server-api/src/main/java/org/avni/server/service/ConceptService.java index d7a6e9732..edb008561 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ConceptService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ConceptService.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.FormElement; import org.avni.server.application.KeyType; import org.avni.server.application.KeyValues; @@ -25,7 +26,6 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import javax.validation.constraints.NotNull; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; diff --git a/avni-server-api/src/main/java/org/avni/server/service/EncounterService.java b/avni-server-api/src/main/java/org/avni/server/service/EncounterService.java index 3c78c25cc..e5e9e9792 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/EncounterService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/EncounterService.java @@ -6,7 +6,6 @@ import org.avni.server.application.FormType; import org.avni.server.common.Messageable; import org.avni.server.dao.*; -import org.avni.server.dao.application.FormMappingRepository; import org.avni.server.domain.*; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.geo.Point; @@ -19,9 +18,8 @@ import org.avni.server.web.request.EncounterContract; import org.avni.server.web.request.EntityTypeContract; import org.avni.server.web.request.api.RequestUtils; -import org.joda.time.DateTime; -import org.avni.server.dao.individualRelationship.RuleFailureLogRepository; import org.avni.server.web.request.rules.RulesContractWrapper.VisitSchedule; +import org.joda.time.DateTime; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -38,7 +36,7 @@ import static org.avni.server.web.request.api.ApiBaseEncounterRequest.*; import static org.avni.server.web.request.api.ApiSubjectRequest.OBSERVATIONS; -import static org.springframework.data.jpa.domain.Specifications.where; +import static org.springframework.data.jpa.domain.Specification.where; @Service public class EncounterService implements ScopeAwareService { diff --git a/avni-server-api/src/main/java/org/avni/server/service/FormMappingService.java b/avni-server-api/src/main/java/org/avni/server/service/FormMappingService.java index 4ff28c8fc..67a22008d 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/FormMappingService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/FormMappingService.java @@ -188,7 +188,6 @@ private void setSubjectTypeIfRequired(FormMapping formMapping, String requestSub formMapping.setSubjectType(subjectType); } - @Transactional(readOnly = true) public LinkedHashMap getAllFormElementsAndDecisionMap(String subjectTypeUUID, String programUUID, String encounterTypeUUID, FormType formType) { return getEntityConceptMap(formMappingRepository.getRequiredFormMapping(subjectTypeUUID, programUUID, encounterTypeUUID, formType), false); } diff --git a/avni-server-api/src/main/java/org/avni/server/service/IdentifierAssignmentService.java b/avni-server-api/src/main/java/org/avni/server/service/IdentifierAssignmentService.java index 584ff7661..2986bc44b 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/IdentifierAssignmentService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/IdentifierAssignmentService.java @@ -1,6 +1,7 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.application.Form; import org.avni.server.application.KeyType; import org.avni.server.dao.IdentifierAssignmentRepository; @@ -16,7 +17,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/service/IdentifierSourceService.java b/avni-server-api/src/main/java/org/avni/server/service/IdentifierSourceService.java index 1f0966ce3..b9f8f2975 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/IdentifierSourceService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/IdentifierSourceService.java @@ -3,16 +3,16 @@ import org.avni.server.common.BulkItemSaveException; import org.avni.server.dao.CatchmentRepository; import org.avni.server.dao.IdentifierSourceRepository; -import org.avni.server.domain.CHSEntity; import org.avni.server.domain.Catchment; import org.avni.server.domain.IdentifierSource; import org.avni.server.domain.JsonObject; import org.avni.server.domain.identifier.IdentifierGeneratorType; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.webapp.IdentifierSourceContractWeb; +import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.joda.time.DateTime; import java.util.UUID; @Service @@ -61,7 +61,7 @@ private Catchment getCatchment(Long catchmentId, String catchmentUUID) { @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return identifierSourceRepository.existsByLastModifiedDateTimeGreaterThan(CHSEntity.toDate(lastModifiedDateTime)); + return identifierSourceRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } public void saveIdSources(IdentifierSourceContractWeb[] identifierSourceContractWebs) { diff --git a/avni-server-api/src/main/java/org/avni/server/service/IndividualSearchService.java b/avni-server-api/src/main/java/org/avni/server/service/IndividualSearchService.java index d6055b64f..bc227dc6e 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/IndividualSearchService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/IndividualSearchService.java @@ -9,7 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.math.BigInteger; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -47,7 +46,7 @@ private LinkedHashMap constructIndividual(List Long.valueOf((Integer) individualRecord.get("id"))) .collect(Collectors.toList()); List addressIds = individualList.stream() - .map(individualRecord -> ((BigInteger) individualRecord.get("addressId")).longValue()) + .map(individualRecord -> (Long) individualRecord.get("addressId")) .collect(Collectors.toList()); List searchSubjectEnrolledPrograms = !individualIds.isEmpty() ? @@ -63,7 +62,7 @@ private LinkedHashMap constructIndividual(List x.getId().equals(individualId)) .map(SearchSubjectEnrolledProgram::getProgram) .collect(Collectors.toList())); - individualRecord.put("addressLevel", titleLineages.get(((BigInteger) individualRecord.get("addressId")).longValue())); + individualRecord.put("addressLevel", titleLineages.get((Long) individualRecord.get("addressId"))); }).collect(Collectors.toList()); recordsMap.put("totalElements", totalCount); recordsMap.put("listOfRecords", listOfRecords); diff --git a/avni-server-api/src/main/java/org/avni/server/service/IndividualService.java b/avni-server-api/src/main/java/org/avni/server/service/IndividualService.java index 146cd3a7e..de4a0485b 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/IndividualService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/IndividualService.java @@ -1,6 +1,8 @@ package org.avni.server.service; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; import org.avni.messaging.domain.EntityType; import org.avni.messaging.service.PhoneNumberNotAvailableOrIncorrectException; import org.avni.server.application.FormElement; @@ -19,7 +21,10 @@ import org.avni.server.domain.observation.PhoneNumberObservationValue; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.accessControl.AccessControlService; -import org.avni.server.util.*; +import org.avni.server.util.ObjectMapperSingleton; +import org.avni.server.util.PhoneNumberUtil; +import org.avni.server.util.RegionUtil; +import org.avni.server.util.S; import org.avni.server.web.request.*; import org.avni.server.web.request.api.RequestUtils; import org.joda.time.DateTime; @@ -30,8 +35,6 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import javax.persistence.EntityNotFoundException; -import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; diff --git a/avni-server-api/src/main/java/org/avni/server/service/KeycloakIdpService.java b/avni-server-api/src/main/java/org/avni/server/service/KeycloakIdpService.java index 7c3ab5ed0..e7de3cfb9 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/KeycloakIdpService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/KeycloakIdpService.java @@ -1,5 +1,11 @@ package org.avni.server.service; +import jakarta.annotation.PostConstruct; +import jakarta.persistence.EntityNotFoundException; +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.ClientErrorException; +import jakarta.ws.rs.ServerErrorException; +import jakarta.ws.rs.core.Response; import org.avni.messaging.domain.EntityType; import org.avni.server.common.Messageable; import org.avni.server.domain.OrganisationConfig; @@ -14,20 +20,20 @@ import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.events.EventType; import org.keycloak.representations.adapters.config.AdapterConfig; -import org.keycloak.representations.idm.*; -import org.passay.*; +import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.representations.idm.EventRepresentation; +import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; -import javax.persistence.EntityNotFoundException; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.ServerErrorException; -import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.*; diff --git a/avni-server-api/src/main/java/org/avni/server/service/LocationHierarchyService.java b/avni-server-api/src/main/java/org/avni/server/service/LocationHierarchyService.java index bc93a50b6..515057db5 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/LocationHierarchyService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/LocationHierarchyService.java @@ -4,16 +4,16 @@ import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.dao.LocationRepository; import org.avni.server.domain.AddressLevelType; -import org.avni.server.domain.CHSEntity; import org.avni.server.domain.JsonObject; import org.avni.server.domain.OrganisationConfig; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; +import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.joda.time.DateTime; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -127,7 +127,7 @@ public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { ArrayList addressLevelTypeIds = (ArrayList) this.getLowestAddressLevelTypeHierarchiesForOrganisation(); if (addressLevelTypeIds != null) { List addressLevelTypes = addressLevelTypeRepository.findAllByIdIn(addressLevelTypeIds); - return locationRepository.existsByLastModifiedDateTimeAfterAndTypeIn(CHSEntity.toDate(lastModifiedDateTime), addressLevelTypes); + return locationRepository.existsByLastModifiedDateTimeAfterAndTypeIn(DateTimeUtil.toInstant(lastModifiedDateTime), addressLevelTypes); } return false; } diff --git a/avni-server-api/src/main/java/org/avni/server/service/LocationService.java b/avni-server-api/src/main/java/org/avni/server/service/LocationService.java index 8dac0d0c8..fcb6b1a3e 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/LocationService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/LocationService.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.FormElement; import org.avni.server.application.FormElementType; import org.avni.server.application.KeyType; @@ -27,7 +28,6 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID; diff --git a/avni-server-api/src/main/java/org/avni/server/service/MetadataBundleAndFileHandler.java b/avni-server-api/src/main/java/org/avni/server/service/MetadataBundleAndFileHandler.java index aa8fd44a8..85db4a9c0 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/MetadataBundleAndFileHandler.java +++ b/avni-server-api/src/main/java/org/avni/server/service/MetadataBundleAndFileHandler.java @@ -2,8 +2,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.avni.server.util.ObjectMapperSingleton; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -18,8 +17,7 @@ @Service public class MetadataBundleAndFileHandler { - - private static final ObjectMapper objectMapper = new ObjectMapper(); + private static final ObjectMapper objectMapper = ObjectMapperSingleton.getObjectMapper(); protected File extractZip(MultipartFile zipFile) throws IOException { File tempDir = Files.createTempDirectory("metadata-zip").toFile(); @@ -77,7 +75,7 @@ protected Map> parseJsonFiles(List files, File Map jsonMapFile = new HashMap<>(); if (jsonContent.toString().trim().startsWith("[")) { - List> jsonArray = objectMapper.readValue(jsonContent.toString(), new TypeReference>>() {}); + List> jsonArray = ObjectMapperSingleton.getObjectMapper().readValue(jsonContent.toString(), new TypeReference>>() {}); for (Map jsonObject : jsonArray) { String uuid = (String) jsonObject.get("uuid"); if (uuid != null) { diff --git a/avni-server-api/src/main/java/org/avni/server/service/NewsService.java b/avni-server-api/src/main/java/org/avni/server/service/NewsService.java index 968607460..6c50634c9 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/NewsService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/NewsService.java @@ -1,14 +1,13 @@ package org.avni.server.service; import org.avni.server.dao.NewsRepository; -import org.avni.server.domain.CHSEntity; import org.avni.server.domain.News; import org.avni.server.domain.util.EntityUtil; import org.avni.server.util.BadRequestError; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.NewsContract; -import org.springframework.stereotype.Service; - import org.joda.time.DateTime; +import org.springframework.stereotype.Service; @Service public class NewsService implements NonScopeAwareService { @@ -63,6 +62,6 @@ private void assertNewTitleIsUnique(String newTitle, String oldTitle) { @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return newsRepository.existsByPublishedDateNotNullAndLastModifiedDateTimeGreaterThan(CHSEntity.toDate(lastModifiedDateTime)); + return newsRepository.existsByPublishedDateNotNullAndLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/ObservationService.java b/avni-server-api/src/main/java/org/avni/server/service/ObservationService.java index da30c5255..ae45db091 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ObservationService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ObservationService.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.validation.constraints.NotNull; import org.avni.server.application.Form; import org.avni.server.application.FormElement; import org.avni.server.application.FormMapping; @@ -22,7 +23,6 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; -import javax.validation.constraints.NotNull; import java.sql.ResultSet; import java.sql.SQLException; import java.util.AbstractMap.SimpleEntry; diff --git a/avni-server-api/src/main/java/org/avni/server/service/OrganisationConfigService.java b/avni-server-api/src/main/java/org/avni/server/service/OrganisationConfigService.java index 3d9da6666..14a14d900 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/OrganisationConfigService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/OrganisationConfigService.java @@ -30,7 +30,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/service/PlatformTranslationService.java b/avni-server-api/src/main/java/org/avni/server/service/PlatformTranslationService.java index 1b6721c0e..4160d4777 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/PlatformTranslationService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/PlatformTranslationService.java @@ -3,6 +3,7 @@ import org.avni.server.application.Platform; import org.avni.server.dao.PlatformTranslationRepository; import org.avni.server.domain.CHSEntity; +import org.avni.server.util.DateTimeUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -20,7 +21,7 @@ public PlatformTranslationService(PlatformTranslationRepository platformTranslat @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return platformTranslationRepository.existsByPlatformAndLastModifiedDateTimeGreaterThan(Platform.Android, CHSEntity.toDate(lastModifiedDateTime)); + return platformTranslationRepository.existsByPlatformAndLastModifiedDateTimeGreaterThan(Platform.Android, DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/ProgramEnrolmentService.java b/avni-server-api/src/main/java/org/avni/server/service/ProgramEnrolmentService.java index 30eeeb336..a6b679657 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ProgramEnrolmentService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ProgramEnrolmentService.java @@ -11,7 +11,6 @@ import org.avni.server.framework.security.UserContextHolder; import org.avni.server.geo.Point; import org.avni.server.service.accessControl.AccessControlService; -import org.avni.server.util.BadRequestError; import org.avni.server.web.request.*; import org.avni.server.web.request.rules.RulesContractWrapper.ChecklistContract; import org.avni.server.web.request.rules.RulesContractWrapper.Decision; @@ -24,7 +23,6 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/service/ResetSyncService.java b/avni-server-api/src/main/java/org/avni/server/service/ResetSyncService.java index c001a12ea..5c07eb404 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/ResetSyncService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/ResetSyncService.java @@ -4,6 +4,7 @@ import org.avni.server.application.projections.CatchmentAddressProjection; import org.avni.server.dao.*; import org.avni.server.domain.*; +import org.avni.server.util.DateTimeUtil; import org.avni.server.util.JsonObjectUtil; import org.avni.server.web.request.CatchmentContract; import org.avni.server.web.request.UserContract; @@ -163,6 +164,6 @@ private boolean isChanged(Object str1, Object str2) { } public Page getByLastModifiedForUser(DateTime lastModifiedDateTime, DateTime now, User user, Pageable pageable) { - return resetSyncRepository.findAllByUserIsNullOrUserAndLastModifiedDateTimeBetweenOrderByLastModifiedDateTimeAscIdAsc(user, lastModifiedDateTime.toDate(), now.toDate(), pageable); + return resetSyncRepository.findAllByUserIsNullOrUserAndLastModifiedDateTimeBetweenOrderByLastModifiedDateTimeAscIdAsc(user, DateTimeUtil.toInstant(lastModifiedDateTime), DateTimeUtil.toInstant(now), pageable); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/RuleDependencyService.java b/avni-server-api/src/main/java/org/avni/server/service/RuleDependencyService.java index 6cdfb1d25..d2f6ee433 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/RuleDependencyService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/RuleDependencyService.java @@ -1,9 +1,9 @@ package org.avni.server.service; import org.avni.server.dao.RuleDependencyRepository; -import org.avni.server.domain.CHSEntity; import org.avni.server.domain.Organisation; import org.avni.server.domain.RuleDependency; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.RuleDependencyRequest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; @@ -32,6 +32,6 @@ public RuleDependencyService(RuleDependencyRepository ruleDependencyRepository) @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return ruleDependencyRepository.existsByLastModifiedDateTimeGreaterThan(CHSEntity.toDate(lastModifiedDateTime)); + return ruleDependencyRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/RuleService.java b/avni-server-api/src/main/java/org/avni/server/service/RuleService.java index cf5064739..ebc280796 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/RuleService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/RuleService.java @@ -1,26 +1,27 @@ package org.avni.server.service; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.joda.JodaModule; +import jakarta.transaction.Transactional; import org.avni.messaging.domain.EntityType; -import org.avni.server.dao.*; -import org.avni.server.domain.*; -import org.avni.server.web.external.RuleServiceClient; -import org.avni.server.web.request.EntityTypeContract; -import org.avni.server.web.request.rules.RulesContractWrapper.*; -import org.avni.server.web.request.rules.constructWrappers.*; -import org.avni.server.web.request.rules.request.*; -import org.avni.server.web.request.rules.response.*; import org.avni.server.application.Form; import org.avni.server.application.RuleType; +import org.avni.server.dao.*; import org.avni.server.dao.application.FormRepository; import org.avni.server.dao.individualRelationship.RuleFailureLogRepository; +import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.util.ObjectMapperSingleton; +import org.avni.server.web.external.RuleServiceClient; +import org.avni.server.web.request.EntityTypeContract; import org.avni.server.web.request.RuleRequest; +import org.avni.server.web.request.rules.RulesContractWrapper.*; import org.avni.server.web.request.rules.constant.WorkFlowTypeEnum; +import org.avni.server.web.request.rules.constructWrappers.*; +import org.avni.server.web.request.rules.request.*; +import org.avni.server.web.request.rules.response.*; import org.avni.server.web.request.rules.validateRules.RuleValidationService; import org.avni.server.web.validation.ValidationException; +import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -28,13 +29,12 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import javax.transaction.Transactional; import java.io.PrintWriter; import java.io.StringWriter; - -import org.joda.time.DateTime; - -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -364,15 +364,14 @@ private void setObservationsOnResponse(String workFlowType, RuleResponseEntity r private R createHttpHeaderAndSendRequest(String url, Object contractObject, RuleFailureLog ruleFailureLog, Class responseType) throws RuleExecutionException { try { ObjectMapper mapper = ObjectMapperSingleton.getObjectMapper(); - mapper.registerModule(new JodaModule()); - String ruleResponse = restClient.post(url, contractObject); - R ruleResponseEntity = mapper.readValue(ruleResponse, responseType); + R ruleResponseEntity = (R) restClient.post(url, contractObject, responseType); if (ruleResponseEntity.getStatus().equals("failure")) { RuleError ruleError = ruleResponseEntity.getError(); saveRuleError(ruleFailureLog, ruleError.getMessage(), ruleError.getStack()); } return ruleResponseEntity; } catch (Exception e) { + logger.error("Error while executing rule", e); saveRuleError(ruleFailureLog, e.getMessage(), getStackTrace(e)); RuleError ruleError = new RuleError(); ruleError.setMessage(e.getMessage()); diff --git a/avni-server-api/src/main/java/org/avni/server/service/StandardReportCardTypeService.java b/avni-server-api/src/main/java/org/avni/server/service/StandardReportCardTypeService.java index 01976aad9..518353096 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/StandardReportCardTypeService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/StandardReportCardTypeService.java @@ -1,11 +1,11 @@ package org.avni.server.service; import org.avni.server.dao.StandardReportCardTypeRepository; +import org.avni.server.util.DateTimeUtil; +import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.joda.time.DateTime; - @Service public class StandardReportCardTypeService implements NonScopeAwareService { @@ -18,6 +18,6 @@ public StandardReportCardTypeService(StandardReportCardTypeRepository standardRe @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return standardReportCardTypeRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime); + return standardReportCardTypeRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/SubjectMigrationService.java b/avni-server-api/src/main/java/org/avni/server/service/SubjectMigrationService.java index 7f01a2446..7cce74f5b 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/SubjectMigrationService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/SubjectMigrationService.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.dao.*; import org.avni.server.dao.individualRelationship.IndividualRelationshipRepository; import org.avni.server.dao.sync.SyncEntityName; @@ -16,8 +17,10 @@ import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; @Service public class SubjectMigrationService implements ScopeAwareService { diff --git a/avni-server-api/src/main/java/org/avni/server/service/SubjectSyncResponseBuilderService.java b/avni-server-api/src/main/java/org/avni/server/service/SubjectSyncResponseBuilderService.java index 8c94d5a99..a8757211c 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/SubjectSyncResponseBuilderService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/SubjectSyncResponseBuilderService.java @@ -2,19 +2,17 @@ import org.avni.server.dao.GroupSubjectRepository; import org.avni.server.dao.IndividualRepository; -import org.avni.server.domain.accessControl.GroupPrivileges; import org.avni.server.domain.GroupSubject; import org.avni.server.domain.Individual; +import org.avni.server.domain.accessControl.GroupPrivileges; import org.avni.server.service.accessControl.GroupPrivilegeService; import org.avni.server.web.response.SyncSubjectResponse; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; @Service -@Transactional public class SubjectSyncResponseBuilderService { private IndividualRepository individualRepository; private ChecklistService checklistService; diff --git a/avni-server-api/src/main/java/org/avni/server/service/SubjectTypeService.java b/avni-server-api/src/main/java/org/avni/server/service/SubjectTypeService.java index 1e33f0e55..74c3f15cd 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/SubjectTypeService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/SubjectTypeService.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.application.Subject; import org.avni.server.application.SubjectTypeSettingKey; import org.avni.server.common.BulkItemSaveException; @@ -17,7 +18,10 @@ import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.batch.core.*; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; @@ -25,7 +29,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/service/SyncDetailsService.java b/avni-server-api/src/main/java/org/avni/server/service/SyncDetailsService.java index 4c50a6754..c0e5dde7c 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/SyncDetailsService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/SyncDetailsService.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.Subject; import org.avni.server.dao.ChecklistDetailRepository; @@ -16,7 +17,6 @@ import org.avni.server.service.accessControl.GroupPrivilegeService; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/service/UserService.java b/avni-server-api/src/main/java/org/avni/server/service/UserService.java index 257449fd1..8b6335a75 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/UserService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/UserService.java @@ -6,6 +6,7 @@ import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.exception.GroupNotFoundException; +import org.avni.server.util.DateTimeUtil; import org.avni.server.util.PhoneNumberUtil; import org.avni.server.util.RegionUtil; import org.avni.server.util.WebResponseUtil; @@ -82,7 +83,6 @@ private User createUpdateUser(User user) { return savedUser; } - @Transactional public void addToDefaultUserGroup(User user) { if (user.getOrganisationId() != null) { //Not a super-admin Group group = groupRepository.findByNameAndOrganisationId(Group.Everyone, user.getOrganisationId()); @@ -125,10 +125,9 @@ public void associateUserToGroups(User user, List associatedGroupIds) { @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return userRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime); + return userRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } - @Transactional public User findByUuid(String uuid) { return userRepository.findByUuid(uuid); } diff --git a/avni-server-api/src/main/java/org/avni/server/service/UserSubjectAssignmentService.java b/avni-server-api/src/main/java/org/avni/server/service/UserSubjectAssignmentService.java index c1f9dc180..a569e0065 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/UserSubjectAssignmentService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/UserSubjectAssignmentService.java @@ -17,8 +17,6 @@ import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; -import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -101,13 +99,12 @@ private void addToSyncAttributes(String st, List syncAttributes syncAttributes.add(ConceptContract.create(concept)); } - @Transactional public LinkedHashMap searchSubjects(SubjectSearchRequest subjectSearchRequest) { List> searchResults = subjectSearchRepository.search(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder()); List subjectIds = searchResults.stream().map(s -> Long.parseLong(s.get("id").toString())).collect(Collectors.toList()); List userSubjectAssignmentBySubjectIds = userSubjectAssignmentRepository.findUserSubjectAssignmentBySubject_IdIn(subjectIds); List addressIds = searchResults.stream() - .map(searchResult -> ((BigInteger) searchResult.get("addressId")).longValue()) + .map(searchResult -> (Long) searchResult.get("addressId")) .collect(Collectors.toList()); Map titleLineages = addressLevelService.getTitleLineages(addressIds); Map> groupedSubjects = userSubjectAssignmentBySubjectIds.stream() @@ -123,10 +120,10 @@ public LinkedHashMap searchSubjects(SubjectSearchRequest subject .orElseGet(Stream::empty) .map(uw -> pf.createProjection(UserWebProjection.class, uw)).collect(Collectors.toList()); searchResult.put("assignedUsers", userWebProjections); - searchResult.put("addressLevel", titleLineages.get(((BigInteger) searchResult.get("addressId")).longValue())); + searchResult.put("addressLevel", titleLineages.get((Long) searchResult.get("addressId"))); } - BigInteger totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder()); + Long totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder()); LinkedHashMap recordsMap = new LinkedHashMap<>(); recordsMap.put("totalElements", totalCount); diff --git a/avni-server-api/src/main/java/org/avni/server/service/accessControl/AccessControlService.java b/avni-server-api/src/main/java/org/avni/server/service/accessControl/AccessControlService.java index 71fafea52..3190ec0e3 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/accessControl/AccessControlService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/accessControl/AccessControlService.java @@ -1,5 +1,6 @@ package org.avni.server.service.accessControl; +import jakarta.validation.constraints.NotNull; import org.avni.server.dao.*; import org.avni.server.domain.*; import org.avni.server.domain.accessControl.*; @@ -11,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.validation.constraints.NotNull; import java.util.Arrays; import java.util.List; import java.util.Map; diff --git a/avni-server-api/src/main/java/org/avni/server/service/accessControl/PrivilegeService.java b/avni-server-api/src/main/java/org/avni/server/service/accessControl/PrivilegeService.java index 49eb056ee..847e6f199 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/accessControl/PrivilegeService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/accessControl/PrivilegeService.java @@ -2,6 +2,7 @@ import org.avni.server.dao.PrivilegeRepository; import org.avni.server.service.NonScopeAwareService; +import org.avni.server.util.DateTimeUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -19,6 +20,6 @@ public PrivilegeService(PrivilegeRepository privilegeRepository) { @Override public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { - return privilegeRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime); + return privilegeRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/service/application/MenuItemService.java b/avni-server-api/src/main/java/org/avni/server/service/application/MenuItemService.java index 048263a4e..2a154b886 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/application/MenuItemService.java +++ b/avni-server-api/src/main/java/org/avni/server/service/application/MenuItemService.java @@ -26,7 +26,6 @@ public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) { return menuItemRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime); } - @Transactional public List findAll() { return menuItemRepository.findAll(); } @@ -36,12 +35,10 @@ public MenuItem save(MenuItem menuItem) { return menuItemRepository.save(menuItem); } - @Transactional public MenuItem find(String uuid) { return menuItemRepository.findByUuid(uuid); } - @Transactional public MenuItem find(Long id) { return menuItemRepository.findEntity(id); } diff --git a/avni-server-api/src/main/java/org/avni/server/service/exception/GroupNotFoundException.java b/avni-server-api/src/main/java/org/avni/server/service/exception/GroupNotFoundException.java index 4ece11b49..c20997177 100644 --- a/avni-server-api/src/main/java/org/avni/server/service/exception/GroupNotFoundException.java +++ b/avni-server-api/src/main/java/org/avni/server/service/exception/GroupNotFoundException.java @@ -1,6 +1,6 @@ package org.avni.server.service.exception; -import javax.persistence.EntityNotFoundException; +import jakarta.persistence.EntityNotFoundException; public class GroupNotFoundException extends EntityNotFoundException { diff --git a/avni-server-api/src/main/java/org/avni/server/util/DateTimeUtil.java b/avni-server-api/src/main/java/org/avni/server/util/DateTimeUtil.java index 62233c8f4..5d33f01f4 100644 --- a/avni-server-api/src/main/java/org/avni/server/util/DateTimeUtil.java +++ b/avni-server-api/src/main/java/org/avni/server/util/DateTimeUtil.java @@ -5,7 +5,10 @@ import org.joda.time.Instant; import org.joda.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; import java.util.Calendar; +import java.util.Date; import java.util.TimeZone; public class DateTimeUtil { @@ -42,4 +45,54 @@ public static String toDateString(String dateStringWithTimezone) { .toDateTime(IST) .toString("yyyy-MM-dd"); } + + public static long getMilliSecondsDuration(LocalDateTime start, LocalDateTime end) { + return java.time.Duration.between(start, end).toMillis(); + } + + public static LocalDate toJodaDate(java.time.Instant instant) { + if (instant == null) { + return null; + } + return DateTimeUtil.toJodaDateTime(instant).toLocalDate(); + } + + public static java.time.Instant toInstant(LocalDate localDate) { + if (localDate == null) { + return null; + } + return localDate.toDate().toInstant(); + } + + public static java.time.Instant toInstant(DateTime createdDateTime) { + if (createdDateTime == null) { + return null; + } + return createdDateTime.toDate().toInstant(); + } + + public static DateTime toJodaDateTime(java.time.Instant instant) { + if (instant == null) { + return null; + } + return new DateTime(instant.toEpochMilli()); + } + + public static DateTime toJodaDateTime(ZonedDateTime zonedDateTime) { + if (zonedDateTime == null) { + return null; + } + return new DateTime(zonedDateTime.toInstant().toEpochMilli()); + } + + public static java.time.Instant toInstant(Date date) { + if (date == null) { + return null; + } + return date.toInstant(); + } + + public static java.time.Instant toInstant(Calendar calendar) { + return calendar == null ? null : calendar.toInstant(); + } } diff --git a/avni-server-api/src/main/java/org/avni/server/util/ObjectMapperSingleton.java b/avni-server-api/src/main/java/org/avni/server/util/ObjectMapperSingleton.java index ef06b6445..be17e3631 100644 --- a/avni-server-api/src/main/java/org/avni/server/util/ObjectMapperSingleton.java +++ b/avni-server-api/src/main/java/org/avni/server/util/ObjectMapperSingleton.java @@ -1,10 +1,16 @@ package org.avni.server.util; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.joda.JodaModule; public final class ObjectMapperSingleton { - private static final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JodaModule()); + private static final ObjectMapper objectMapper = new ObjectMapper() + .registerModule(new JodaModule()) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); private ObjectMapperSingleton() { } diff --git a/avni-server-api/src/main/java/org/avni/server/web/AccountController.java b/avni-server-api/src/main/java/org/avni/server/web/AccountController.java index ccc275357..7c11b752e 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/AccountController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/AccountController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.AccountRepository; import org.avni.server.domain.Account; import org.avni.server.domain.AccountAdmin; @@ -16,7 +17,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/web/AddressLevelTypeController.java b/avni-server-api/src/main/java/org/avni/server/web/AddressLevelTypeController.java index 4eb6c1b9c..c07b64f1e 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/AddressLevelTypeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/AddressLevelTypeController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.AddressLevelType; @@ -20,7 +21,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Set; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/web/CatchmentController.java b/avni-server-api/src/main/java/org/avni/server/web/CatchmentController.java index a331cbc7c..d2d776391 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/CatchmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/CatchmentController.java @@ -1,5 +1,7 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; +import jakarta.validation.Valid; import org.avni.server.builder.BuilderException; import org.avni.server.dao.CatchmentRepository; import org.avni.server.dao.LocationRepository; @@ -23,14 +25,12 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; -import javax.validation.Valid; import java.util.List; import java.util.stream.Collectors; @@ -67,19 +67,19 @@ public CatchmentController(CatchmentRepository catchmentRepository, } @GetMapping(value = "catchment") - public PagedResources> get(Pageable pageable) { + public CollectionModel> get(Pageable pageable) { Page all = catchmentRepository.findPageByIsVoidedFalse(pageable); Page catchmentContracts = all.map(CatchmentContract::fromEntity); return wrap(catchmentContracts); } @GetMapping(value = "catchment/{id}") - public Resource getById(@PathVariable Long id) { + public EntityModel getById(@PathVariable Long id) { Catchment catchment = catchmentRepository.findOne(id); CatchmentContract catchmentContract = CatchmentContract.fromEntity(catchment); boolean fastSyncExists = s3Service.fileExists(String.format("MobileDbBackup-%s", catchment.getUuid())); catchmentContract.setFastSyncExists(fastSyncExists); - return new Resource<>(catchmentContract); + return EntityModel.of(catchmentContract); } @GetMapping(value = "catchment/search/findAllById") @@ -89,7 +89,7 @@ public List getById(@Param("ids") Long[] ids) { } @GetMapping(value = "catchment/search/find") - public PagedResources> find(@RequestParam(value = "name") String name, Pageable pageable) { + public CollectionModel> find(@RequestParam(value = "name") String name, Pageable pageable) { Page catchments = catchmentRepository.findByIsVoidedFalseAndNameIgnoreCaseStartingWithOrderByNameAsc(name, pageable); Page catchmentContracts = catchments.map(CatchmentContract::fromEntity); return wrap(catchmentContracts); diff --git a/avni-server-api/src/main/java/org/avni/server/web/ChecklistController.java b/avni-server-api/src/main/java/org/avni/server/web/ChecklistController.java index 1571a9221..f96c9a9e3 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ChecklistController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ChecklistController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.ChecklistDetailRepository; import org.avni.server.dao.ChecklistRepository; import org.avni.server.dao.ProgramEnrolmentRepository; @@ -17,13 +18,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -66,7 +66,7 @@ public void saveOld(@RequestBody Object object) { @RequestMapping(value = "/txNewChecklistEntity/search/byIndividualsOfCatchmentAndLastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getByIndividualsOfCatchmentAndLastModified( + public CollectionModel> getByIndividualsOfCatchmentAndLastModified( @RequestParam("catchmentId") long catchmentId, @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @@ -77,7 +77,7 @@ public PagedResources> getByIndividualsOfCatchmentAndLastMod @RequestMapping(value = "/txNewChecklistEntity/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getChecklistsByOperatingIndividualScopeAsSlice( + public SlicedResources> getChecklistsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "checklistDetailUuid", required = false) String checklistDetailUuid, @@ -92,7 +92,7 @@ public SlicedResources> getChecklistsByOperatingIndividualSc @RequestMapping(value = "/txNewChecklistEntity", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getChecklistsByOperatingIndividualScope( + public CollectionModel> getChecklistsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "checklistDetailUuid", required = false) String checklistDetailUuid, @@ -106,12 +106,12 @@ public PagedResources> getChecklistsByOperatingIndividualSco } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Checklist checklist = resource.getContent(); resource.removeLinks(); - resource.add(new Link(checklist.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); + resource.add(Link.of(checklist.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); if (checklist.getChecklistDetail() != null) { - resource.add(new Link(checklist.getChecklistDetail().getUuid(), "checklistDetailUUID")); + resource.add(Link.of(checklist.getChecklistDetail().getUuid(), "checklistDetailUUID")); } addAuditFields(checklist, resource); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/ChecklistDetailController.java b/avni-server-api/src/main/java/org/avni/server/web/ChecklistDetailController.java index 7393e19b4..3af0ac3cf 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ChecklistDetailController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ChecklistDetailController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.service.ChecklistDetailService; import org.avni.server.service.accessControl.AccessControlService; @@ -13,7 +14,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/ChecklistItemController.java b/avni-server-api/src/main/java/org/avni/server/web/ChecklistItemController.java index 9e7c4b185..46d2bd4e6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ChecklistItemController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ChecklistItemController.java @@ -1,6 +1,10 @@ package org.avni.server.web; -import org.avni.server.dao.*; +import jakarta.transaction.Transactional; +import org.avni.server.dao.ChecklistDetailRepository; +import org.avni.server.dao.ChecklistItemDetailRepository; +import org.avni.server.dao.ChecklistItemRepository; +import org.avni.server.dao.ChecklistRepository; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.Checklist; @@ -17,13 +21,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -72,7 +75,7 @@ public void save(@RequestBody ChecklistItemRequest checklistItemRequest) { @RequestMapping(value = "/txNewChecklistItemEntity/search/byIndividualsOfCatchmentAndLastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getByIndividualsOfCatchmentAndLastModified( + public CollectionModel> getByIndividualsOfCatchmentAndLastModified( @RequestParam("catchmentId") long catchmentId, @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @@ -83,7 +86,7 @@ public PagedResources> getByIndividualsOfCatchmentAndLas @RequestMapping(value = "/txNewChecklistItemEntity/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getChecklistItemsByOperatingIndividualScopeAsSlice( + public SlicedResources> getChecklistItemsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "checklistDetailUuid", required = false) String checklistDetailUuid, @@ -98,7 +101,7 @@ public SlicedResources> getChecklistItemsByOperatingIndi @RequestMapping(value = "/txNewChecklistItemEntity", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getChecklistItemsByOperatingIndividualScope( + public CollectionModel> getChecklistItemsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "checklistDetailUuid", required = false) String checklistDetailUuid, @@ -112,12 +115,12 @@ public PagedResources> getChecklistItemsByOperatingIndiv } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ChecklistItem checklistItem = resource.getContent(); resource.removeLinks(); - resource.add(new Link(checklistItem.getChecklist().getUuid(), "checklistUUID")); + resource.add(Link.of(checklistItem.getChecklist().getUuid(), "checklistUUID")); if (checklistItem.getChecklistItemDetail() != null) { - resource.add(new Link(checklistItem.getChecklistItemDetail().getUuid(), "checklistItemDetailUUID")); + resource.add(Link.of(checklistItem.getChecklistItemDetail().getUuid(), "checklistItemDetailUUID")); } addAuditFields(checklistItem, resource); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/CommentController.java b/avni-server-api/src/main/java/org/avni/server/web/CommentController.java index 4a657381b..f290eeb88 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/CommentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/CommentController.java @@ -1,6 +1,10 @@ package org.avni.server.web; -import org.avni.server.dao.*; +import jakarta.transaction.Transactional; +import org.avni.server.dao.CommentRepository; +import org.avni.server.dao.CommentThreadRepository; +import org.avni.server.dao.IndividualRepository; +import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.domain.Comment; import org.avni.server.domain.CommentThread; @@ -18,14 +22,13 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -118,7 +121,7 @@ public void save(@RequestBody CommentContract commentContract) { @GetMapping(value = {"/comment/v2"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getCommentsByOperatingIndividualScopeAsSlice( + public SlicedResources> getCommentsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid") String subjectTypeUuid, @@ -132,7 +135,7 @@ public SlicedResources> getCommentsByOperatingIndividualScopeA @GetMapping(value = {"/comment"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getCommentsByOperatingIndividualScope( + public CollectionModel> getCommentsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid") String subjectTypeUuid, @@ -145,13 +148,13 @@ public PagedResources> getCommentsByOperatingIndividualScope( } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Comment comment = resource.getContent(); CommentThread commentThread = comment.getCommentThread(); resource.removeLinks(); - resource.add(new Link(comment.getSubjectUUID(), "individualUUID")); + resource.add(Link.of(comment.getSubjectUUID(), "individualUUID")); if (commentThread != null) { - resource.add(new Link(commentThread.getUuid(), "commentThreadUUID")); + resource.add(Link.of(commentThread.getUuid(), "commentThreadUUID")); } addAuditFields(comment, resource); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/CommentThreadController.java b/avni-server-api/src/main/java/org/avni/server/web/CommentThreadController.java index 4a09416ae..7467651a5 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/CommentThreadController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/CommentThreadController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.CommentThreadRepository; import org.avni.server.dao.IndividualRepository; import org.avni.server.dao.SubjectTypeRepository; @@ -10,8 +11,8 @@ import org.avni.server.service.CommentThreadService; import org.avni.server.service.ScopeBasedSyncService; import org.avni.server.service.UserService; -import org.avni.server.web.response.CommentThreadResponse; import org.avni.server.web.request.CommentThreadContract; +import org.avni.server.web.response.CommentThreadResponse; import org.avni.server.web.response.slice.SlicedResources; import org.joda.time.DateTime; import org.slf4j.LoggerFactory; @@ -20,13 +21,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -59,7 +59,7 @@ public CommentThreadController(CommentThreadRepository commentThreadRepository, @GetMapping(value = {"/commentThread/v2"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getCommentThreadsByOperatingIndividualScopeAsSlice( + public SlicedResources> getCommentThreadsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid") String subjectTypeUuid, @@ -73,7 +73,7 @@ public SlicedResources> getCommentThreadsByOperatingIndi @GetMapping(value = {"/commentThread"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getCommentThreadsByOperatingIndividualScope( + public CollectionModel> getCommentThreadsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid") String subjectTypeUuid, diff --git a/avni-server-api/src/main/java/org/avni/server/web/ConceptController.java b/avni-server-api/src/main/java/org/avni/server/web/ConceptController.java index 786ff9f22..a94fe6b56 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ConceptController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ConceptController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.ConceptAnswerRepository; import org.avni.server.dao.ConceptRepository; import org.avni.server.domain.Concept; @@ -22,14 +23,13 @@ import org.springframework.data.domain.*; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.repository.query.Param; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.HtmlUtils; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -83,9 +83,9 @@ public ResponseEntity getOneForWebByName(@RequestParam String @GetMapping(value = "/web/concepts") @ResponseBody - public PagedResources> getAll(@RequestParam(value = "name", required = false) String name, Pageable pageable) { - Sort sortWithId = pageable.getSort().and(new Sort("id")); - PageRequest pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sortWithId); + public CollectionModel> getAll(@RequestParam(value = "name", required = false) String name, Pageable pageable) { + Sort sortWithId = pageable.getSort().and(Sort.by("id")); + PageRequest pageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sortWithId); if (name == null) { return wrap(conceptRepository.getAllNonVoidedConcepts(pageRequest)); } else { diff --git a/avni-server-api/src/main/java/org/avni/server/web/CustomQueryController.java b/avni-server-api/src/main/java/org/avni/server/web/CustomQueryController.java index 459dee22b..02ad5a4f9 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/CustomQueryController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/CustomQueryController.java @@ -1,6 +1,7 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.QueryRepository; import org.avni.server.web.request.CustomQueryRequest; import org.springframework.beans.factory.annotation.Autowired; @@ -8,8 +9,6 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; - @RestController public class CustomQueryController { diff --git a/avni-server-api/src/main/java/org/avni/server/web/DashboardController.java b/avni-server-api/src/main/java/org/avni/server/web/DashboardController.java index f08757c37..86c6b7aa4 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/DashboardController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/DashboardController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.DashboardRepository; import org.avni.server.dao.OrganisationRepository; import org.avni.server.domain.CHSEntity; @@ -11,6 +12,7 @@ import org.avni.server.mapper.dashboard.DefaultDashboardConstants; import org.avni.server.service.DashboardService; import org.avni.server.service.accessControl.AccessControlService; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.DashboardWebRequest; import org.avni.server.web.response.reports.DashboardWebResponse; import org.avni.server.web.validation.ValidationException; @@ -19,12 +21,11 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -116,17 +117,17 @@ public ResponseEntity createDefaultDashboard(@RequestParam //This is here because dashboardCardMapping used to get synced earlier which is no longer required now @Deprecated @RequestMapping(value = "/dashboardCardMapping/search/lastModified", method = RequestMethod.GET) - public PagedResources getByIndividualsOfCatchmentAndLastModified(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now) { + public CollectionModel getByIndividualsOfCatchmentAndLastModified(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, + @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now) { return wrap(new PageImpl<>(Collections.emptyList())); } @GetMapping(value = "/v2/dashboard/search/lastModified") - public PagedResources> getDashboards(@RequestParam("lastModifiedDateTime") - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, - @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, - Pageable pageable) { - return wrap(dashboardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + public CollectionModel> getDashboards(@RequestParam("lastModifiedDateTime") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, + @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, + Pageable pageable) { + return wrap(dashboardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/DashboardFilterController.java b/avni-server-api/src/main/java/org/avni/server/web/DashboardFilterController.java index 84ef11aa7..b1c07f767 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/DashboardFilterController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/DashboardFilterController.java @@ -3,13 +3,14 @@ import org.avni.server.dao.DashboardFilterRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.app.dashboard.DashboardFilter; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -26,19 +27,19 @@ public DashboardFilterController(DashboardFilterRepository dashboardFilterReposi } @GetMapping(value = "/v2/dashboardFilter/search/lastModified") - public PagedResources> getDashboardFilters(@RequestParam("lastModifiedDateTime") + public CollectionModel> getDashboardFilters(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(dashboardFilterRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + return wrap(dashboardFilterRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DashboardFilter entity = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entity.getDashboard().getUuid(), "dashboardUUID")); + resource.add(Link.of(entity.getDashboard().getUuid(), "dashboardUUID")); addAuditFields(entity, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionCardMappingController.java b/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionCardMappingController.java index 33629703b..e833b3113 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionCardMappingController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionCardMappingController.java @@ -3,13 +3,14 @@ import org.avni.server.dao.DashboardSectionCardMappingRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.DashboardSectionCardMapping; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -26,20 +27,20 @@ public DashboardSectionCardMappingController(DashboardSectionCardMappingReposito } @GetMapping(value = "/v2/dashboardSectionCardMapping/search/lastModified") - public PagedResources> getDashboardSectionCardMappings(@RequestParam("lastModifiedDateTime") + public CollectionModel> getDashboardSectionCardMappings(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(dashboardSectionCardMappingRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + return wrap(dashboardSectionCardMappingRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DashboardSectionCardMapping entity = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entity.getDashboardSection().getUuid(), "dashboardSectionUUID")); - resource.add(new Link(entity.getCard().getUuid(), "cardUUID")); + resource.add(Link.of(entity.getDashboardSection().getUuid(), "dashboardSectionUUID")); + resource.add(Link.of(entity.getCard().getUuid(), "cardUUID")); addAuditFields(entity, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionController.java b/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionController.java index 1f0fbe1db..b6e8ea9ca 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/DashboardSectionController.java @@ -3,13 +3,14 @@ import org.avni.server.dao.DashboardSectionRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.DashboardSection; +import org.avni.server.util.DateTimeUtil; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -26,19 +27,19 @@ public DashboardSectionController(DashboardSectionRepository dashboardSectionRep } @GetMapping(value = "/v2/dashboardSection/search/lastModified") - public PagedResources> getDashboardSection(@RequestParam("lastModifiedDateTime") + public CollectionModel> getDashboardSection(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(dashboardSectionRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + return wrap(dashboardSectionRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { DashboardSection entity = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entity.getDashboard().getUuid(), "dashboardUUID")); + resource.add(Link.of(entity.getDashboard().getUuid(), "dashboardUUID")); addAuditFields(entity, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/DocumentationController.java b/avni-server-api/src/main/java/org/avni/server/web/DocumentationController.java index 78d0c0d41..24c5e8285 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/DocumentationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/DocumentationController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.projections.DocumentationProjection; import org.avni.server.dao.DocumentationRepository; import org.avni.server.domain.Documentation; @@ -14,7 +15,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/EncounterController.java b/avni-server-api/src/main/java/org/avni/server/web/EncounterController.java index 18f07d9c0..21894296c 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/EncounterController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/EncounterController.java @@ -1,6 +1,7 @@ package org.avni.server.web; import com.bugsnag.Bugsnag; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.FormType; import org.avni.server.dao.EncounterRepository; @@ -27,15 +28,14 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; @@ -202,7 +202,7 @@ private Encounter createEncounter(EncounterRequest request) { @RequestMapping(value = "/encounter/search/byIndividualsOfCatchmentAndLastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getEncountersByCatchmentAndLastModified( + public CollectionModel> getEncountersByCatchmentAndLastModified( @RequestParam("catchmentId") long catchmentId, @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @@ -212,7 +212,7 @@ public PagedResources> getEncountersByCatchmentAndLastModifi @RequestMapping(value = "/encounter/search/lastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getEncountersByLastModified( + public CollectionModel> getEncountersByLastModified( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -221,7 +221,7 @@ public PagedResources> getEncountersByLastModified( @RequestMapping(value = "/encounter/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getEncountersByOperatingIndividualScopeAsSlice( + public SlicedResources> getEncountersByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "encounterTypeUuid", required = false) String encounterTypeUuid, @@ -237,7 +237,7 @@ public SlicedResources> getEncountersByOperatingIndividualSc @RequestMapping(value = "/encounter", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getEncountersByOperatingIndividualScope( + public CollectionModel> getEncountersByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "encounterTypeUuid", required = false) String encounterTypeUuid, @@ -273,11 +273,11 @@ public AvniEntityResponse voidEncounter(@PathVariable String uuid) { } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Encounter encounter = resource.getContent(); resource.removeLinks(); - resource.add(new Link(encounter.getEncounterType().getUuid(), "encounterTypeUUID")); - resource.add(new Link(encounter.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(encounter.getEncounterType().getUuid(), "encounterTypeUUID")); + resource.add(Link.of(encounter.getIndividual().getUuid(), "individualUUID")); addAuditFields(encounter, resource); addUserFields(encounter.getFilledBy(), resource, "filledBy"); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/EncounterTypeController.java b/avni-server-api/src/main/java/org/avni/server/web/EncounterTypeController.java index e6c74afe4..694798305 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/EncounterTypeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/EncounterTypeController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.Form; import org.avni.server.application.FormType; import org.avni.server.dao.EncounterTypeRepository; @@ -21,14 +22,13 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; @@ -68,7 +68,7 @@ void save(@RequestBody List encounterTypeRequests) { @GetMapping(value = "/web/encounterType") @ResponseBody - public PagedResources> getAll(Pageable pageable) { + public CollectionModel> getAll(Pageable pageable) { return wrap(operationalEncounterTypeRepository .findPageByIsVoidedFalse(pageable) .map(EncounterTypeContractWeb::fromOperationalEncounterType)); diff --git a/avni-server-api/src/main/java/org/avni/server/web/EntityApprovalStatusController.java b/avni-server-api/src/main/java/org/avni/server/web/EntityApprovalStatusController.java index 9201ec727..6a0921dc0 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/EntityApprovalStatusController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/EntityApprovalStatusController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.FormType; import org.avni.server.dao.EncounterTypeRepository; @@ -21,13 +22,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -72,7 +72,7 @@ public void save(@RequestBody EntityApprovalStatusRequest request) { @RequestMapping(value = "/entityApprovalStatus", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getEntityApprovals( + public CollectionModel> getEntityApprovals( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "entityType", required = false) SyncEntityName entityName, @@ -89,7 +89,7 @@ public PagedResources> getEntityApprovals( @RequestMapping(value = "/entityApprovalStatus/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getEntityApprovalsAsSlice( + public SlicedResources> getEntityApprovalsAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "entityType", required = false) SyncEntityName entityName, @@ -101,11 +101,11 @@ public SlicedResources> getEntityApprovalsAsSlice } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { EntityApprovalStatus entityApprovalStatus = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entityApprovalStatusService.getEntityUuid(entityApprovalStatus), "entityUUID")); - resource.add(new Link(entityApprovalStatus.getApprovalStatus().getUuid(), "approvalStatusUUID")); + resource.add(Link.of(entityApprovalStatusService.getEntityUuid(entityApprovalStatus), "entityUUID")); + resource.add(Link.of(entityApprovalStatus.getApprovalStatus().getUuid(), "approvalStatusUUID")); addAuditFields(entityApprovalStatus, resource); return resource; } @@ -146,7 +146,7 @@ private String getSubjectTypeUuidFromProgramTypeUuid(String entityTypeUuid, Form return formMapping.getSubjectTypeUuid(); } - private SlicedResources> getScopeBasedSyncResultsAsSlice(DateTime lastModifiedDateTime, + private SlicedResources> getScopeBasedSyncResultsAsSlice(DateTime lastModifiedDateTime, DateTime now, String subjectTypeUuid, Pageable pageable, SyncEntityName entityName, String entityTypeUuid) { if (subjectTypeUuid == null || subjectTypeUuid.isEmpty()) return wrap(new SliceImpl<>(Collections.emptyList())); @@ -156,7 +156,7 @@ private SlicedResources> getScopeBasedSyncResults userService.getCurrentUser(), lastModifiedDateTime, now, entityTypeUuid, pageable, subjectType, entityName)); } - private PagedResources> getScopeBasedSyncResults(DateTime lastModifiedDateTime, + private CollectionModel> getScopeBasedSyncResults(DateTime lastModifiedDateTime, DateTime now, String subjectTypeUuid, Pageable pageable, SyncEntityName entityName, String entityTypeUuid) { if (subjectTypeUuid == null || subjectTypeUuid.isEmpty()) return wrap(new PageImpl<>(Collections.emptyList())); diff --git a/avni-server-api/src/main/java/org/avni/server/web/ErrorInterceptors.java b/avni-server-api/src/main/java/org/avni/server/web/ErrorInterceptors.java index 344a3e43c..7687566e4 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ErrorInterceptors.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ErrorInterceptors.java @@ -16,6 +16,7 @@ import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.web.bind.MethodArgumentNotValidException; @@ -72,7 +73,7 @@ public ErrorInterceptors(@Value("${spring.servlet.multipart.max-file-size}") Str } @Override - protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { + protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Map body = new HashMap<>(); List errors = ex.getBindingResult() .getFieldErrors() @@ -89,7 +90,7 @@ private ResponseEntity error(final Exception excep return new ResponseEntity(new RestControllerErrorResponse(errorBodyBuilder.getErrorBody(message)), httpStatus); } - @ExceptionHandler(value = {MaxUploadSizeExceededException.class, SizeLimitExceededException.class}) + @ExceptionHandler(value = {SizeLimitExceededException.class}) public ResponseEntity fileUploadSizeLimitExceededError(Exception e) { return ResponseEntity.badRequest().body(String.format("Maximum upload file size exceeded; ensure file size is less than %s.", maxFileSize)); } @@ -121,8 +122,8 @@ public ResponseEntity unknownException(Exception e) { } @Override - protected ResponseEntity handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { + protected ResponseEntity handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) { bugsnagReporter.logAndReportToBugsnag(ex); - return super.handleExceptionInternal(ex, errorBodyBuilder.getErrorBody(body), headers, status, request); + return super.handleExceptionInternal(ex, errorBodyBuilder.getErrorBody(body), headers, statusCode, request); } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/ExtensionController.java b/avni-server-api/src/main/java/org/avni/server/web/ExtensionController.java index ec2f806f0..c229672df 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ExtensionController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ExtensionController.java @@ -19,8 +19,8 @@ import org.springframework.core.io.InputStreamResource; import org.springframework.data.domain.PageImpl; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; @@ -29,9 +29,9 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.HandlerMapping; -import javax.servlet.http.HttpServletRequest; -import javax.transaction.Transactional; -import javax.validation.Valid; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.transaction.Transactional; +import jakarta.validation.Valid; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -84,7 +84,7 @@ public ResponseEntity uploadExtensions(@RequestPart(value = "file") Multipart } @GetMapping(value = "/extensions") - public PagedResources> listExtensionFiles(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Optional lastModifiedDateTime) { + public CollectionModel> listExtensionFiles(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Optional lastModifiedDateTime) { return wrap(new PageImpl<>(s3Service.listExtensionFiles(lastModifiedDateTime))); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/FormController.java b/avni-server-api/src/main/java/org/avni/server/web/FormController.java index 9cd9b2e0a..525f450b3 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/FormController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/FormController.java @@ -40,20 +40,20 @@ import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.persistence.criteria.Predicate; -import javax.transaction.Transactional; +import jakarta.persistence.criteria.Predicate; +import jakarta.transaction.Transactional; import java.io.InvalidObjectException; import java.util.*; import java.util.stream.Collectors; import static java.lang.String.format; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @RestController public class FormController implements RestControllerResourceProcessor { @@ -100,14 +100,14 @@ public FormController(FormRepository formRepository, } @GetMapping(value = "/web/forms") - public PagedResources> getAllFormsWeb( + public CollectionModel> getAllFormsWeb( @RequestParam(value = "name", required = false) String name, @RequestParam(value = "includeVoided", required = false) boolean includeVoided, Pageable pageable) { Long organisationId = UserContextHolder.getUserContext().getOrganisation().getId(); - Sort sortWithId = pageable.getSort().and(new Sort("id")); + Sort sortWithId = pageable.getSort().and(Sort.by("id")); - PageRequest pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sortWithId); + PageRequest pageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sortWithId); Page
forms = formRepository.findAll((root, query, builder) -> { Predicate predicate = builder.equal(root.get("organisationId"), organisationId); @@ -390,11 +390,11 @@ private List getFormsByProgram(Program program, Pageable pagea Form form = fm.getForm(); BasicFormDetails formDetail = new BasicFormDetails(form, program.getOperationalProgramName()); formDetail.add(linkTo(methodOn(FormController.class).getForms(programId, pageable)).withSelfRel()); - Link formLink = entityLinks.linkToSingleResource(Form.class, form.getId()); + Link formLink = entityLinks.linkToItemResource(Form.class, form.getId()); formDetail.add(formLink); - formDetail.add(new Link(formLink.getHref() + "/formElementGroups", "formElementGroups")); - formDetail.add(entityLinks.linkToSingleResource(User.class, form.getCreatedBy().getId()).withRel("createdBy")); - formDetail.add(entityLinks.linkToSingleResource(User.class, form.getLastModifiedBy().getId()).withRel("lastModifiedBy")); + formDetail.add(Link.of(formLink.getHref() + "/formElementGroups", "formElementGroups")); + formDetail.add(entityLinks.linkToItemResource(User.class, form.getCreatedBy().getId()).withRel("createdBy")); + formDetail.add(entityLinks.linkToItemResource(User.class, form.getLastModifiedBy().getId()).withRel("lastModifiedBy")); return formDetail; }).collect(Collectors.toList()); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/FormMappingController.java b/avni-server-api/src/main/java/org/avni/server/web/FormMappingController.java index 982d53d95..cbfdb42d2 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/FormMappingController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/FormMappingController.java @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/GenderController.java b/avni-server-api/src/main/java/org/avni/server/web/GenderController.java index 8b2172a46..903ec2e56 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GenderController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GenderController.java @@ -14,7 +14,7 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/GroupDashboardController.java b/avni-server-api/src/main/java/org/avni/server/web/GroupDashboardController.java index 02a7785c5..134e3f96b 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GroupDashboardController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GroupDashboardController.java @@ -1,25 +1,25 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.GroupDashboardRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.GroupDashboard; import org.avni.server.domain.ValidationException; import org.avni.server.domain.accessControl.PrivilegeType; -import org.avni.server.domain.app.dashboard.DashboardFilter; import org.avni.server.service.GroupDashboardService; import org.avni.server.service.accessControl.AccessControlService; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.GroupDashboardContract; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -99,20 +99,20 @@ public List getDashboardsByGroupId(@PathVariable("id") L } @GetMapping(value = "/v2/groupDashboard/search/lastModified") - public PagedResources> getDashboardFilters(@RequestParam("lastModifiedDateTime") + public CollectionModel> getDashboardFilters(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(groupDashboardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + return wrap(groupDashboardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { GroupDashboard entity = resource.getContent(); resource.removeLinks(); - resource.add(new Link(entity.getDashboard().getUuid(), "dashboardUUID")); - resource.add(new Link(entity.getGroup().getUuid(), "groupUUID")); + resource.add(Link.of(entity.getDashboard().getUuid(), "dashboardUUID")); + resource.add(Link.of(entity.getGroup().getUuid(), "groupUUID")); addAuditFields(entity, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/GroupPrivilegeController.java b/avni-server-api/src/main/java/org/avni/server/web/GroupPrivilegeController.java index eff7fcd1c..f90591d0a 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GroupPrivilegeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GroupPrivilegeController.java @@ -1,10 +1,11 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.*; import org.avni.server.domain.Group; +import org.avni.server.domain.SubjectType; import org.avni.server.domain.accessControl.GroupPrivilege; import org.avni.server.domain.accessControl.Privilege; -import org.avni.server.domain.SubjectType; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.service.accessControl.GroupPrivilegeService; @@ -13,7 +14,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; diff --git a/avni-server-api/src/main/java/org/avni/server/web/GroupRoleController.java b/avni-server-api/src/main/java/org/avni/server/web/GroupRoleController.java index 43c1f877d..47bd6ad3b 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GroupRoleController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GroupRoleController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.GroupRoleRepository; import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.domain.GroupRole; @@ -12,14 +13,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class GroupRoleController implements RestControllerResourceProcessor { diff --git a/avni-server-api/src/main/java/org/avni/server/web/GroupSubjectController.java b/avni-server-api/src/main/java/org/avni/server/web/GroupSubjectController.java index 310917b25..b56316ff6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GroupSubjectController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GroupSubjectController.java @@ -1,11 +1,11 @@ package org.avni.server.web; -import org.avni.server.dao.*; +import jakarta.transaction.Transactional; +import org.avni.server.dao.GroupRoleRepository; +import org.avni.server.dao.GroupSubjectRepository; +import org.avni.server.dao.IndividualRepository; +import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.dao.sync.SyncEntityName; -import org.avni.server.domain.GroupRole; -import org.avni.server.domain.GroupSubject; -import org.avni.server.domain.Individual; -import org.avni.server.domain.SubjectType; import org.avni.server.domain.*; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.service.GroupSubjectService; @@ -26,13 +26,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -69,7 +68,7 @@ public GroupSubjectController(GroupSubjectRepository groupSubjectRepository, Use @RequestMapping(value = "/groupSubject/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getGroupSubjectsByOperatingIndividualScopeAsSlice( + public SlicedResources> getGroupSubjectsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String groupSubjectTypeUuid, @@ -83,7 +82,7 @@ public SlicedResources> getGroupSubjectsByOperatingIndivi @RequestMapping(value = "/groupSubject", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getGroupSubjectsByOperatingIndividualScope( + public CollectionModel> getGroupSubjectsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String groupSubjectTypeUuid, @@ -159,12 +158,12 @@ public List getGroupRoles(@PathVariable String groupUuid) { } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { GroupSubject groupSubject = resource.getContent(); resource.removeLinks(); - resource.add(new Link(groupSubject.getGroupSubject().getUuid(), "groupSubjectUUID")); - resource.add(new Link(groupSubject.getMemberSubject().getUuid(), "memberSubjectUUID")); - resource.add(new Link(groupSubject.getGroupRole().getUuid(), "groupRoleUUID")); + resource.add(Link.of(groupSubject.getGroupSubject().getUuid(), "groupSubjectUUID")); + resource.add(Link.of(groupSubject.getMemberSubject().getUuid(), "memberSubjectUUID")); + resource.add(Link.of(groupSubject.getGroupRole().getUuid(), "groupRoleUUID")); addAuditFields(groupSubject, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/GroupsController.java b/avni-server-api/src/main/java/org/avni/server/web/GroupsController.java index 46d4441b6..4e735b319 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/GroupsController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/GroupsController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.GroupRepository; import org.avni.server.dao.UserGroupRepository; import org.avni.server.domain.Group; @@ -14,13 +15,12 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; @@ -39,7 +39,7 @@ public GroupsController(GroupRepository groupRepository, GroupsService groupsSer } @GetMapping(value = "group") - public PagedResources> get(Pageable pageable) { + public CollectionModel> get(Pageable pageable) { Page all = groupRepository.findPageByIsVoidedFalse(pageable); Page groupContracts = all.map(GroupContract::fromEntity); return wrap(groupContracts); @@ -53,7 +53,7 @@ public List findAllById(@Param("ids") Long[] ids) { } @GetMapping(value = "/group/search/find") - public PagedResources> find( + public CollectionModel> find( @RequestParam(value = "isNotEveryoneGroup", defaultValue = "true") Boolean isNotEveryoneGroup, Pageable pageable) { Page groupContracts = null; diff --git a/avni-server-api/src/main/java/org/avni/server/web/IdentifierAssignmentController.java b/avni-server-api/src/main/java/org/avni/server/web/IdentifierAssignmentController.java index 1602523a0..0a9a87aea 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IdentifierAssignmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IdentifierAssignmentController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.IdentifierAssignmentRepository; import org.avni.server.dao.IndividualRepository; import org.avni.server.dao.ProgramEnrolmentRepository; @@ -15,14 +16,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; - import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @RestController @@ -58,7 +57,7 @@ public IdentifierAssignmentController(IdentifierAssignmentRepository identifierA @RequestMapping(value = "/identifierAssignment", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public PagedResources> get( + public CollectionModel> get( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam(value = "deviceId", required = false) String deviceId, Pageable pageable) { @@ -71,7 +70,7 @@ public PagedResources> get( @RequestMapping(value = "/identifierAssignment/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public SlicedResources> getAsSlice( + public SlicedResources> getAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam(value = "deviceId", required = false) String deviceId, Pageable pageable) { @@ -108,16 +107,16 @@ private IdentifierAssignment createIdentifierAssignment(IdentifierAssignmentRequ } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { IdentifierAssignment identifierAssignment = resource.getContent(); resource.removeLinks(); if (identifierAssignment.getProgramEnrolment() != null) { - resource.add(new Link(identifierAssignment.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); + resource.add(Link.of(identifierAssignment.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); } if (identifierAssignment.getIndividual() != null) { - resource.add(new Link(identifierAssignment.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(identifierAssignment.getIndividual().getUuid(), "individualUUID")); } - resource.add(new Link(identifierAssignment.getIdentifierSource().getUuid(), "identifierSourceUUID")); + resource.add(Link.of(identifierAssignment.getIdentifierSource().getUuid(), "identifierSourceUUID")); addAuditFields(identifierAssignment, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceController.java b/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceController.java index 6f56f3e64..fa8980ac6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.CatchmentRepository; import org.avni.server.dao.IdentifierSourceRepository; import org.avni.server.domain.CHSEntity; @@ -7,20 +8,18 @@ import org.avni.server.domain.User; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.domain.identifier.IdentifierGeneratorType; -import org.avni.server.service.accessControl.AccessControlService; -import org.joda.time.DateTime; import org.avni.server.service.UserService; +import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.IdentifierSourceContract; +import org.joda.time.DateTime; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; -import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; @RestController @@ -41,7 +40,7 @@ public IdentifierSourceController(IdentifierSourceRepository identifierSourceRep } @RequestMapping(value = "/identifierSource/search/lastModified", method = RequestMethod.GET) - public PagedResources> get( + public CollectionModel> get( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { diff --git a/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceWebController.java b/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceWebController.java index 7bdf01a64..5e82fd1f1 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceWebController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IdentifierSourceWebController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.IdentifierSourceRepository; import org.avni.server.domain.IdentifierSource; import org.avni.server.domain.accessControl.PrivilegeType; @@ -10,15 +11,12 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; - @RestController public class IdentifierSourceWebController extends AbstractController implements RestControllerResourceProcessor { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(IndividualController.class); @@ -34,7 +32,7 @@ public IdentifierSourceWebController(IdentifierSourceRepository identifierSource } @GetMapping(value = "/web/identifierSource/search/findAllById") - public PagedResources> findAllById(Long ids, Pageable pageable) { + public CollectionModel> findAllById(Long ids, Pageable pageable) { accessControlService.checkPrivilege(PrivilegeType.EditIdentifierSource); Long[] id = {ids}; return wrap(identifierSourceRepository.findByIdIn(id, pageable).map(IdentifierSourceContractWeb::fromIdentifierSource)); @@ -42,7 +40,7 @@ public PagedResources> findAllById(Long id @GetMapping(value = "/web/identifierSource") @ResponseBody - public PagedResources> getAll(Pageable pageable) { + public CollectionModel> getAll(Pageable pageable) { return wrap(identifierSourceRepository.findPageByIsVoidedFalse(pageable).map(IdentifierSourceContractWeb::fromIdentifierSource)); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentController.java b/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentController.java index 07557846d..32330a686 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.IdentifierSourceRepository; import org.avni.server.dao.IdentifierUserAssignmentRepository; import org.avni.server.dao.UserRepository; @@ -8,13 +9,11 @@ import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.IdentifierUserAssignmentContract; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentWebController.java b/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentWebController.java index 0110df5c3..661961fed 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentWebController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IdentifierUserAssignmentWebController.java @@ -1,29 +1,27 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; +import org.avni.server.dao.IdentifierSourceRepository; +import org.avni.server.dao.IdentifierUserAssignmentRepository; +import org.avni.server.dao.UserRepository; +import org.avni.server.domain.IdentifierUserAssignment; import org.avni.server.domain.ValidationException; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.domain.identifier.IdentifierOverlappingException; import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.service.identifier.IdentifierUserAssignmentService; +import org.avni.server.util.ReactAdminUtil; import org.avni.server.util.WebResponseUtil; +import org.avni.server.web.request.webapp.IdentifierUserAssignmentContractWeb; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.web.bind.annotation.RestController; -import org.avni.server.dao.IdentifierSourceRepository; -import org.avni.server.dao.IdentifierUserAssignmentRepository; -import org.avni.server.dao.UserRepository; -import org.avni.server.domain.IdentifierUserAssignment; -import org.avni.server.util.ReactAdminUtil; -import org.avni.server.web.request.webapp.IdentifierUserAssignmentContractWeb; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import javax.transaction.Transactional; import org.springframework.web.bind.annotation.*; @RestController @@ -46,7 +44,7 @@ public IdentifierUserAssignmentWebController(IdentifierUserAssignmentRepository @GetMapping(value = "/web/identifierUserAssignment") @ResponseBody - public PagedResources> getAll(Pageable pageable) { + public CollectionModel> getAll(Pageable pageable) { Page nonVoided = identifierUserAssignmentRepository.findPageByIsVoidedFalse(pageable); Page response = nonVoided.map(IdentifierUserAssignmentContractWeb::fromIdentifierUserAssignment); return wrap(response); diff --git a/avni-server-api/src/main/java/org/avni/server/web/ImplementationController.java b/avni-server-api/src/main/java/org/avni/server/web/ImplementationController.java index 10d6ad85a..268f9fc99 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ImplementationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ImplementationController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.domain.Concept; import org.avni.server.domain.Organisation; import org.avni.server.domain.accessControl.PrivilegeType; @@ -21,7 +22,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; import java.io.ByteArrayOutputStream; import java.util.zip.ZipOutputStream; diff --git a/avni-server-api/src/main/java/org/avni/server/web/ImportController.java b/avni-server-api/src/main/java/org/avni/server/web/ImportController.java index a3fb5e562..d288c2e09 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ImportController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ImportController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.servlet.http.HttpServletResponse; import org.avni.server.application.FormElement; import org.avni.server.dao.JobStatus; import org.avni.server.dao.application.FormElementRepository; @@ -33,10 +34,12 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; -import java.util.*; +import java.util.Base64; +import java.util.Collections; +import java.util.Map; +import java.util.UUID; import static java.lang.String.format; import static org.avni.server.util.AvniFiles.*; diff --git a/avni-server-api/src/main/java/org/avni/server/web/IndividualController.java b/avni-server-api/src/main/java/org/avni/server/web/IndividualController.java index 0e5107acc..00420e7f5 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IndividualController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IndividualController.java @@ -1,6 +1,7 @@ package org.avni.server.web; import com.bugsnag.Bugsnag; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.FormType; import org.avni.server.dao.*; @@ -34,21 +35,20 @@ import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.repository.query.Param; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; -import static org.springframework.data.jpa.domain.Specifications.where; +import static org.springframework.data.jpa.domain.Specification.where; @RestController public class IndividualController extends AbstractController implements RestControllerResourceProcessor { @@ -153,7 +153,7 @@ private void saveIdentifierAssignments(Individual individual, IndividualRequest @GetMapping(value = {"/individual/v2", "/individual/search/lastModified/v2"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getIndividualsByOperatingIndividualScopeAsSlice( + public SlicedResources> getIndividualsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -166,7 +166,7 @@ public SlicedResources> getIndividualsByOperatingIndividual @GetMapping(value = {"/individual", /*-->Both are Deprecated */ "/individual/search/byCatchmentAndLastModified", "/individual/search/lastModified"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getIndividualsByOperatingIndividualScope( + public CollectionModel> getIndividualsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -329,17 +329,17 @@ public ResponseEntity findByMetadata( } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Individual individual = resource.getContent(); resource.removeLinks(); if (individual.getAddressLevel() != null) { - resource.add(new Link(individual.getAddressLevel().getUuid(), "addressUUID")); + resource.add(Link.of(individual.getAddressLevel().getUuid(), "addressUUID")); } if (individual.getGender() != null) { - resource.add(new Link(individual.getGender().getUuid(), "genderUUID")); + resource.add(Link.of(individual.getGender().getUuid(), "genderUUID")); } if (individual.getSubjectType() != null) { - resource.add(new Link(individual.getSubjectType().getUuid(), "subjectTypeUUID")); + resource.add(Link.of(individual.getSubjectType().getUuid(), "subjectTypeUUID")); } addAuditFields(individual, resource); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationController.java b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationController.java index b41293b51..96d15d1d2 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.individualRelationship.IndividualRelationRepository; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.domain.individualRelationship.IndividualRelation; @@ -8,10 +9,8 @@ import org.avni.server.web.request.IndividualRelationContract; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Optional; diff --git a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipController.java b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipController.java index ca12bb845..88629233d 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.IndividualRepository; import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.dao.individualRelationship.IndividualRelationshipRepository; @@ -14,6 +15,7 @@ import org.avni.server.service.ScopeBasedSyncService; import org.avni.server.service.UserService; import org.avni.server.service.accessControl.AccessControlService; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.IndividualRelationshipRequest; import org.avni.server.web.response.slice.SlicedResources; import org.joda.time.DateTime; @@ -22,13 +24,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import java.util.Optional; @@ -76,7 +77,7 @@ public void save(@RequestBody IndividualRelationshipRequest request) { @RequestMapping(value = "/individualRelationship/search/byIndividualsOfCatchmentAndLastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getByIndividualsOfCatchmentAndLastModified( + public CollectionModel> getByIndividualsOfCatchmentAndLastModified( @RequestParam("catchmentId") long catchmentId, @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @@ -86,16 +87,16 @@ public PagedResources> getByIndividualsOfCatchm @RequestMapping(value = "/individualRelationship/search/lastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getByLastModified( + public CollectionModel> getByLastModified( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(individualRelationshipRepository.findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime, now, pageable)); + return wrap(individualRelationshipRepository.findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), DateTimeUtil.toInstant(now), pageable)); } @RequestMapping(value = "/individualRelationship/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getIndividualRelationshipsByOperatingIndividualScopeAsSlice( + public SlicedResources> getIndividualRelationshipsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -108,7 +109,7 @@ public SlicedResources> getIndividualRelationsh @RequestMapping(value = "/individualRelationship", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getIndividualRelationshipsByOperatingIndividualScope( + public CollectionModel> getIndividualRelationshipsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -120,12 +121,12 @@ public PagedResources> getIndividualRelationshi } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { IndividualRelationship individualRelationship = resource.getContent(); resource.removeLinks(); - resource.add(new Link(individualRelationship.getRelationship().getUuid(), "relationshipTypeUUID")); - resource.add(new Link(individualRelationship.getIndividuala().getUuid(), "individualAUUID")); - resource.add(new Link(individualRelationship.getIndividualB().getUuid(), "individualBUUID")); + resource.add(Link.of(individualRelationship.getRelationship().getUuid(), "relationshipTypeUUID")); + resource.add(Link.of(individualRelationship.getIndividuala().getUuid(), "individualAUUID")); + resource.add(Link.of(individualRelationship.getIndividualB().getUuid(), "individualBUUID")); addAuditFields(individualRelationship, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipTypeController.java b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipTypeController.java index 471827c59..573bf9130 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipTypeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/IndividualRelationshipTypeController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.individualRelationship.IndividualRelationshipTypeRepository; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.domain.individualRelationship.IndividualRelationshipType; @@ -7,10 +8,8 @@ import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.IndividualRelationshipTypeContract; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; @RestController diff --git a/avni-server-api/src/main/java/org/avni/server/web/LocationController.java b/avni-server-api/src/main/java/org/avni/server/web/LocationController.java index 6eafda967..7c23e7280 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/LocationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/LocationController.java @@ -1,6 +1,7 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.projections.LocationProjection; import org.avni.server.builder.BuilderException; import org.avni.server.dao.LocationRepository; @@ -27,13 +28,12 @@ import org.springframework.data.repository.query.Param; import org.springframework.data.rest.webmvc.RepositoryRestController; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -113,7 +113,7 @@ public List findByIdIn(@Param("ids") Long[] ids) { @RequestMapping(value = {"/locations/search/lastModified", "/locations/search/byCatchmentAndLastModified"}, method = RequestMethod.GET) @ResponseBody - public PagedResources> getAddressLevelsByOperatingIndividualScope( + public CollectionModel> getAddressLevelsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { diff --git a/avni-server-api/src/main/java/org/avni/server/web/LocationHierarchyController.java b/avni-server-api/src/main/java/org/avni/server/web/LocationHierarchyController.java index 21eafcc8f..60ee873fa 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/LocationHierarchyController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/LocationHierarchyController.java @@ -1,22 +1,25 @@ package org.avni.server.web; -import org.avni.server.domain.CHSEntity; -import org.joda.time.DateTime; import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.dao.LocationRepository; import org.avni.server.domain.AddressLevel; import org.avni.server.domain.AddressLevelType; +import org.avni.server.domain.CHSEntity; import org.avni.server.service.LocationHierarchyService; import org.avni.server.service.OrganisationConfigService; +import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; -import org.springframework.web.bind.annotation.*; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Collections; @@ -40,7 +43,7 @@ public LocationHierarchyController(LocationRepository locationRepository, Locati @GetMapping(value = "/locationHierarchy/search/lastModified") @ResponseBody - public PagedResources> getAddressLevels( + public CollectionModel> getAddressLevels( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, Pageable pageable) { try { diff --git a/avni-server-api/src/main/java/org/avni/server/web/LocationMappingController.java b/avni-server-api/src/main/java/org/avni/server/web/LocationMappingController.java index 3080d789a..d65a78d54 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/LocationMappingController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/LocationMappingController.java @@ -1,25 +1,24 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.LocationMappingRepository; import org.avni.server.dao.LocationMappingSyncRepository; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.domain.ParentLocationMapping; import org.avni.server.service.ScopeBasedSyncService; import org.avni.server.service.UserService; -import org.springframework.hateoas.PagedResources; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class LocationMappingController implements RestControllerResourceProcessor { private final LocationMappingRepository locationMappingRepository; @@ -37,7 +36,7 @@ public LocationMappingController(UserService userService, LocationMappingReposit @RequestMapping(value = {"/locationMapping/search/lastModified", "/locationMapping/search/byCatchmentAndLastModified"}, method = RequestMethod.GET) @Transactional - public PagedResources> getParentLocationMappingsByOperatingIndividualScope( + public CollectionModel> getParentLocationMappingsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -45,11 +44,11 @@ public PagedResources> getParentLocationMappings } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ParentLocationMapping content = resource.getContent(); resource.removeLinks(); - resource.add(new Link(content.getLocation().getUuid(), "locationUUID")); - resource.add(new Link(content.getParentLocation().getUuid(), "parentLocationUUID")); + resource.add(Link.of(content.getLocation().getUuid(), "locationUUID")); + resource.add(Link.of(content.getParentLocation().getUuid(), "parentLocationUUID")); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/LogoutController.java b/avni-server-api/src/main/java/org/avni/server/web/LogoutController.java index c691d5de1..5d165226e 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/LogoutController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/LogoutController.java @@ -1,12 +1,11 @@ package org.avni.server.web; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @RestController public class LogoutController { public static final String LOGOUT_URL = "/web/logout"; diff --git a/avni-server-api/src/main/java/org/avni/server/web/MediaController.java b/avni-server-api/src/main/java/org/avni/server/web/MediaController.java index 9782e931d..21c42f866 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/MediaController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/MediaController.java @@ -1,6 +1,8 @@ package org.avni.server.web; import com.amazonaws.HttpMethod; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.avni.server.domain.User; import org.avni.server.domain.accessControl.PrivilegeType; @@ -24,8 +26,6 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.io.File; import java.io.IOException; diff --git a/avni-server-api/src/main/java/org/avni/server/web/NewsController.java b/avni-server-api/src/main/java/org/avni/server/web/NewsController.java index 7dccd6f3b..401a81214 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/NewsController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/NewsController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.NewsRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.News; @@ -14,13 +15,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -106,7 +106,7 @@ public void deleteNews(@PathVariable Long id) { @RequestMapping(value = "/news/v2", method = RequestMethod.GET) @Transactional - public SlicedResources> getNewsAsSlice( + public SlicedResources> getNewsAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -115,7 +115,7 @@ public SlicedResources> getNewsAsSlice( @RequestMapping(value = "/news", method = RequestMethod.GET) @Transactional - public PagedResources> getNews( + public CollectionModel> getNews( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -123,10 +123,10 @@ public PagedResources> getNews( } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { News news = resource.getContent(); if (!S.isEmpty(news.getHeroImage())) { - resource.add(new Link(s3Service.generateMediaDownloadUrl(news.getHeroImage()).toString(), "heroImageSignedURL")); + resource.add(Link.of(s3Service.generateMediaDownloadUrl(news.getHeroImage()).toString(), "heroImageSignedURL")); } return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/OperationalEncounterTypesController.java b/avni-server-api/src/main/java/org/avni/server/web/OperationalEncounterTypesController.java index ef7523e5f..5cda5afe2 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OperationalEncounterTypesController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OperationalEncounterTypesController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.domain.Organisation; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.framework.security.UserContextHolder; @@ -12,8 +13,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class OperationalEncounterTypesController { private final EncounterTypeService encounterTypeService; diff --git a/avni-server-api/src/main/java/org/avni/server/web/OperationalProgramsController.java b/avni-server-api/src/main/java/org/avni/server/web/OperationalProgramsController.java index 30873e5b7..fd164c31d 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OperationalProgramsController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OperationalProgramsController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.domain.Organisation; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.framework.security.UserContextHolder; @@ -7,14 +8,11 @@ import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.OperationalProgramsContract; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class OperationalProgramsController { private final ProgramService programService; diff --git a/avni-server-api/src/main/java/org/avni/server/web/OperationalSubjectTypesController.java b/avni-server-api/src/main/java/org/avni/server/web/OperationalSubjectTypesController.java index 46e9e913c..4a0607f52 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OperationalSubjectTypesController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OperationalSubjectTypesController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.domain.Organisation; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.framework.security.UserContextHolder; @@ -7,14 +8,11 @@ import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.OperationalSubjectTypesContract; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class OperationalSubjectTypesController { private final SubjectTypeService subjectTypeService; diff --git a/avni-server-api/src/main/java/org/avni/server/web/OrganisationConfigController.java b/avni-server-api/src/main/java/org/avni/server/web/OrganisationConfigController.java index c024c7c06..3f70241fa 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OrganisationConfigController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OrganisationConfigController.java @@ -21,7 +21,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; @RepositoryRestController public class OrganisationConfigController implements RestControllerResourceProcessor { diff --git a/avni-server-api/src/main/java/org/avni/server/web/OrganisationController.java b/avni-server-api/src/main/java/org/avni/server/web/OrganisationController.java index 68785330a..662cb0055 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OrganisationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OrganisationController.java @@ -15,8 +15,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.persistence.criteria.Predicate; -import javax.transaction.Transactional; +import jakarta.persistence.criteria.Predicate; +import jakarta.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/web/OrganisationGroupController.java b/avni-server-api/src/main/java/org/avni/server/web/OrganisationGroupController.java index 524fbab7f..da2aff260 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/OrganisationGroupController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/OrganisationGroupController.java @@ -22,7 +22,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.HashSet; import java.util.Set; diff --git a/avni-server-api/src/main/java/org/avni/server/web/PlatformTranslationController.java b/avni-server-api/src/main/java/org/avni/server/web/PlatformTranslationController.java index 0c4113655..f3b018bc9 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/PlatformTranslationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/PlatformTranslationController.java @@ -12,13 +12,13 @@ import org.slf4j.LoggerFactory; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; @RestController public class PlatformTranslationController implements RestControllerResourceProcessor { @@ -54,7 +54,7 @@ public ResponseEntity uploadPlatformTranslations(@RequestBody TranslationRequ } @RequestMapping(value = "/platformTranslation/search/lastModified", method = RequestMethod.GET) - public PagedResources> get( + public CollectionModel> get( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { diff --git a/avni-server-api/src/main/java/org/avni/server/web/ProgramController.java b/avni-server-api/src/main/java/org/avni/server/web/ProgramController.java index 6000910fd..2433a93ef 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ProgramController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ProgramController.java @@ -24,14 +24,14 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -165,7 +165,7 @@ public ResponseEntity voidProgram(@PathVariable("id") Long id) { @GetMapping(value = "/web/program") @ResponseBody - public PagedResources> getAll(Pageable pageable) { + public CollectionModel> getAll(Pageable pageable) { return wrap(operationalProgramRepository .findPageByIsVoidedFalse(pageable) .map(ProgramContractWeb::fromOperationalProgram)); diff --git a/avni-server-api/src/main/java/org/avni/server/web/ProgramEncounterController.java b/avni-server-api/src/main/java/org/avni/server/web/ProgramEncounterController.java index 4ba2678eb..701889058 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ProgramEncounterController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ProgramEncounterController.java @@ -9,6 +9,7 @@ import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.service.*; import org.avni.server.service.accessControl.AccessControlService; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.ProgramEncounterContract; import org.avni.server.web.request.ProgramEncounterRequest; import org.avni.server.web.response.AvniEntityResponse; @@ -21,14 +22,15 @@ import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; +import org.springframework.hateoas.PagedModel; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -104,7 +106,7 @@ public AvniEntityResponse saveForWeb(@RequestBody ProgramEncounterRequest reques @RequestMapping(value = "/programEncounter/search/byIndividualsOfCatchmentAndLastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Deprecated() - public PagedResources> getByIndividualsOfCatchmentAndLastModified( + public PagedModel> getByIndividualsOfCatchmentAndLastModified( @RequestParam("catchmentId") long catchmentId, @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @@ -114,16 +116,16 @@ public PagedResources> getByIndividualsOfCatchmentAnd @RequestMapping(value = "/programEncounter/search/lastModified", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getByLastModified( + public CollectionModel> getByLastModified( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(programEncounterRepository.findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime, now, pageable)); + return wrap(programEncounterRepository.findByLastModifiedDateTimeIsBetweenOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), DateTimeUtil.toInstant(now), pageable)); } @RequestMapping(value = "/programEncounter/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getProgramEncountersByOperatingIndividualScopeAsSlice( + public SlicedResources> getProgramEncountersByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "programEncounterTypeUuid", required = false) String encounterTypeUuid, @@ -140,7 +142,7 @@ public SlicedResources> getProgramEncountersByOperati @RequestMapping(value = "/programEncounter", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getProgramEncountersByOperatingIndividualScope( + public CollectionModel> getProgramEncountersByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "programEncounterTypeUuid", required = false) String encounterTypeUuid, @@ -176,11 +178,11 @@ public AvniEntityResponse voidProgramEncounter(@PathVariable String uuid) { } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ProgramEncounter programEncounter = resource.getContent(); resource.removeLinks(); - resource.add(new Link(programEncounter.getEncounterType().getUuid(), "encounterTypeUUID")); - resource.add(new Link(programEncounter.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); + resource.add(Link.of(programEncounter.getEncounterType().getUuid(), "encounterTypeUUID")); + resource.add(Link.of(programEncounter.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); addAuditFields(programEncounter, resource); addUserFields(programEncounter.getFilledBy(), resource, "filledBy"); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/ProgramEnrolmentController.java b/avni-server-api/src/main/java/org/avni/server/web/ProgramEnrolmentController.java index 418827037..7b98984d0 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ProgramEnrolmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ProgramEnrolmentController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.FormType; import org.avni.server.dao.ProgramEnrolmentRepository; @@ -25,15 +26,14 @@ import org.springframework.data.domain.SliceImpl; import org.springframework.data.projection.ProjectionFactory; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -93,7 +93,7 @@ public AvniEntityResponse saveForWeb(@RequestBody ProgramEnrolmentRequest reques @GetMapping(value = {"/programEnrolment/v2"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getProgramEnrolmentsByOperatingIndividualScopeAsSlice( + public SlicedResources> getProgramEnrolmentsByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "programUuid", required = false) String programUuid, @@ -111,7 +111,7 @@ public SlicedResources> getProgramEnrolmentsByOperati @GetMapping(value = {"/programEnrolment", /* Deprecated -> */ "/programEnrolment/search/lastModified", "/programEnrolment/search/byIndividualsOfCatchmentAndLastModified"}) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getProgramEnrolmentsByOperatingIndividualScope( + public CollectionModel> getProgramEnrolmentsByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "programUuid", required = false) String programUuid, @@ -177,11 +177,11 @@ public AvniEntityResponse voidProgramEnrolment(@PathVariable String uuid) { } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ProgramEnrolment programEnrolment = resource.getContent(); resource.removeLinks(); - resource.add(new Link(programEnrolment.getProgram().getUuid(), "programUUID")); - resource.add(new Link(programEnrolment.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(programEnrolment.getProgram().getUuid(), "programUUID")); + resource.add(Link.of(programEnrolment.getIndividual().getUuid(), "individualUUID")); addAuditFields(programEnrolment, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/ReportCardController.java b/avni-server-api/src/main/java/org/avni/server/web/ReportCardController.java index c5eee269c..547473f19 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ReportCardController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ReportCardController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.CardRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.ReportCard; @@ -9,20 +10,20 @@ import org.avni.server.service.CardService; import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.util.BadRequestError; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.reports.ReportCardWebRequest; import org.avni.server.web.response.reports.ReportCardWebResponse; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -95,21 +96,21 @@ public void deleteCard(@PathVariable Long id) { } @GetMapping(value = "/v2/card/search/lastModified") - public PagedResources> getReportCards(@RequestParam("lastModifiedDateTime") + public CollectionModel> getReportCards(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { - return wrap(cardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(lastModifiedDateTime.toDate(), + return wrap(cardRepository.findByLastModifiedDateTimeIsGreaterThanEqualAndLastModifiedDateTimeLessThanEqualOrderByLastModifiedDateTimeAscIdAsc(DateTimeUtil.toInstant(lastModifiedDateTime), CHSEntity.toDate(now), pageable)); } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ReportCard entity = resource.getContent(); resource.removeLinks(); StandardReportCardType standardReportCardType = entity.getStandardReportCardType(); if (standardReportCardType != null) - resource.add(new Link(standardReportCardType.getUuid(), "standardReportCardUUID")); + resource.add(Link.of(standardReportCardType.getUuid(), "standardReportCardUUID")); addAuditFields(entity, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/ReportingController.java b/avni-server-api/src/main/java/org/avni/server/web/ReportingController.java index 921d73ac9..74e4172e6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ReportingController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ReportingController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.persistence.EntityNotFoundException; import org.avni.server.application.Form; import org.avni.server.application.FormMapping; import org.avni.server.application.projections.CatchmentAddressProjection; @@ -22,7 +23,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.persistence.EntityNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/web/ResetSyncController.java b/avni-server-api/src/main/java/org/avni/server/web/ResetSyncController.java index dd8a16c20..3491bb01b 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ResetSyncController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ResetSyncController.java @@ -8,9 +8,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -29,7 +29,7 @@ public ResetSyncController(ResetSyncService resetSyncService) { @RequestMapping(value = "/resetSyncs", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> fetchByLastModified( + public CollectionModel> fetchByLastModified( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -38,11 +38,11 @@ public PagedResources> fetchByLastModified( } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ResetSync resetSync = resource.getContent(); resource.removeLinks(); if (resetSync.getSubjectType() != null) { - resource.add(new Link(resetSync.getSubjectType().getUuid(), "subjectTypeUUID")); + resource.add(Link.of(resetSync.getSubjectType().getUuid(), "subjectTypeUUID")); } return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/RestControllerResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/RestControllerResourceProcessor.java index 43b5e2348..9327bdbc6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/RestControllerResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/RestControllerResourceProcessor.java @@ -4,44 +4,43 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.EntityModel; +import org.springframework.hateoas.PagedModel; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public interface RestControllerResourceProcessor { - - default Resource process(Resource t) { + default EntityModel process(EntityModel t) { return t; } - default PagedResources> wrap(Page page) { - PagedResources.PageMetadata pageMetadata = new PagedResources.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages()); - List> resources = new ArrayList<>(); - for (T it : page) resources.add(this.process(new Resource<>(it))); - return new PagedResources<>(resources, pageMetadata); + default PagedModel> wrap(Page page) { + PagedModel.PageMetadata pageMetadata = new PagedModel.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages()); + List> resources = new ArrayList<>(); + for (T it : page) resources.add(this.process(EntityModel.of(it))); + return PagedModel.of(resources, pageMetadata); } - default SlicedResources> wrap(Slice slice) { + default SlicedResources> wrap(Slice slice) { SlicedResources.SliceMetadata sliceMetadata = new SlicedResources.SliceMetadata(slice.getSize(), slice.getNumber(), slice.hasNext()); - List> resources = new ArrayList<>(); - for (T it : slice) resources.add(this.process(new Resource<>(it))); + List> resources = new ArrayList<>(); + for (T it : slice) resources.add(this.process(EntityModel.of(it))); return new SlicedResources<>(resources, sliceMetadata); } - default List> wrap(List list) { - return list.stream().map(t -> this.process(new Resource<>(t))).collect(Collectors.toList()); + default List> wrap(List list) { + return list.stream().map(t -> this.process(EntityModel.of(t))).collect(Collectors.toList()); } - default PagedResources> empty(Pageable pageable) { - PagedResources.PageMetadata pageMetadata = new PagedResources.PageMetadata(pageable.getPageSize(), 0, 0, 0); - return new PagedResources<>(new ArrayList<>(), pageMetadata); + default PagedModel> empty(Pageable pageable) { + PagedModel.PageMetadata pageMetadata = new PagedModel.PageMetadata(pageable.getPageSize(), 0, 0, 0); + return PagedModel.of(new ArrayList<>(), pageMetadata); } - default PagedResources wrapListAsPage(List list) { - PagedResources.PageMetadata pageMetadata = new PagedResources.PageMetadata(list.size(), 0, list.size(), 1); - return new PagedResources<>(list, pageMetadata); + default PagedModel wrapListAsPage(List list) { + PagedModel.PageMetadata pageMetadata = new PagedModel.PageMetadata(list.size(), 0, list.size(), 1); + return PagedModel.of(list, pageMetadata); } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/StandardReportCardTypeController.java b/avni-server-api/src/main/java/org/avni/server/web/StandardReportCardTypeController.java index b81e44a2b..5afd1f062 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/StandardReportCardTypeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/StandardReportCardTypeController.java @@ -3,14 +3,12 @@ import org.avni.server.dao.StandardReportCardTypeRepository; import org.avni.server.domain.StandardReportCardType; import org.avni.server.web.request.StandardReportCardTypeContract; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Pageable; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; diff --git a/avni-server-api/src/main/java/org/avni/server/web/SubjectMigrationController.java b/avni-server-api/src/main/java/org/avni/server/web/SubjectMigrationController.java index eec872994..d7659e3a0 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SubjectMigrationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SubjectMigrationController.java @@ -25,11 +25,13 @@ import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.*; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -72,7 +74,7 @@ public SubjectMigrationController(SubjectMigrationRepository subjectMigrationRep @RequestMapping(value = "/subjectMigrations/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getMigrationsByCatchmentAndLastModifiedAsSlice( + public SlicedResources> getMigrationsByCatchmentAndLastModifiedAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -86,7 +88,7 @@ public SlicedResources> getMigrationsByCatchmentAndLa @RequestMapping(value = "/subjectMigrations", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getMigrationsByCatchmentAndLastModified( + public CollectionModel> getMigrationsByCatchmentAndLastModified( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -99,15 +101,15 @@ public PagedResources> getMigrationsByCatchmentAndLas } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { SubjectMigration content = resource.getContent(); resource.removeLinks(); - resource.add(new Link(content.getIndividual().getUuid(), "individualUUID")); - resource.add(new Link(content.getSubjectType().getUuid(), "subjectTypeUUID")); + resource.add(Link.of(content.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(content.getSubjectType().getUuid(), "subjectTypeUUID")); if (content.getOldAddressLevel() != null) - resource.add(new Link(content.getOldAddressLevel().getUuid(), "oldAddressLevelUUID")); + resource.add(Link.of(content.getOldAddressLevel().getUuid(), "oldAddressLevelUUID")); if (content.getNewAddressLevel() != null) - resource.add(new Link(content.getNewAddressLevel().getUuid(), "newAddressLevelUUID")); + resource.add(Link.of(content.getNewAddressLevel().getUuid(), "newAddressLevelUUID")); addAuditFields(content, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/SubjectProgramEligibilityController.java b/avni-server-api/src/main/java/org/avni/server/web/SubjectProgramEligibilityController.java index 61830a553..27829901a 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SubjectProgramEligibilityController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SubjectProgramEligibilityController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.IndividualRepository; import org.avni.server.dao.ProgramRepository; import org.avni.server.dao.SubjectTypeRepository; @@ -24,13 +25,12 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.SliceImpl; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Collections; import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @@ -66,7 +66,7 @@ public SubjectProgramEligibilityController(SubjectProgramEligibilityRepository s @RequestMapping(value = "/subjectProgramEligibility/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public SlicedResources> getSubjectProgramEligibilityByOperatingIndividualScopeAsSlice( + public SlicedResources> getSubjectProgramEligibilityByOperatingIndividualScopeAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -80,7 +80,7 @@ public SlicedResources> getSubjectProgramEli @RequestMapping(value = "/subjectProgramEligibility", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getSubjectProgramEligibilityByOperatingIndividualScope( + public CollectionModel> getSubjectProgramEligibilityByOperatingIndividualScope( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, @RequestParam(value = "subjectTypeUuid", required = false) String subjectTypeUuid, @@ -112,11 +112,11 @@ public AvniEntityResponse save(@RequestBody SubjectProgramEligibilityContract re } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { SubjectProgramEligibility subjectProgramEligibility = resource.getContent(); resource.removeLinks(); - resource.add(new Link(subjectProgramEligibility.getSubject().getUuid(), "subjectUUID")); - resource.add(new Link(subjectProgramEligibility.getProgram().getUuid(), "programUUID")); + resource.add(Link.of(subjectProgramEligibility.getSubject().getUuid(), "subjectUUID")); + resource.add(Link.of(subjectProgramEligibility.getProgram().getUuid(), "programUUID")); addAuditFields(subjectProgramEligibility, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/SubjectTypeController.java b/avni-server-api/src/main/java/org/avni/server/web/SubjectTypeController.java index a8e76ed39..5ff56affa 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SubjectTypeController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SubjectTypeController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.FormMapping; import org.avni.server.application.FormType; import org.avni.server.application.Subject; @@ -24,13 +25,12 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -83,7 +83,7 @@ public void save(@RequestBody List subjectTypeRequests) { @GetMapping(value = "/web/subjectType") @ResponseBody - public PagedResources> getAll(Pageable pageable) { + public CollectionModel> getAll(Pageable pageable) { return wrap(operationalSubjectTypeRepository .findPageByIsVoidedFalse(pageable) .map((OperationalSubjectType operationalSubjectType) -> { diff --git a/avni-server-api/src/main/java/org/avni/server/web/SyncController.java b/avni-server-api/src/main/java/org/avni/server/web/SyncController.java index b2df02101..af8496840 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SyncController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SyncController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.annotation.PostConstruct; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.domain.JsonObject; import org.avni.server.domain.SyncableItem; @@ -22,8 +23,10 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.annotation.PostConstruct; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import static org.avni.server.dao.sync.SyncEntityName.*; diff --git a/avni-server-api/src/main/java/org/avni/server/web/SyncSubjectController.java b/avni-server-api/src/main/java/org/avni/server/web/SyncSubjectController.java index 41ed52e5d..9e4381251 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SyncSubjectController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SyncSubjectController.java @@ -4,7 +4,7 @@ import org.avni.server.web.resourceProcessors.*; import org.avni.server.web.response.SyncSubjectResponse; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; @@ -24,23 +24,23 @@ public SyncSubjectController(SubjectSyncResponseBuilderService subjectSyncRespon this.subjectSyncResponseBuilderService = subjectSyncResponseBuilderService; } - public Resource> process(SyncSubjectResponse syncSubjectResponse) { + public EntityModel> process(SyncSubjectResponse syncSubjectResponse) { HashMap result = new HashMap<>(); - result.put("individual", new IndividualResourceProcessor().process(new Resource<>(syncSubjectResponse.getIndividual()))); - result.put("programEnrolments", syncSubjectResponse.getProgramEnrolments().stream().map(programEnrolment -> new ProgramEnrolmentResourceProcessor().process(new Resource<>(programEnrolment)))); - result.put("programEncounters", syncSubjectResponse.getProgramEncounters().stream().map(programEncounter1 -> new ProgramEncounterResourceProcessor().process(new Resource<>(programEncounter1)))); - result.put("encounters", syncSubjectResponse.getEncounters().stream().map(encounter -> new EncounterResourceProcessor().process(new Resource<>(encounter)))); - result.put("checklists", syncSubjectResponse.getChecklists().stream().map(checklist -> new ChecklistResourceProcessor().process(new Resource<>(checklist)))); - result.put("checklistItems", syncSubjectResponse.getChecklistItems().stream().map(checklistItem -> new ChecklistItemResourceProcessor().process(new Resource<>(checklistItem)))); - result.put("groupSubjects", syncSubjectResponse.getGroupSubjects().stream().map(groupSubject -> new GroupSubjectResourceProcessor().process(new Resource<>(groupSubject)))); - result.put("individualRelationships", syncSubjectResponse.getIndividualRelationships().stream().map(individualRelationship -> new IndividualRelationshipResourceProcessor().process(new Resource<>(individualRelationship)))); - return new Resource<>(result); + result.put("individual", new IndividualResourceProcessor().process(EntityModel.of(syncSubjectResponse.getIndividual()))); + result.put("programEnrolments", syncSubjectResponse.getProgramEnrolments().stream().map(programEnrolment -> new ProgramEnrolmentResourceProcessor().process(EntityModel.of(programEnrolment)))); + result.put("programEncounters", syncSubjectResponse.getProgramEncounters().stream().map(programEncounter1 -> new ProgramEncounterResourceProcessor().process(EntityModel.of(programEncounter1)))); + result.put("encounters", syncSubjectResponse.getEncounters().stream().map(encounter -> new EncounterResourceProcessor().process(EntityModel.of(encounter)))); + result.put("checklists", syncSubjectResponse.getChecklists().stream().map(checklist -> new ChecklistResourceProcessor().process(EntityModel.of(checklist)))); + result.put("checklistItems", syncSubjectResponse.getChecklistItems().stream().map(checklistItem -> new ChecklistItemResourceProcessor().process(EntityModel.of(checklistItem)))); + result.put("groupSubjects", syncSubjectResponse.getGroupSubjects().stream().map(groupSubject -> new GroupSubjectResourceProcessor().process(EntityModel.of(groupSubject)))); + result.put("individualRelationships", syncSubjectResponse.getIndividualRelationships().stream().map(individualRelationship -> new IndividualRelationshipResourceProcessor().process(EntityModel.of(individualRelationship)))); + return EntityModel.of(result); } @GetMapping("/subject/{uuid}/allEntities") @PreAuthorize(value = "hasAnyAuthority('user')") @ResponseBody - public ResponseEntity>> getSubjectDetailsForSync(@PathVariable String uuid) { + public ResponseEntity>> getSubjectDetailsForSync(@PathVariable String uuid) { return ResponseEntity.ok(process(subjectSyncResponseBuilderService.getSubject(uuid))) ; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/SyncTelemetryController.java b/avni-server-api/src/main/java/org/avni/server/web/SyncTelemetryController.java index 80a09cc38..ec5e58415 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/SyncTelemetryController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/SyncTelemetryController.java @@ -1,21 +1,23 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.SyncTelemetryRepository; import org.avni.server.domain.Organisation; import org.avni.server.domain.SyncTelemetry; import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.DateTimeUtil; import org.avni.server.web.request.SyncTelemetryRequest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; + import java.util.List; @RestController @@ -51,26 +53,27 @@ public void saveSyncTelemetry(@RequestBody SyncTelemetryRequest request) { @RequestMapping(value = "/report/syncTelemetry", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getAll(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) DateTime startDate, + public CollectionModel> getAll(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) DateTime startDate, @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) DateTime endDate, @RequestParam(value = "userIds", required = false, defaultValue = "") List userIds, Pageable pageable) { if (startDate == null && userIds.isEmpty()) { return wrap(syncTelemetryRepository.findAllByOrderByIdDesc(pageable)); } else if (startDate != null && !userIds.isEmpty()) { - return wrap(syncTelemetryRepository.findAllByUserIdInAndSyncStartTimeBetweenOrderByIdDesc(userIds, startDate, endDate, pageable)); + return wrap(syncTelemetryRepository.findAllByUserIdInAndSyncStartTimeBetweenOrderByIdDesc(userIds, DateTimeUtil.toInstant(startDate), + DateTimeUtil.toInstant(endDate), pageable)); } else if (!userIds.isEmpty()) { return wrap(syncTelemetryRepository.findAllByUserIdInOrderByIdDesc(userIds, pageable)); } else { - return wrap(syncTelemetryRepository.findAllBySyncStartTimeBetweenOrderByIdDesc(startDate, endDate, pageable)); + return wrap(syncTelemetryRepository.findAllBySyncStartTimeBetweenOrderByIdDesc(DateTimeUtil.toInstant(startDate), DateTimeUtil.toInstant(endDate), pageable)); } } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { SyncTelemetry syncTelemetry = resource.getContent(); resource.removeLinks(); - resource.add(new Link(syncTelemetry.getUser().getName(), "userName")); + resource.add(Link.of(syncTelemetry.getUser().getName(), "userName")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/TranslationController.java b/avni-server-api/src/main/java/org/avni/server/web/TranslationController.java index 7d6866ccf..beaafe1ca 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/TranslationController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/TranslationController.java @@ -1,12 +1,13 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.application.Platform; import org.avni.server.dao.*; import org.avni.server.dao.application.FormElementGroupRepository; import org.avni.server.dao.application.FormElementRepository; import org.avni.server.dao.application.FormRepository; -import org.avni.server.domain.*; import org.avni.server.domain.Locale; +import org.avni.server.domain.*; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.accessControl.AccessControlService; @@ -23,7 +24,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/web/UserController.java b/avni-server-api/src/main/java/org/avni/server/web/UserController.java index 7f7ce1099..c3e641971 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/UserController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/UserController.java @@ -2,6 +2,11 @@ import com.amazonaws.services.cognitoidp.model.AWSCognitoIdentityProviderException; import com.amazonaws.services.cognitoidp.model.UsernameExistsException; +import jakarta.persistence.EntityNotFoundException; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import jakarta.transaction.Transactional; import org.apache.commons.validator.routines.EmailValidator; import org.avni.server.dao.*; import org.avni.server.domain.Account; @@ -32,11 +37,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.persistence.EntityNotFoundException; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; diff --git a/avni-server-api/src/main/java/org/avni/server/web/UserGroupController.java b/avni-server-api/src/main/java/org/avni/server/web/UserGroupController.java index 4b4225b93..3f86396a2 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/UserGroupController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/UserGroupController.java @@ -1,29 +1,28 @@ package org.avni.server.web; -import org.avni.server.domain.CHSEntity; -import org.avni.server.domain.accessControl.PrivilegeType; -import org.avni.server.service.accessControl.AccessControlService; -import org.joda.time.DateTime; +import jakarta.transaction.Transactional; import org.avni.server.dao.GroupRepository; import org.avni.server.dao.UserGroupRepository; import org.avni.server.dao.UserRepository; +import org.avni.server.domain.CHSEntity; import org.avni.server.domain.Group; import org.avni.server.domain.User; import org.avni.server.domain.UserGroup; +import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.request.UserGroupContract; +import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -45,7 +44,7 @@ public UserGroupController(UserGroupRepository userGroupRepository, UserReposito } @RequestMapping(value = "/myGroups/search/lastModified", method = RequestMethod.GET) - public PagedResources> get(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, + public CollectionModel> get(@RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { User user = UserContextHolder.getUserContext().getUser(); diff --git a/avni-server-api/src/main/java/org/avni/server/web/UserInfoController.java b/avni-server-api/src/main/java/org/avni/server/web/UserInfoController.java index 92c7fb519..31a81a22f 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/UserInfoController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/UserInfoController.java @@ -1,42 +1,44 @@ package org.avni.server.web; -import org.avni.server.dao.CatchmentRepository; -import org.avni.server.dao.OrganisationRepository; -import org.avni.server.dao.UserRepository; -import org.avni.server.domain.*; -import org.avni.server.domain.accessControl.GroupPrivilege; -import org.avni.server.domain.accessControl.PrivilegeType; -import org.avni.server.framework.security.UserContextHolder; -import org.avni.server.service.*; -import org.avni.server.service.accessControl.AccessControlService; -import org.avni.server.service.accessControl.GroupPrivilegeService; -import org.avni.server.util.PhoneNumberUtil; -import org.avni.server.util.RegionUtil; -import org.avni.server.web.request.GroupPrivilegeContract; -import org.avni.server.web.request.UserBulkUploadContract; -import org.avni.server.web.request.UserInfoClientContract; -import org.avni.server.web.request.UserInfoContract; -import org.avni.server.web.response.slice.SlicedResources; -import org.joda.time.DateTime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.SliceImpl; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.transaction.Transactional; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; + import jakarta.transaction.Transactional; + import org.avni.server.dao.CatchmentRepository; + import org.avni.server.dao.OrganisationRepository; + import org.avni.server.dao.UserRepository; + import org.avni.server.domain.*; + import org.avni.server.domain.accessControl.GroupPrivilege; + import org.avni.server.domain.accessControl.PrivilegeType; + import org.avni.server.framework.security.UserContextHolder; + import org.avni.server.service.IDPException; + import org.avni.server.service.IdpServiceFactory; + import org.avni.server.service.OrganisationConfigService; + import org.avni.server.service.UserService; + import org.avni.server.service.accessControl.AccessControlService; + import org.avni.server.service.accessControl.GroupPrivilegeService; + import org.avni.server.util.RegionUtil; + import org.avni.server.web.request.GroupPrivilegeContract; + import org.avni.server.web.request.UserBulkUploadContract; + import org.avni.server.web.request.UserInfoClientContract; + import org.avni.server.web.request.UserInfoContract; + import org.avni.server.web.response.slice.SlicedResources; + import org.joda.time.DateTime; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.annotation.Autowired; + import org.springframework.data.domain.PageImpl; + import org.springframework.data.domain.SliceImpl; + import org.springframework.hateoas.CollectionModel; + import org.springframework.hateoas.EntityModel; + import org.springframework.http.HttpStatus; + import org.springframework.http.ResponseEntity; + import org.springframework.web.bind.annotation.RequestBody; + import org.springframework.web.bind.annotation.RequestMapping; + import org.springframework.web.bind.annotation.RequestMethod; + import org.springframework.web.bind.annotation.RestController; + + import java.util.Arrays; + import java.util.List; + import java.util.UUID; + import java.util.stream.Collectors; @RestController public class UserInfoController implements RestControllerResourceProcessor { @@ -92,7 +94,7 @@ public ResponseEntity getMyProfileOld() { } @RequestMapping(value = "/v2/me", method = RequestMethod.GET) - public PagedResources> getMyProfile() { + public CollectionModel> getMyProfile() { UserContext userContext = UserContextHolder.getUserContext(); User user = userContext.getUser(); Organisation organisation = userContext.getOrganisation(); @@ -101,7 +103,7 @@ public PagedResources> getMyProfile() { } @RequestMapping(value = "/me/v3", method = RequestMethod.GET) - public SlicedResources> getMyProfileAsSlice() { + public SlicedResources> getMyProfileAsSlice() { UserContext userContext = UserContextHolder.getUserContext(); User user = userContext.getUser(); Organisation organisation = userContext.getOrganisation(); diff --git a/avni-server-api/src/main/java/org/avni/server/web/UserSubjectAssignmentController.java b/avni-server-api/src/main/java/org/avni/server/web/UserSubjectAssignmentController.java index 4a59c3b0a..1b783b510 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/UserSubjectAssignmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/UserSubjectAssignmentController.java @@ -15,9 +15,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -45,7 +45,7 @@ public UserSubjectAssignmentController(UserSubjectAssignmentRepository userSubje @RequestMapping(value = "/userSubjectAssignment", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public PagedResources> getTasks( + public CollectionModel> getTasks( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -56,7 +56,7 @@ public PagedResources> getTasks( @RequestMapping(value = "/userSubjectAssignment/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public SlicedResources> getTasksAsSlice( + public SlicedResources> getTasksAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -91,10 +91,10 @@ ResponseEntity save(@RequestBody UserSubjectAssignmentContract userSubjectAss } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { UserSubjectAssignment userSubjectAssignment = resource.getContent(); resource.removeLinks(); - resource.add(new Link(userSubjectAssignment.getSubject().getUuid(), "subjectUUID")); + resource.add(Link.of(userSubjectAssignment.getSubject().getUuid(), "subjectUUID")); addAuditFields(userSubjectAssignment, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/UtilityController.java b/avni-server-api/src/main/java/org/avni/server/web/UtilityController.java deleted file mode 100644 index 88f477144..000000000 --- a/avni-server-api/src/main/java/org/avni/server/web/UtilityController.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.avni.server.web; - -import org.avni.server.application.Form; -import org.avni.server.application.FormElement; -import org.avni.server.dao.application.FormRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ClassPathResource; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import javax.script.Invocable; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.List; -import java.util.stream.Collectors; - -@RestController -public class UtilityController { - private FormRepository formRepository; - private final Invocable invocable; - - @Autowired - public UtilityController(FormRepository formRepository) throws IOException, ScriptException { - this.formRepository = formRepository; - Reader camelCaseFile = new InputStreamReader(new ClassPathResource("/js/camelCase.js").getInputStream()); - ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); - engine.eval(camelCaseFile); - invocable = (Invocable) engine; - } - - @RequestMapping(value = "/util/formElementHandlerNames", method = RequestMethod.GET) - public List formElementHandlerNames(@RequestParam(value = "formUUID") String formUUID) { - Form form = formRepository.findByUuid(formUUID); - return form.getAllFormElements().stream() - .map(FormElement::getName) - .map((String str) -> { - try { - return (String) invocable.invokeFunction("camelCase", str); - } catch (Exception e) {//ignore - return ""; - } - }) - .collect(Collectors.toList()); - } -} diff --git a/avni-server-api/src/main/java/org/avni/server/web/VideoController.java b/avni-server-api/src/main/java/org/avni/server/web/VideoController.java index 2f832781a..a898c7c3d 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/VideoController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/VideoController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.builder.VideoBuilder; import org.avni.server.dao.VideoRepository; import org.avni.server.domain.Video; @@ -12,7 +13,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.Arrays; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/web/VideoTelemetricController.java b/avni-server-api/src/main/java/org/avni/server/web/VideoTelemetricController.java index 75b621c6b..814cb1966 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/VideoTelemetricController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/VideoTelemetricController.java @@ -1,6 +1,6 @@ package org.avni.server.web; -import org.joda.time.DateTime; +import jakarta.transaction.Transactional; import org.avni.server.builder.VideoTelemetricBuilder; import org.avni.server.dao.VideoRepository; import org.avni.server.dao.VideoTelemetricRepository; @@ -10,18 +10,14 @@ import org.avni.server.domain.VideoTelemetric; import org.avni.server.framework.security.UserContextHolder; import org.avni.server.web.request.VideoTelemetricContract; +import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class VideoTelemetricController implements RestControllerResourceProcessor { diff --git a/avni-server-api/src/main/java/org/avni/server/web/ViewGenController.java b/avni-server-api/src/main/java/org/avni/server/web/ViewGenController.java index 6e7bf8cd6..727bfa271 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/ViewGenController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/ViewGenController.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.dao.ImplementationRepository; import org.avni.server.dao.SubjectTypeRepository; import org.avni.server.dao.application.FormMappingRepository; @@ -19,7 +20,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/avni-server-api/src/main/java/org/avni/server/web/api/GeneralEncounterApiController.java b/avni-server-api/src/main/java/org/avni/server/web/api/GeneralEncounterApiController.java index 5f7c8502c..79f550b38 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/api/GeneralEncounterApiController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/api/GeneralEncounterApiController.java @@ -29,7 +29,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.io.IOException; import java.util.ArrayList; import java.util.Map; @@ -77,7 +77,7 @@ public ResponsePage getEncounters(@RequestParam(value = "lastModifiedDateTime", Page encounters; Map conceptsMap = conceptService.readConceptsFromJsonObject(concepts); - EncounterSearchRequest encounterSearchRequest = new EncounterSearchRequest(CHSEntity.toDate(lastModifiedDateTime), CHSEntity.toDate(now), encounterType, subjectUUID, conceptsMap, pageable); + EncounterSearchRequest encounterSearchRequest = new EncounterSearchRequest(CHSEntity.toUtilDate(lastModifiedDateTime), CHSEntity.toUtilDate(now), encounterType, subjectUUID, conceptsMap, pageable); TimeTakenLogger timeTakenLogger = new TimeTakenLogger("Search encounters", logger); encounters = encounterService.search(encounterSearchRequest); timeTakenLogger.logInfo(); diff --git a/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEncounterApiController.java b/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEncounterApiController.java index eedcd0b2d..169ad28e8 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEncounterApiController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEncounterApiController.java @@ -30,7 +30,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import java.io.IOException; import java.util.ArrayList; import java.util.Map; @@ -95,7 +95,7 @@ public ProgramEncounterRepository.SearchParams createSearchParams(DateTime lastM programEnrolment = programEnrolmentRepository.findByUuid(programEnrolmentUuid); } - return new ProgramEncounterRepository.SearchParams(CHSEntity.toDate(lastModifiedDateTime), CHSEntity.toDate(now), conceptsMap, encounterType, programEnrolment); + return new ProgramEncounterRepository.SearchParams(CHSEntity.toUtilDate(lastModifiedDateTime), CHSEntity.toUtilDate(now), conceptsMap, encounterType, programEnrolment); } @GetMapping(value = "/api/programEncounter/{id}") diff --git a/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEnrolmentApiController.java b/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEnrolmentApiController.java index 117236b25..281a6ad25 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEnrolmentApiController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/api/ProgramEnrolmentApiController.java @@ -1,5 +1,6 @@ package org.avni.server.web.api; +import jakarta.transaction.Transactional; import org.avni.server.dao.ConceptRepository; import org.avni.server.dao.IndividualRepository; import org.avni.server.dao.ProgramEnrolmentRepository; @@ -14,10 +15,10 @@ import org.avni.server.service.ProgramEnrolmentService; import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.util.S; +import org.avni.server.web.request.api.ApiProgramEnrolmentRequest; import org.avni.server.web.request.api.RequestUtils; import org.avni.server.web.response.ProgramEnrolmentResponse; import org.avni.server.web.response.ResponsePage; -import org.avni.server.web.request.api.ApiProgramEnrolmentRequest; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -29,7 +30,6 @@ import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.io.IOException; import java.util.ArrayList; diff --git a/avni-server-api/src/main/java/org/avni/server/web/external/RuleServiceClient.java b/avni-server-api/src/main/java/org/avni/server/web/external/RuleServiceClient.java index c6ddb61a0..cdaa7308b 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/external/RuleServiceClient.java +++ b/avni-server-api/src/main/java/org/avni/server/web/external/RuleServiceClient.java @@ -5,6 +5,7 @@ import org.avni.server.framework.security.UserContextHolder; 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.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -16,16 +17,21 @@ @Service public class RuleServiceClient { + private final RestTemplate restTemplate; @Value("${node.server.url}") private String NODE_SERVER_HOST; - private Logger logger = LoggerFactory.getLogger(RuleServiceClient.class); + private final Logger logger = LoggerFactory.getLogger(RuleServiceClient.class); - public String post(String api, T jsonObj) throws HttpClientErrorException { + @Autowired + public RuleServiceClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + public Object post(String api, Object jsonObj, Class responseType) throws HttpClientErrorException { String uri = NODE_SERVER_HOST.concat(api); - RestTemplate restTemplate = new RestTemplate(); HttpEntity entityCredentials = new HttpEntity<>(jsonObj, constructHeaders()); try { - return restTemplate.postForObject(uri, entityCredentials, String.class); + return restTemplate.postForObject(uri, entityCredentials, responseType); } catch (HttpClientErrorException e) { logger.info("rule " + api + " not found"); throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "rule " + api + " not found"); diff --git a/avni-server-api/src/main/java/org/avni/server/web/menu/MenuItemWebController.java b/avni-server-api/src/main/java/org/avni/server/web/menu/MenuItemWebController.java index 6e8a27ca6..d8204c9ad 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/menu/MenuItemWebController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/menu/MenuItemWebController.java @@ -1,23 +1,23 @@ package org.avni.server.web.menu; +import jakarta.transaction.Transactional; import org.avni.server.application.menu.MenuItem; import org.avni.server.dao.application.MenuItemRepository; import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.service.application.MenuItemService; -import org.avni.server.web.response.AvniEntityResponse; -import org.avni.server.web.response.MenuItemWebResponse; import org.avni.server.web.AbstractController; import org.avni.server.web.RestControllerResourceProcessor; import org.avni.server.web.request.application.menu.MenuItemContract; +import org.avni.server.web.response.AvniEntityResponse; +import org.avni.server.web.response.MenuItemWebResponse; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.hateoas.PagedResources; +import org.springframework.hateoas.CollectionModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors; @@ -66,7 +66,7 @@ public MenuItemContract getOne(@PathVariable("id") Long id) { @RequestMapping(value = "/web/menuItem", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources getAll() { + public CollectionModel getAll() { return wrapListAsPage(menuItemRepository.findAllByIsVoidedFalse().stream().map(MenuItemWebResponse::new).collect(Collectors.toList())); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/CatchmentContract.java b/avni-server-api/src/main/java/org/avni/server/web/request/CatchmentContract.java index ca6ae9949..d7f5f8381 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/CatchmentContract.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/CatchmentContract.java @@ -1,9 +1,9 @@ package org.avni.server.web.request; import org.avni.server.domain.Catchment; -import org.springframework.hateoas.core.Relation; - import org.joda.time.DateTime; +import org.springframework.hateoas.server.core.Relation; + import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/GroupContract.java b/avni-server-api/src/main/java/org/avni/server/web/request/GroupContract.java index a38c278db..f8d07f18f 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/GroupContract.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/GroupContract.java @@ -1,7 +1,7 @@ package org.avni.server.web.request; import org.avni.server.domain.Group; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; @Relation(collectionRelation = "group") public class GroupContract extends ReferenceDataContract { diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/UserContract.java b/avni-server-api/src/main/java/org/avni/server/web/request/UserContract.java index e9be80b13..1bbbe73bd 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/UserContract.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/UserContract.java @@ -1,8 +1,8 @@ package org.avni.server.web.request; import com.fasterxml.jackson.annotation.JsonInclude; -import org.avni.server.domain.OperatingIndividualScope; import org.avni.server.domain.JsonObject; +import org.avni.server.domain.OperatingIndividualScope; import org.avni.server.domain.User; import org.joda.time.DateTime; @@ -45,9 +45,9 @@ public static UserContract fromEntity(User user) { userContract.setCatchmentId(user.getCatchmentId().orElse(null)); userContract.setSettings(user.getSettings()); userContract.setCreatedBy(user.getCreatedByUserName()); - userContract.setCreatedDateTime(user.getCreatedDateTime()); + userContract.setCreatedDateTime(user.getCreatedDateTime().toDateTime()); userContract.setLastModifiedBy(user.getLastModifiedByUserName()); - userContract.setLastModifiedDateTime(user.getLastModifiedDateTime()); + userContract.setLastModifiedDateTime(user.getLastModifiedDateTime().toDateTime()); userContract.setGroupIds(user.getUserGroups().stream() .map(userGroup -> userGroup.getGroupId()).collect(Collectors.toList())); userContract.setUserGroupNames(user.getUserGroups().stream() diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoClientContract.java b/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoClientContract.java index fcd72349e..9be67819d 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoClientContract.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoClientContract.java @@ -1,7 +1,7 @@ package org.avni.server.web.request; import org.avni.server.domain.JsonObject; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoContract.java b/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoContract.java index bba0b0e02..1a38729f7 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoContract.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/UserInfoContract.java @@ -1,8 +1,8 @@ package org.avni.server.web.request; -import org.joda.time.DateTime; import org.avni.server.domain.JsonObject; -import org.springframework.hateoas.core.Relation; +import org.joda.time.DateTime; +import org.springframework.hateoas.server.core.Relation; @Relation(collectionRelation = "userInfo") public class UserInfoContract { diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/application/BasicFormDetails.java b/avni-server-api/src/main/java/org/avni/server/web/request/application/BasicFormDetails.java index f22c65d8c..0fbcea54b 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/application/BasicFormDetails.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/application/BasicFormDetails.java @@ -2,14 +2,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.joda.time.DateTime; import org.avni.server.application.Form; -import org.springframework.hateoas.ResourceSupport; +import org.joda.time.DateTime; +import org.springframework.hateoas.RepresentationModel; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "name", "uuid", "formType", "programName", "createdDateTime", "lastModifiedDate", "createdBy", "lastModifiedBy", "createdByUUID", "lastModifiedByUUID" }) -public class BasicFormDetails extends ResourceSupport { +public class BasicFormDetails extends RepresentationModel { private String name; private String uuid; diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/rules/validateRules/RuleValidationService.java b/avni-server-api/src/main/java/org/avni/server/web/request/rules/validateRules/RuleValidationService.java index b05c9a801..839e993e5 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/rules/validateRules/RuleValidationService.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/rules/validateRules/RuleValidationService.java @@ -1,6 +1,5 @@ package org.avni.server.web.request.rules.validateRules; -import org.apache.logging.log4j.util.Strings; import org.avni.server.dao.ConceptRepository; import org.avni.server.dao.individualRelationship.RuleFailureLogRepository; import org.avni.server.domain.Concept; @@ -70,7 +69,7 @@ private Boolean checkConceptForRule(String conceptName, RuleFailureLog ruleFailu Concept concept = conceptRepository.findByName(conceptName); if (concept == null) { ruleFailureLog.setErrorMessage(String.format("concept not found with the name %s", conceptName)); - ruleFailureLog.setStacktrace(Strings.EMPTY); + ruleFailureLog.setStacktrace(""); ruleFailureLog.setUuid(UUID.randomUUID().toString()); ruleFailureLogRepository.save(ruleFailureLog); return false; diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/EncounterTypeContractWeb.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/EncounterTypeContractWeb.java index adff9e939..e6cad1639 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/EncounterTypeContractWeb.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/EncounterTypeContractWeb.java @@ -2,8 +2,8 @@ import org.avni.server.domain.DeclarativeRule; import org.avni.server.domain.OperationalEncounterType; -import org.springframework.hateoas.core.Relation; import org.joda.time.DateTime; +import org.springframework.hateoas.server.core.Relation; /** diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierSourceContractWeb.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierSourceContractWeb.java index 72d9292fa..e3a142820 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierSourceContractWeb.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierSourceContractWeb.java @@ -2,8 +2,7 @@ import org.avni.server.domain.IdentifierSource; import org.avni.server.domain.JsonObject; -import org.avni.server.domain.identifier.IdentifierGeneratorType; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; @Relation(collectionRelation = "identifierSource") public class IdentifierSourceContractWeb { diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierUserAssignmentContractWeb.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierUserAssignmentContractWeb.java index 89542f804..09395eeaa 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierUserAssignmentContractWeb.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/IdentifierUserAssignmentContractWeb.java @@ -2,7 +2,7 @@ import org.avni.server.domain.IdentifierSource; import org.avni.server.domain.IdentifierUserAssignment; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; @Relation(collectionRelation = "identifierUserAssignment") public class IdentifierUserAssignmentContractWeb { diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/ProgramContractWeb.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/ProgramContractWeb.java index 31dd2191e..22c74ed4e 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/ProgramContractWeb.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/ProgramContractWeb.java @@ -3,7 +3,7 @@ import org.avni.server.domain.OperationalProgram; import org.avni.server.web.contract.ProgramContract; import org.joda.time.DateTime; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; /** diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/SubjectTypeContractWeb.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/SubjectTypeContractWeb.java index 1875693e3..172c1d8e0 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/SubjectTypeContractWeb.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/SubjectTypeContractWeb.java @@ -8,7 +8,7 @@ import org.avni.server.web.request.FormatContract; import org.avni.server.web.request.GroupRoleContract; import org.joda.time.DateTime; -import org.springframework.hateoas.core.Relation; +import org.springframework.hateoas.server.core.Relation; import java.util.List; diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/DateRange.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/DateRange.java index d40856c96..412b9fa76 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/DateRange.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/DateRange.java @@ -1,6 +1,8 @@ package org.avni.server.web.request.webapp.search; public class DateRange extends RangeFilter{ + public DateRange() { + } public DateRange(String minValue, String maxValue) { super(minValue, maxValue); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/IntegerRange.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/IntegerRange.java index fefb9e0ac..060112319 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/IntegerRange.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/IntegerRange.java @@ -1,6 +1,8 @@ package org.avni.server.web.request.webapp.search; public class IntegerRange extends RangeFilter{ + public IntegerRange() { + } public IntegerRange(Integer minValue, Integer maxValue) { super(minValue, maxValue); diff --git a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/RangeFilter.java b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/RangeFilter.java index 11d886e5c..6c15f091a 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/RangeFilter.java +++ b/avni-server-api/src/main/java/org/avni/server/web/request/webapp/search/RangeFilter.java @@ -4,6 +4,9 @@ public abstract class RangeFilter { private T minValue; private T maxValue; + public RangeFilter() { + } + public RangeFilter(T minValue, T maxValue) { this.minValue = minValue; this.maxValue = maxValue; diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistItemResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistItemResourceProcessor.java index 1242643e2..f0e0f41a7 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistItemResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistItemResourceProcessor.java @@ -1,16 +1,16 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.ChecklistItem; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class ChecklistItemResourceProcessor extends ResourceProcessor{ @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ChecklistItem checklistItem = resource.getContent(); resource.removeLinks(); - resource.add(new Link(checklistItem.getChecklist().getUuid(), "checklistUUID")); - resource.add(new Link(checklistItem.getChecklistItemDetail().getUuid(), "checklistItemDetailUUID")); + resource.add(Link.of(checklistItem.getChecklist().getUuid(), "checklistUUID")); + resource.add(Link.of(checklistItem.getChecklistItemDetail().getUuid(), "checklistItemDetailUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistResourceProcessor.java index de85b581f..1d5706f73 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ChecklistResourceProcessor.java @@ -1,16 +1,16 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.Checklist; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class ChecklistResourceProcessor extends ResourceProcessor { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Checklist checklist = resource.getContent(); resource.removeLinks(); - resource.add(new Link(checklist.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); - resource.add(new Link(checklist.getChecklistDetail().getUuid(), "checklistDetailUUID")); + resource.add(Link.of(checklist.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); + resource.add(Link.of(checklist.getChecklistDetail().getUuid(), "checklistDetailUUID")); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/EncounterResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/EncounterResourceProcessor.java index 6a8783d27..7c85bdde0 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/EncounterResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/EncounterResourceProcessor.java @@ -1,16 +1,16 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.Encounter; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class EncounterResourceProcessor extends ResourceProcessor{ @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Encounter encounter = resource.getContent(); resource.removeLinks(); - resource.add(new Link(encounter.getEncounterType().getUuid(), "encounterTypeUUID")); - resource.add(new Link(encounter.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(encounter.getEncounterType().getUuid(), "encounterTypeUUID")); + resource.add(Link.of(encounter.getIndividual().getUuid(), "individualUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/GroupSubjectResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/GroupSubjectResourceProcessor.java index f0480c33c..490600f73 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/GroupSubjectResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/GroupSubjectResourceProcessor.java @@ -1,16 +1,16 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.GroupSubject; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class GroupSubjectResourceProcessor extends ResourceProcessor{ @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { GroupSubject groupSubject = resource.getContent(); resource.removeLinks(); - resource.add(new Link(groupSubject.getGroupSubject().getUuid(), "groupSubjectUUID")); - resource.add(new Link(groupSubject.getMemberSubject().getUuid(), "memberSubjectUUID")); - resource.add(new Link(groupSubject.getGroupRole().getUuid(), "groupRoleUUID")); + resource.add(Link.of(groupSubject.getGroupSubject().getUuid(), "groupSubjectUUID")); + resource.add(Link.of(groupSubject.getMemberSubject().getUuid(), "memberSubjectUUID")); + resource.add(Link.of(groupSubject.getGroupRole().getUuid(), "groupRoleUUID")); return resource; }} diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualRelationshipResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualRelationshipResourceProcessor.java index c3ef2a7a2..de2d0ab07 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualRelationshipResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualRelationshipResourceProcessor.java @@ -1,17 +1,17 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.individualRelationship.IndividualRelationship; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class IndividualRelationshipResourceProcessor extends ResourceProcessor{ @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { IndividualRelationship individualRelationship = resource.getContent(); resource.removeLinks(); - resource.add(new Link(individualRelationship.getRelationship().getUuid(), "relationshipTypeUUID")); - resource.add(new Link(individualRelationship.getIndividuala().getUuid(), "individualAUUID")); - resource.add(new Link(individualRelationship.getIndividualB().getUuid(), "individualBUUID")); + resource.add(Link.of(individualRelationship.getRelationship().getUuid(), "relationshipTypeUUID")); + resource.add(Link.of(individualRelationship.getIndividuala().getUuid(), "individualAUUID")); + resource.add(Link.of(individualRelationship.getIndividualB().getUuid(), "individualBUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualResourceProcessor.java index 432b20da4..e3fb6a8cf 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/IndividualResourceProcessor.java @@ -1,21 +1,21 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.Individual; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class IndividualResourceProcessor extends ResourceProcessor { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Individual individual = resource.getContent(); resource.removeLinks(); if (individual.getAddressLevel() != null) { - resource.add(new Link(individual.getAddressLevel().getUuid(), "addressUUID")); + resource.add(Link.of(individual.getAddressLevel().getUuid(), "addressUUID")); } if (individual.getGender() != null) { - resource.add(new Link(individual.getGender().getUuid(), "genderUUID")); + resource.add(Link.of(individual.getGender().getUuid(), "genderUUID")); } - resource.add(new Link(individual.getSubjectType().getUuid(), "subjectTypeUUID")); + resource.add(Link.of(individual.getSubjectType().getUuid(), "subjectTypeUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEncounterResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEncounterResourceProcessor.java index 81d60c11a..619f97068 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEncounterResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEncounterResourceProcessor.java @@ -2,15 +2,15 @@ import org.avni.server.domain.ProgramEncounter; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.EntityModel; public class ProgramEncounterResourceProcessor extends ResourceProcessor { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ProgramEncounter programEncounter = resource.getContent(); resource.removeLinks(); - resource.add(new Link(programEncounter.getEncounterType().getUuid(), "encounterTypeUUID")); - resource.add(new Link(programEncounter.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); + resource.add(Link.of(programEncounter.getEncounterType().getUuid(), "encounterTypeUUID")); + resource.add(Link.of(programEncounter.getProgramEnrolment().getUuid(), "programEnrolmentUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEnrolmentResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEnrolmentResourceProcessor.java index 3ab49687c..88d4e3287 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEnrolmentResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ProgramEnrolmentResourceProcessor.java @@ -1,16 +1,16 @@ package org.avni.server.web.resourceProcessors; import org.avni.server.domain.ProgramEnrolment; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public class ProgramEnrolmentResourceProcessor extends ResourceProcessor { @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { ProgramEnrolment programEnrolment = resource.getContent(); resource.removeLinks(); - resource.add(new Link(programEnrolment.getProgram().getUuid(), "programUUID")); - resource.add(new Link(programEnrolment.getIndividual().getUuid(), "individualUUID")); + resource.add(Link.of(programEnrolment.getProgram().getUuid(), "programUUID")); + resource.add(Link.of(programEnrolment.getIndividual().getUuid(), "individualUUID")); return resource; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ResourceProcessor.java b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ResourceProcessor.java index 64e39a693..0dfec5df5 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ResourceProcessor.java +++ b/avni-server-api/src/main/java/org/avni/server/web/resourceProcessors/ResourceProcessor.java @@ -2,25 +2,25 @@ import org.avni.server.domain.CHSEntity; import org.avni.server.domain.User; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.Resource; public abstract class ResourceProcessor { /** * Individual controllers handle their own resource processing. This is only for backward compatibility. Hence its implementers may not implement resource processing for all the fields */ @Deprecated - public abstract Resource process(Resource resource); + public abstract EntityModel process(EntityModel resource); - public static void addAuditFields(CHSEntity chsEntity, Resource resource) { + public static void addAuditFields(CHSEntity chsEntity, EntityModel resource) { addUserFields(chsEntity.getCreatedBy(), resource, "createdBy"); addUserFields(chsEntity.getLastModifiedBy(), resource, "lastModifiedBy"); } - public static void addUserFields(User user, Resource resource, String fieldName) { + public static void addUserFields(User user, EntityModel resource, String fieldName) { if (user == null) return; - resource.add(new Link(user.getUuid(), fieldName + "UUID")); - resource.add(new Link(user.getName(), fieldName)); + resource.add(Link.of(user.getUuid(), fieldName + "UUID")); + resource.add(Link.of(user.getName(), fieldName)); } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/response/SubjectResponse.java b/avni-server-api/src/main/java/org/avni/server/web/response/SubjectResponse.java index a8699a1cc..1d7d9f07f 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/response/SubjectResponse.java +++ b/avni-server-api/src/main/java/org/avni/server/web/response/SubjectResponse.java @@ -8,11 +8,12 @@ import org.avni.server.service.ConceptService; import org.avni.server.service.S3Service; import org.avni.server.web.request.api.SubjectResponseOptions; -import org.jadira.usertype.spi.utils.lang.StringUtils; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; import java.net.URL; import java.util.*; +import java.util.stream.Collectors; import static org.avni.server.web.api.CommonFieldNames.EXTERNAL_ID; @@ -38,7 +39,7 @@ public static SubjectResponse fromSubject(Individual subject, SubjectResponseOpt Response.putIfPresent(observations, "Middle name", subject.getMiddleName()); Response.putIfPresent(observations, "Last name", subject.getLastName()); if (subject.getSubjectType().isAllowProfilePicture() - && StringUtils.isNotEmpty(subject.getProfilePicture())) { + && !StringUtils.isEmpty(subject.getProfilePicture())) { URL url = s3Service.generateMediaDownloadUrl(subject.getProfilePicture()); observations.put("Profile picture", url.toString()); } @@ -97,7 +98,7 @@ private static void putAddressLevel(Map map, AddressLevel addres public static SubjectResponse fromSubject(Individual subject, SubjectResponseOptions options, ConceptRepository conceptRepository, ConceptService conceptService, List groups, S3Service s3Service) { SubjectResponse subjectResponse = fromSubject(subject, options, conceptRepository, conceptService, s3Service); - subjectResponse.put("Groups", groups.stream().map(GroupSubject::getGroupSubjectUUID)); + subjectResponse.put("Groups", groups.stream().map(GroupSubject::getGroupSubjectUUID).collect(Collectors.toList())); return subjectResponse; } } diff --git a/avni-server-api/src/main/java/org/avni/server/web/response/UserInfoWebResponse.java b/avni-server-api/src/main/java/org/avni/server/web/response/UserInfoWebResponse.java index 8a65d3aeb..3fdafa28a 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/response/UserInfoWebResponse.java +++ b/avni-server-api/src/main/java/org/avni/server/web/response/UserInfoWebResponse.java @@ -26,7 +26,7 @@ public static UserInfoWebResponse createForAdminUser(List extends Resources { +public class SlicedResources extends CollectionModel { public static SlicedResources NO_PAGE = new SlicedResources(); @@ -51,7 +50,7 @@ public SlicedResources(Collection content, SlicedResources.SliceMetadata meta * @param links */ public SlicedResources(Collection content, SlicedResources.SliceMetadata metadata, Iterable links) { - super(content, links); + super(content, links, ResolvableType.NONE); this.metadata = metadata; } @@ -73,13 +72,13 @@ public SlicedResources.SliceMetadata getMetadata() { * @return */ @SuppressWarnings("unchecked") - public static , S> SlicedResources wrap(Iterable content, SlicedResources.SliceMetadata metadata) { + public static , S> SlicedResources wrap(Iterable content, SlicedResources.SliceMetadata metadata) { Assert.notNull(content, "Content must not be null!"); ArrayList resources = new ArrayList(); for (S element : content) { - resources.add((T) new Resource(element)); + resources.add((T) EntityModel.of(element)); } return new SlicedResources(resources, metadata); @@ -92,7 +91,7 @@ public static , S> SlicedResources wrap(Iterable con */ @JsonIgnore public Link getNextLink() { - return getLink(Link.REL_NEXT); + return Link.of("foo"); } /** @@ -102,7 +101,7 @@ public Link getNextLink() { */ @JsonIgnore public Link getPreviousLink() { - return getLink(Link.REL_PREVIOUS); + return Link.of("foo"); } /* @@ -164,12 +163,6 @@ public static class SliceMetadata { protected SliceMetadata() {} - /** - * Creates a new {@link SlicedModel.SliceMetadata} from the given size, and slice number. - * - * @param size must be greater or equal to zero. - * @param number zero-indexed slice number, greater or equal to zero. - */ public SliceMetadata(long size, long number) { Assert.isTrue(size > -1, "Size must not be negative!"); diff --git a/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryController.java b/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryController.java index c3a0d2916..10f1e5e96 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryController.java @@ -1,5 +1,6 @@ package org.avni.server.web.rules; +import jakarta.transaction.Transactional; import org.avni.server.dao.RuleFailureTelemetryRepository; import org.avni.server.domain.Organisation; import org.avni.server.domain.RuleFailureTelemetry; @@ -9,16 +10,14 @@ import org.avni.server.web.request.RuleFailureTelemetryRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - @RestController public class RuleFailureTelemetryController implements RestControllerResourceProcessor { private final RuleFailureTelemetryRepository ruleFailureTelemetryRepository; @@ -30,7 +29,7 @@ public RuleFailureTelemetryController(RuleFailureTelemetryRepository ruleFailure @RequestMapping(value = "ruleFailureTelemetry", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") - public PagedResources> getEmpty(Pageable pageable) { + public CollectionModel> getEmpty(Pageable pageable) { return empty(pageable); } diff --git a/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryWebController.java b/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryWebController.java index be6be4e3a..7b4a98338 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryWebController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/rules/RuleFailureTelemetryWebController.java @@ -1,5 +1,6 @@ package org.avni.server.web.rules; +import jakarta.transaction.Transactional; import org.avni.server.dao.RuleFailureTelemetryRepository; import org.avni.server.domain.RuleFailureTelemetry; import org.avni.server.domain.accessControl.PrivilegeType; @@ -9,8 +10,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; @@ -18,7 +19,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; import java.util.List; @RestController @@ -33,7 +33,7 @@ public RuleFailureTelemetryWebController(RuleFailureTelemetryRepository ruleFail } @RequestMapping(value = "/web/ruleFailureTelemetry", method = RequestMethod.GET) - public PagedResources> getByStatus(@RequestParam(value = "isClosed", required = false) Boolean isClosed, + public CollectionModel> getByStatus(@RequestParam(value = "isClosed", required = false) Boolean isClosed, Pageable pageable) { Page ruleFailureTelemetries = isClosed != null ? ruleFailureTelemetryRepository.findByIsClosed(isClosed, pageable) diff --git a/avni-server-api/src/main/java/org/avni/server/web/task/TaskController.java b/avni-server-api/src/main/java/org/avni/server/web/task/TaskController.java index 5190ef2b8..9a03b5fd1 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/task/TaskController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/task/TaskController.java @@ -1,5 +1,6 @@ package org.avni.server.web.task; +import jakarta.transaction.Transactional; import org.avni.server.dao.task.TaskRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.User; @@ -8,24 +9,22 @@ import org.avni.server.framework.security.UserContextHolder; import org.avni.server.service.TaskService; import org.avni.server.service.accessControl.AccessControlService; -import org.avni.server.web.response.AvniEntityResponse; import org.avni.server.web.AbstractController; import org.avni.server.web.RestControllerResourceProcessor; import org.avni.server.web.request.TaskRequest; +import org.avni.server.web.response.AvniEntityResponse; import org.avni.server.web.response.slice.SlicedResources; import org.joda.time.DateTime; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; - import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @RestController @@ -46,7 +45,7 @@ public TaskController(TaskRepository taskRepository, TaskService taskService, Ac @RequestMapping(value = "/task", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public PagedResources> getTasks( + public CollectionModel> getTasks( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -57,7 +56,7 @@ public PagedResources> getTasks( @RequestMapping(value = "/task/v2", method = RequestMethod.GET) @PreAuthorize(value = "hasAnyAuthority('user')") @Transactional - public SlicedResources> getTasksAsSlice( + public SlicedResources> getTasksAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -75,13 +74,13 @@ public AvniEntityResponse save(@RequestBody TaskRequest taskRequest) { } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { Task task = resource.getContent(); resource.removeLinks(); - resource.add(new Link(task.getTaskType().getUuid(), "taskTypeUUID")); - resource.add(new Link(task.getTaskStatus().getUuid(), "taskStatusUUID")); + resource.add(Link.of(task.getTaskType().getUuid(), "taskTypeUUID")); + resource.add(Link.of(task.getTaskStatus().getUuid(), "taskStatusUUID")); if (task.getSubject() != null) { - resource.add(new Link(task.getSubject().getUuid(), "subjectUUID")); + resource.add(Link.of(task.getSubject().getUuid(), "subjectUUID")); } addAuditFields(task, resource); return resource; diff --git a/avni-server-api/src/main/java/org/avni/server/web/task/TaskUnAssignmentController.java b/avni-server-api/src/main/java/org/avni/server/web/task/TaskUnAssignmentController.java index 9caa16c92..6fee7896c 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/task/TaskUnAssignmentController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/task/TaskUnAssignmentController.java @@ -1,12 +1,11 @@ package org.avni.server.web.task; +import jakarta.transaction.Transactional; import org.avni.server.dao.task.TaskUnAssignmentRepository; import org.avni.server.domain.CHSEntity; import org.avni.server.domain.User; -import org.avni.server.domain.accessControl.PrivilegeType; import org.avni.server.domain.task.TaskUnAssignment; import org.avni.server.framework.security.UserContextHolder; -import org.avni.server.service.accessControl.AccessControlService; import org.avni.server.web.AbstractController; import org.avni.server.web.RestControllerResourceProcessor; import org.avni.server.web.response.slice.SlicedResources; @@ -14,17 +13,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.transaction.Transactional; - import static org.avni.server.web.resourceProcessors.ResourceProcessor.addAuditFields; @RestController @@ -38,7 +34,7 @@ public TaskUnAssignmentController(TaskUnAssignmentRepository taskUnAssignmentRep @RequestMapping(value = "/taskUnAssignments", method = RequestMethod.GET) @Transactional - public PagedResources> getTasks( + public CollectionModel> getTasks( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -48,7 +44,7 @@ public PagedResources> getTasks( @RequestMapping(value = "/taskUnAssignments/v2", method = RequestMethod.GET) @Transactional - public SlicedResources> getTasksAsSlice( + public SlicedResources> getTasksAsSlice( @RequestParam("lastModifiedDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime lastModifiedDateTime, @RequestParam("now") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) DateTime now, Pageable pageable) { @@ -57,9 +53,9 @@ public SlicedResources> getTasksAsSlice( } @Override - public Resource process(Resource resource) { + public EntityModel process(EntityModel resource) { TaskUnAssignment taskUnAssignment = resource.getContent(); - resource.add(new Link(taskUnAssignment.getTask().getUuid(), "taskUUID")); + resource.add(Link.of(taskUnAssignment.getTask().getUuid(), "taskUUID")); addAuditFields(taskUnAssignment, resource); return resource; } diff --git a/avni-server-api/src/main/java/org/avni/server/web/task/TaskWebController.java b/avni-server-api/src/main/java/org/avni/server/web/task/TaskWebController.java index 6891d8103..fbcc789b9 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/task/TaskWebController.java +++ b/avni-server-api/src/main/java/org/avni/server/web/task/TaskWebController.java @@ -1,5 +1,6 @@ package org.avni.server.web.task; +import jakarta.transaction.Transactional; import org.avni.server.dao.ConceptRepository; import org.avni.server.domain.JsonObject; import org.avni.server.domain.accessControl.PrivilegeType; @@ -7,17 +8,15 @@ import org.avni.server.service.ConceptService; import org.avni.server.service.TaskService; import org.avni.server.service.accessControl.AccessControlService; -import org.avni.server.web.response.Response; -import org.avni.server.web.response.TaskSearchResponse; import org.avni.server.web.request.task.TaskAssignmentRequest; import org.avni.server.web.request.task.TaskFilterCriteria; +import org.avni.server.web.response.Response; +import org.avni.server.web.response.TaskSearchResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.transaction.Transactional; import java.util.HashMap; import java.util.Map; diff --git a/avni-server-api/src/main/java/org/avni/server/web/util/Configuration.java b/avni-server-api/src/main/java/org/avni/server/web/util/Configuration.java index 4c80e951f..54675adc6 100644 --- a/avni-server-api/src/main/java/org/avni/server/web/util/Configuration.java +++ b/avni-server-api/src/main/java/org/avni/server/web/util/Configuration.java @@ -1,7 +1,14 @@ package org.avni.server.web.util; +import org.avni.server.util.ObjectMapperSingleton; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; import java.util.List; @Component @@ -16,4 +23,15 @@ public List getReportingSystems() { public void setReportingSystems(List reportingSystems) { this.reportingSystems = reportingSystems; } -} \ No newline at end of file + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + List> messageConverters = new ArrayList<>(); + MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); + jsonMessageConverter.setObjectMapper(ObjectMapperSingleton.getObjectMapper()); + messageConverters.add(jsonMessageConverter); + restTemplate.setMessageConverters(messageConverters); + return restTemplate; + } +} diff --git a/avni-server-api/src/main/resources/application.properties b/avni-server-api/src/main/resources/application.properties index eafa6ce6d..9fddb7c34 100644 --- a/avni-server-api/src/main/resources/application.properties +++ b/avni-server-api/src/main/resources/application.properties @@ -23,27 +23,30 @@ spring.flyway.enabled=${FLYWAY_ENABLED:true} spring.flyway.schemas=public spring.flyway.baseline-on-migrate=false spring.flyway.out-of-order=true +spring.flyway.ignore-migration-patterns=repeatable:missing +spring.flyway.table=schema_version # JPA, Hibernate and Spring Data spring.jpa.show-sql=${SHOW_SQL:false} spring.jpa.hibernate.ddl-auto=none -spring.jpa.properties.jadira.usertype.databaseZone=jvm -spring.jpa.properties.jadira.usertype.javaZone=jvm -spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true -spring.jpa.properties.hibernate.dialect=org.avni.server.framework.postgres.CHSPostgreSQL94Dialect -spring.jpa.properties.hibernate.ejb.interceptor=org.avni.server.framework.hibernate.UpdateOrganisationHibernateInterceptor -spring.jpa.database-platform=org.avni.server.framework.postgres.CHSPostgreSQL94Dialect -spring.jpa.hibernate.use-new-id-generator-mappings=true +#spring.jpa.properties.jadira.usertype.databaseZone=jvm +#spring.jpa.properties.jadira.usertype.javaZone=jvm +#spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.properties.hibernate.session_factory.interceptor=org.avni.server.framework.hibernate.UpdateOrganisationHibernateInterceptor +#spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL10Dialect spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false avni.custom.query.timeout=${AVNI_CUSTOM_QUERY_TIMEOUT:3} avni.custom.query.max.rows=${AVNI_CUSTOM_QUERY_MAX_ROWS:2000} avni.longitudinal.export.v2.limit=${AVNI_LONGITUDINAL_EXPORT_V2_LIMIT:10000} avni.legacy.longitudinal.export.limit=${AVNI_LEGACY_LONGITUDINAL_EXPORT_LIMIT:10000} +spring.main.allow-bean-definition-overriding=true + # Second level and Query cache. Also check ehcache.xml file. spring.jpa.properties.hibernate.cache.use_second_level_cache=true spring.jpa.properties.hibernate.cache.use_query_cache=true -spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory +spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory # Hibernate Search spring.jpa.properties.hibernate.search.default.directory_provider=local-heap @@ -167,5 +170,8 @@ metabase.api.key=${METABASE_API_KEY:mb_uhFRMqCSre4v/hTZTsQcMnh8k2GCZFX2tGmSBdoxN # end of life avni.endpoints.endOfLife.1=${AVNI_ENDPOINT_END_OF_LIFE_1:2024-09-05} +spring.mvc.pathmatch.matching-strategy=ant_path_matcher +server.servlet.register-default-servlet=true + #default org configuration avni.default.org.user.db.password=${AVNI_DEFAULT_ORG_USER_DB_PASSWORD:password} \ No newline at end of file diff --git a/avni-server-api/src/main/resources/db/migration/V1_347__IdentifierAssignmentDeviceId.sql b/avni-server-api/src/main/resources/db/migration/V1_347_1__IdentifierAssignmentDeviceId.sql similarity index 100% rename from avni-server-api/src/main/resources/db/migration/V1_347__IdentifierAssignmentDeviceId.sql rename to avni-server-api/src/main/resources/db/migration/V1_347_1__IdentifierAssignmentDeviceId.sql diff --git a/avni-server-api/src/main/resources/db/migration/V1_347__SpringBatchSchemaUpgradeTo5.sql b/avni-server-api/src/main/resources/db/migration/V1_347__SpringBatchSchemaUpgradeTo5.sql new file mode 100644 index 000000000..597559a5d --- /dev/null +++ b/avni-server-api/src/main/resources/db/migration/V1_347__SpringBatchSchemaUpgradeTo5.sql @@ -0,0 +1,21 @@ +ALTER TABLE if exists BATCH_STEP_EXECUTION ADD CREATE_TIME TIMESTAMP NOT NULL DEFAULT '1970-01-01 00:00:00'; + +ALTER TABLE if exists BATCH_STEP_EXECUTION ALTER COLUMN START_TIME DROP NOT NULL; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS DROP COLUMN DATE_VAL; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS DROP COLUMN LONG_VAL; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS DROP COLUMN DOUBLE_VAL; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS ALTER COLUMN TYPE_CD TYPE VARCHAR(100); + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS RENAME TYPE_CD TO PARAMETER_TYPE; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS ALTER COLUMN KEY_NAME TYPE VARCHAR(100); + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS RENAME KEY_NAME TO PARAMETER_NAME; + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS ALTER COLUMN STRING_VAL TYPE VARCHAR(2500); + +ALTER TABLE if exists BATCH_JOB_EXECUTION_PARAMS RENAME STRING_VAL TO PARAMETER_VALUE; diff --git a/avni-server-api/src/main/resources/log4j.properties b/avni-server-api/src/main/resources/log4j.properties deleted file mode 100644 index 065753297..000000000 --- a/avni-server-api/src/main/resources/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=ERROR, A1 - -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=[%c{2}] %-5p - %m%n diff --git a/avni-server-api/src/test/java/org/avni/messaging/repository/GlificRestClientTest.java b/avni-server-api/src/test/java/org/avni/messaging/repository/GlificRestClientTest.java index 26920440a..2f545b104 100644 --- a/avni-server-api/src/test/java/org/avni/messaging/repository/GlificRestClientTest.java +++ b/avni-server-api/src/test/java/org/avni/messaging/repository/GlificRestClientTest.java @@ -2,6 +2,7 @@ import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; +import jakarta.transaction.Transactional; import org.avni.messaging.contract.glific.GlificAuth; import org.avni.messaging.contract.glific.GlificMessageTemplateResponse; import org.avni.messaging.contract.glific.GlificResponse; @@ -23,7 +24,10 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.assertj.core.api.Assertions.assertThat; +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = {"/test-data.sql"}) +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class GlificRestClientTest extends AbstractControllerIntegrationTest { private String SAMPLE_AUTH_RESPONSE = "{\"data\":{\"access_token\":\"SFMyNTY.YjQ2M2MzMmMtNGZlOC00OTEyLWIzYTEtZmRhZTRkOGQ1ZTIx.3TjKqpElrD5N2ffGHEAFX91cyp7zwoTztYR8p1jwwgA\",\"renewal_token\":\"SFMyNTY.MjYxODllMTgtNDM1OC00YjJjLTlmN2MtOTA5MzMwYzM3ZjA2.dDigSwftcGFGHu4o9MwkASp2KqH6eitp1aRmeYSgi5M\",\"token_expiry_time\":\"2022-10-13T21:42:33.342529Z\"}}"; diff --git a/avni-server-api/src/test/java/org/avni/messaging/repository/MessageRequestQueueRepositoryTest.java b/avni-server-api/src/test/java/org/avni/messaging/repository/MessageRequestQueueRepositoryTest.java index 60fe3e413..857f71bcc 100644 --- a/avni-server-api/src/test/java/org/avni/messaging/repository/MessageRequestQueueRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/messaging/repository/MessageRequestQueueRepositoryTest.java @@ -12,6 +12,8 @@ import static org.assertj.core.api.Assertions.assertThat; +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) @Sql(scripts = {"/test-data.sql"}) public class MessageRequestQueueRepositoryTest extends AbstractControllerIntegrationTest { diff --git a/avni-server-api/src/test/java/org/avni/server/common/AbstractControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/common/AbstractControllerIntegrationTest.java index 808c7d3ba..69c78d768 100644 --- a/avni-server-api/src/test/java/org/avni/server/common/AbstractControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/common/AbstractControllerIntegrationTest.java @@ -1,10 +1,13 @@ package org.avni.server.common; import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.avni.server.dao.OrganisationRepository; import org.avni.server.dao.UserRepository; import org.avni.server.domain.User; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.ObjectMapperSingleton; import org.avni.server.web.TestWebContextService; import org.junit.After; import org.junit.Before; @@ -12,15 +15,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; import java.net.URL; import java.util.ArrayList; @@ -50,7 +51,7 @@ public abstract class AbstractControllerIntegrationTest { @Autowired private TestWebContextService testWebContextService; - protected static ObjectMapper mapper = new ObjectMapper(); + protected static ObjectMapper mapper = ObjectMapperSingleton.getObjectMapper(); @PersistenceContext private EntityManager em; @@ -67,10 +68,14 @@ public void setUp() throws Exception { @After public void teardown() { - UserContextHolder.clear(); template.getRestTemplate().setInterceptors(new ArrayList<>()); testWebContextService.setRoles(); em.getEntityManagerFactory().getCache().evictAll(); + try { + em.createNativeQuery("reset role;").executeUpdate(); + } catch (Exception ignored) { + } + UserContextHolder.clear(); } protected void post(String path, Object json) { diff --git a/avni-server-api/src/test/java/org/avni/server/dao/EntityApprovalStatusRepositoryIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/dao/EntityApprovalStatusRepositoryIntegrationTest.java index a2fff4678..899aeb962 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/EntityApprovalStatusRepositoryIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/EntityApprovalStatusRepositoryIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.application.Subject; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.ApprovalStatus; @@ -19,10 +20,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class EntityApprovalStatusRepositoryIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestDataSetupService testDataSetupService; diff --git a/avni-server-api/src/test/java/org/avni/server/dao/LocationRepositoryIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/dao/LocationRepositoryIntegrationTest.java index c9a854317..04090ad24 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/LocationRepositoryIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/LocationRepositoryIntegrationTest.java @@ -1,8 +1,8 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.AddressLevel; -import org.avni.server.domain.factory.AddressLevelTypeBuilder; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; @@ -13,6 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; @Sql({"/test-data.sql"}) +@Transactional public class LocationRepositoryIntegrationTest extends AbstractControllerIntegrationTest { @Autowired diff --git a/avni-server-api/src/test/java/org/avni/server/dao/OrganisationRepositoryIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/dao/OrganisationRepositoryIntegrationTest.java index 4290da7c7..372f71115 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/OrganisationRepositoryIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/OrganisationRepositoryIntegrationTest.java @@ -1,10 +1,12 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.ImplementationRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +@Transactional public class OrganisationRepositoryIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private ImplementationRepository implementationRepository; diff --git a/avni-server-api/src/test/java/org/avni/server/dao/ProgramEnrolmentRepositoryIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/dao/ProgramEnrolmentRepositoryIntegrationTest.java index be59a2a46..cd6c00a93 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/ProgramEnrolmentRepositoryIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/ProgramEnrolmentRepositoryIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.*; import org.avni.server.domain.factory.UserBuilder; @@ -36,6 +37,7 @@ public class ProgramEnrolmentRepositoryIntegrationTest extends AbstractControlle private ProgramEnrolmentRepository programEnrolmentRepository; @Test + @Transactional public void updateSyncAttributesForIndividual_should_update_last_modified_datetime() throws Exception { TestDataSetupService.TestOrganisationData organisationData = testDataSetupService.setupOrganisation(); TestDataSetupService.TestCatchmentData catchmentData = testDataSetupService.setupACatchment(); diff --git a/avni-server-api/src/test/java/org/avni/server/dao/QueryRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/dao/QueryRepositoryTest.java index 770b36370..a019ea118 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/QueryRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/QueryRepositoryTest.java @@ -19,7 +19,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - public class QueryRepositoryTest extends AbstractControllerIntegrationTest { @Autowired diff --git a/avni-server-api/src/test/java/org/avni/server/dao/SubjectMigrationIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/dao/SubjectMigrationIntegrationTest.java index 6170d46c9..f1e6a4598 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/SubjectMigrationIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/SubjectMigrationIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.sync.SyncEntityName; import org.avni.server.domain.*; @@ -20,8 +21,8 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.test.context.jdbc.Sql; @@ -32,6 +33,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class SubjectMigrationIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestDataSetupService testDataSetupService; @@ -60,8 +62,8 @@ public class SubjectMigrationIntegrationTest extends AbstractControllerIntegrati private TestDataSetupService.TestOrganisationData organisationData; private List getMigrations(SubjectType subjectType, DateTime lastModifiedDateTime, DateTime now) { - PagedResources> migrations = subjectMigrationController.getMigrationsByCatchmentAndLastModified(lastModifiedDateTime, now, subjectType.getUuid(), PageRequest.of(0, 10)); - return migrations.getContent().stream().map(Resource::getContent).collect(Collectors.toList()); + CollectionModel> migrations = subjectMigrationController.getMigrationsByCatchmentAndLastModified(lastModifiedDateTime, now, subjectType.getUuid(), PageRequest.of(0, 10)); + return migrations.getContent().stream().map(EntityModel::getContent).collect(Collectors.toList()); } private boolean hasMigrationFor(SubjectType subjectType, DateTime lastModifiedDateTime, DateTime now, Individual subject) { diff --git a/avni-server-api/src/test/java/org/avni/server/dao/UserRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/dao/UserRepositoryTest.java index 3bfaca558..f483eb1f8 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/UserRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/UserRepositoryTest.java @@ -1,16 +1,23 @@ package org.avni.server.dao; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; +import org.avni.server.domain.User; import org.avni.server.domain.accessControl.PrivilegeType; +import org.avni.server.domain.factory.UserBuilder; import org.avni.server.framework.security.UserContextHolder; +import org.joda.time.DateTime; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; +import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql({"/test-data.sql"}) +@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public class UserRepositoryTest extends AbstractControllerIntegrationTest { @Autowired private UserRepository userRepository; @@ -32,4 +39,17 @@ public void hasNoSubjectPrivilege() { setUser("user-no-access"); assertFalse(userRepository.hasSubjectPrivilege(PrivilegeType.ViewSubject.name(), 1, UserContextHolder.getUser().getId())); } + + @Test + @Transactional + public void loadingAndSavingUserShouldNotChangeModifiedAudit() throws InterruptedException { + User defaultSuperAdmin = userRepository.getDefaultSuperAdmin(); + User user1 = new UserBuilder().withDefaultValuesForNewEntity().userName("user@example").withAuditUser(defaultSuperAdmin).build(); + user1 = userRepository.save(user1); + DateTime lastModifiedDateTime = user1.getLastModifiedDateTime(); + Thread.sleep(1); + userRepository.save(user1); + User loaded = userRepository.findOne(user1.getId()); + assertEquals(lastModifiedDateTime, loaded.getLastModifiedDateTime()); + } } diff --git a/avni-server-api/src/test/java/org/avni/server/dao/accessControl/PrivilegeRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/dao/accessControl/PrivilegeRepositoryTest.java index 046d465cf..8ecda4f3f 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/accessControl/PrivilegeRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/accessControl/PrivilegeRepositoryTest.java @@ -1,5 +1,6 @@ package org.avni.server.dao.accessControl; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.PrivilegeRepository; import org.avni.server.domain.accessControl.Privilege; @@ -17,6 +18,7 @@ @Sql(scripts = {"/test-data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class PrivilegeRepositoryTest extends AbstractControllerIntegrationTest { @Autowired private PrivilegeRepository privilegeRepository; diff --git a/avni-server-api/src/test/java/org/avni/server/dao/application/FormElementRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/dao/application/FormElementRepositoryTest.java index fce42cea0..0046f3b0d 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/application/FormElementRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/application/FormElementRepositoryTest.java @@ -1,5 +1,6 @@ package org.avni.server.dao.application; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.application.FormElementRepository; import org.joda.time.DateTime; @@ -19,6 +20,7 @@ @Sql(scripts = {"/test-data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class FormElementRepositoryTest extends AbstractControllerIntegrationTest { @Autowired private FormElementRepository formElementRepository; @@ -29,7 +31,7 @@ public class FormElementRepositoryTest extends AbstractControllerIntegrationTest @Before public void setUp() throws Exception { super.setUp(); - pageRequest = new PageRequest(0, 100); + pageRequest = PageRequest.of(0, 100); setUser("demo-admin"); } diff --git a/avni-server-api/src/test/java/org/avni/server/dao/application/FormMappingRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/dao/application/FormMappingRepositoryTest.java index a79da4c5a..24378ab6a 100644 --- a/avni-server-api/src/test/java/org/avni/server/dao/application/FormMappingRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/dao/application/FormMappingRepositoryTest.java @@ -44,7 +44,7 @@ private void tryFailedFormMappingSave(FormMapping formMapping) { formMappingRepository.saveFormMapping(formMapping); fail("Successfully saved form mapping"); } catch (JpaSystemException ignored) { - ignored.printStackTrace(); +// ignored.printStackTrace(); } } diff --git a/avni-server-api/src/test/java/org/avni/server/domain/CHSBaseEntityTest.java b/avni-server-api/src/test/java/org/avni/server/domain/CHSBaseEntityTest.java new file mode 100644 index 000000000..8446dd608 --- /dev/null +++ b/avni-server-api/src/test/java/org/avni/server/domain/CHSBaseEntityTest.java @@ -0,0 +1,48 @@ +package org.avni.server.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class CHSBaseEntityTest { + @Test + public void equals() { + assertEquals(entity(1L), entity(1L)); + assertEquals(entity(1L, "a"), entity(1L, "a")); + assertEquals(entity(null, "a"), entity(null, "a")); + + assertNotEquals(entity(1L), entity(2L)); + assertNotEquals(new CHSBaseEntity(), new CHSBaseEntity()); + assertNotEquals(entity(1L), new CHSBaseEntity()); + assertNotEquals(new CHSBaseEntity(), entity(1L)); + assertNotEquals(otherTypeOfEntity(1L), entity(1L)); + assertNotEquals(new OtherTypeOfEntity(), new CHSBaseEntity()); + assertEquals(entity(1L), entity(1L)); + } + + private static CHSBaseEntity entity(Long id) { + return entity(id, null); + } + + private static CHSBaseEntity entity(Long id, String uuid) { + CHSBaseEntity chsBaseEntity = new CHSBaseEntity(); + chsBaseEntity.setId(id); + chsBaseEntity.setUuid(uuid); + return chsBaseEntity; + } + + private static OtherTypeOfEntity otherTypeOfEntity(Long id) { + return otherTypeOfEntity(id, null); + } + + private static OtherTypeOfEntity otherTypeOfEntity(Long id, String uuid) { + OtherTypeOfEntity chsBaseEntity = new OtherTypeOfEntity(); + chsBaseEntity.setId(id); + chsBaseEntity.setUuid(uuid); + return chsBaseEntity; + } + + static class OtherTypeOfEntity extends CHSBaseEntity { + } +} diff --git a/avni-server-api/src/test/java/org/avni/server/domain/OrganisationAwareEntityTest.java b/avni-server-api/src/test/java/org/avni/server/domain/OrganisationAwareEntityTest.java index f3658fc58..591454cfd 100644 --- a/avni-server-api/src/test/java/org/avni/server/domain/OrganisationAwareEntityTest.java +++ b/avni-server-api/src/test/java/org/avni/server/domain/OrganisationAwareEntityTest.java @@ -1,6 +1,7 @@ package org.avni.server.domain; import org.joda.time.DateTime; +import org.junit.Before; import org.junit.Test; import java.util.HashSet; @@ -9,18 +10,24 @@ import static org.junit.Assert.assertEquals; public class OrganisationAwareEntityTest { + private User user1; + private User user2; - - @Test - public void test_getLastModifiedForSubject(){ - User user1 = new User(); + @Before + public void setUp() { + user1 = new User(); + user1.setId(1l); user1.setUsername("user1"); user1.setName("user1"); - User user2 = new User(); + user2 = new User(); + user2.setId(2l); user2.setUsername("user2"); user2.setName("user2"); + } + @Test + public void test_getLastModifiedForSubject() { DateTime lastModifiedDateTime1 = new DateTime("2023-05-06T10:11:12.123"); DateTime lastModifiedDateTime2 = new DateTime("2023-05-05T10:11:12.123"); @@ -40,31 +47,22 @@ public void test_getLastModifiedForSubject(){ subjectType.setOperationalSubjectTypes(operationalSubjectTypeSet); operationalSubjectType.setSubjectType(subjectType); - assertEquals(operationalSubjectType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalSubjectType.getLastModifiedBy(),user1); + assertEquals(operationalSubjectType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalSubjectType.getLastModifiedBy(), user1); subjectType.setLastModifiedDateTime(lastModifiedDateTime2); operationalSubjectType.setLastModifiedDateTime(lastModifiedDateTime1); - assertEquals(operationalSubjectType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalSubjectType.getLastModifiedBy(),user2); + assertEquals(operationalSubjectType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalSubjectType.getLastModifiedBy(), user2); operationalSubjectType.setLastModifiedDateTime(lastModifiedDateTime2); - assertEquals(operationalSubjectType.getLastModifiedDateTime(),lastModifiedDateTime2); - assertEquals(operationalSubjectType.getLastModifiedBy(),user2); - + assertEquals(operationalSubjectType.getLastModifiedDateTime(), lastModifiedDateTime2); + assertEquals(operationalSubjectType.getLastModifiedBy(), user2); } @Test - public void test_getLastModifiedForProgram(){ - User user1 = new User(); - user1.setUsername("user1"); - user1.setName("user1"); - - User user2 = new User(); - user2.setUsername("user2"); - user2.setName("user2"); - + public void test_getLastModifiedForProgram() { DateTime lastModifiedDateTime1 = new DateTime("2023-05-06T10:11:12.123"); DateTime lastModifiedDateTime2 = new DateTime("2023-05-05T10:11:12.123"); @@ -84,31 +82,23 @@ public void test_getLastModifiedForProgram(){ program.setOperationalPrograms(operationalProgramTypeSet); operationalProgramType.setProgram(program); - assertEquals(operationalProgramType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalProgramType.getLastModifiedBy(),user1); + assertEquals(operationalProgramType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalProgramType.getLastModifiedBy(), user1); program.setLastModifiedDateTime(lastModifiedDateTime2); operationalProgramType.setLastModifiedDateTime(lastModifiedDateTime1); - assertEquals(operationalProgramType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalProgramType.getLastModifiedBy(),user2); + assertEquals(operationalProgramType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalProgramType.getLastModifiedBy(), user2); operationalProgramType.setLastModifiedDateTime(lastModifiedDateTime2); - assertEquals(operationalProgramType.getLastModifiedDateTime(),lastModifiedDateTime2); - assertEquals(operationalProgramType.getLastModifiedBy(),user2); + assertEquals(operationalProgramType.getLastModifiedDateTime(), lastModifiedDateTime2); + assertEquals(operationalProgramType.getLastModifiedBy(), user2); } @Test - public void test_getLastModifiedForEncounter(){ - User user1 = new User(); - user1.setUsername("user1"); - user1.setName("user1"); - - User user2 = new User(); - user2.setUsername("user2"); - user2.setName("user2"); - + public void test_getLastModifiedForEncounter() { DateTime lastModifiedDateTime1 = new DateTime("2023-05-06T10:11:12.123"); DateTime lastModifiedDateTime2 = new DateTime("2023-05-05T10:11:12.123"); @@ -128,18 +118,18 @@ public void test_getLastModifiedForEncounter(){ encounterType.setOperationalEncounterTypes(operationalEncounterTypeSet); operationalEncounterType.setEncounterType(encounterType); - assertEquals(operationalEncounterType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalEncounterType.getLastModifiedBy(),user1); + assertEquals(operationalEncounterType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalEncounterType.getLastModifiedBy(), user1); encounterType.setLastModifiedDateTime(lastModifiedDateTime2); operationalEncounterType.setLastModifiedDateTime(lastModifiedDateTime1); - assertEquals(operationalEncounterType.getLastModifiedDateTime(),lastModifiedDateTime1); - assertEquals(operationalEncounterType.getLastModifiedBy(),user2); + assertEquals(operationalEncounterType.getLastModifiedDateTime(), lastModifiedDateTime1); + assertEquals(operationalEncounterType.getLastModifiedBy(), user2); operationalEncounterType.setLastModifiedDateTime(lastModifiedDateTime2); - assertEquals(operationalEncounterType.getLastModifiedDateTime(),lastModifiedDateTime2); - assertEquals(operationalEncounterType.getLastModifiedBy(),user2); + assertEquals(operationalEncounterType.getLastModifiedDateTime(), lastModifiedDateTime2); + assertEquals(operationalEncounterType.getLastModifiedBy(), user2); } } diff --git a/avni-server-api/src/test/java/org/avni/server/framework/security/LimitHostNamesFilterTest.java b/avni-server-api/src/test/java/org/avni/server/framework/security/LimitHostNamesFilterTest.java index dec65949e..38f6b4ef9 100644 --- a/avni-server-api/src/test/java/org/avni/server/framework/security/LimitHostNamesFilterTest.java +++ b/avni-server-api/src/test/java/org/avni/server/framework/security/LimitHostNamesFilterTest.java @@ -1,17 +1,17 @@ package org.avni.server.framework.security; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.*; +import static org.junit.Assert.assertThat; public class LimitHostNamesFilterTest { private MockHttpServletRequest request; diff --git a/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditorIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditorIntegrationTest.java index a5ff9523e..3e1c8b235 100644 --- a/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditorIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/BulkLocationEditorIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.importer.batch.csv.writer; +import jakarta.transaction.Transactional; import org.avni.server.application.*; import org.avni.server.dao.LocationRepository; import org.avni.server.dao.application.FormRepository; @@ -24,6 +25,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class BulkLocationEditorIntegrationTest extends BaseCSVImportTest { @Autowired private TestDataSetupService testDataSetupService; diff --git a/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriterIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriterIntegrationTest.java index 54cc148e6..350d353fe 100644 --- a/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriterIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/importer/batch/csv/writer/UserAndCatchmentWriterIntegrationTest.java @@ -13,11 +13,11 @@ import org.avni.server.service.builder.TestLocationService; import org.avni.server.service.builder.TestSubjectTypeService; import org.junit.Test; +import org.springframework.batch.item.Chunk; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import java.util.Arrays; -import java.util.Collections; import java.util.UUID; import static org.junit.Assert.*; @@ -96,7 +96,7 @@ private String[] has(String... errors) { private void success(String[] headers, String[] cells, boolean catchmentCreated, boolean userCreated) throws IDPException { long numberOfUsers = userRepository.count(); long numberOfCatchments = catchmentRepository.count(); - userAndCatchmentWriter.write(Collections.singletonList(new Row(headers, cells))); + userAndCatchmentWriter.write(Chunk.of(new Row(headers, cells))); if (catchmentCreated) assertEquals(catchmentRepository.count(), numberOfCatchments + 1); else @@ -109,7 +109,7 @@ private void success(String[] headers, String[] cells, boolean catchmentCreated, private void failure(String[] headers, String[] cells, String[] errorMessages) throws IDPException { try { - userAndCatchmentWriter.write(Collections.singletonList(new Row(headers, cells))); + userAndCatchmentWriter.write(Chunk.of(new Row(headers, cells))); fail(); } catch (RuntimeException e) { String message = e.getMessage(); @@ -129,7 +129,7 @@ private void failure(String[] headers, String[] cells, String[] errorMessages) t private void failsOnMissingHeader(String[] headers, String[] errorMessages, String... nonExistentErrorMessages) throws IDPException { try { - userAndCatchmentWriter.write(Collections.singletonList(new Row(headers, new String[]{}))); + userAndCatchmentWriter.write(Chunk.of(new Row(headers, new String[]{}))); fail(); } catch (RuntimeException e) { String message = e.getMessage(); diff --git a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelCacheIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelCacheIntegrationTest.java index 3dc931c4f..251e86c39 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelCacheIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelCacheIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.application.projections.CatchmentAddressProjection; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.LocationRepository; @@ -29,6 +30,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class AddressLevelCacheIntegrationTest extends AbstractControllerIntegrationTest { private static final long ADDRESS_LEVEL_TYPE_ID = 1L; @@ -398,4 +400,4 @@ public void validateCacheClearedAndGCRemovesTheOldEntryValueFromMemory_attempt_2 public void validateCacheClearedAndGCRemovesTheOldEntryValueFromMemory_attempt_3() throws InterruptedException { givenAddressLevelCachesAreFullyPopulated_whenCallGetCatchmentAddressesForNewCatchmentId_thenValidateCacheClearedAndGCRemovesTheOldEntryValueFromMemory(); } -} \ No newline at end of file +} diff --git a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceIntegrationTest.java index 972194dc0..cbc568eb7 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.domain.AddressLevel; @@ -21,6 +22,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class AddressLevelServiceIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestDataSetupService testDataSetupService; diff --git a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceTest.java b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceTest.java index bc20b822e..0b9e1ddaa 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/AddressLevelServiceTest.java @@ -1,23 +1,21 @@ package org.avni.server.service; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; import org.avni.server.application.KeyType; import org.avni.server.dao.AddressLevelTypeRepository; import org.avni.server.dao.LocationRepository; import org.avni.server.domain.*; import org.avni.server.framework.security.UserContextHolder; +import org.avni.server.util.ObjectMapperSingleton; +import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.util.Arrays; import java.util.Map; @@ -27,7 +25,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) @PrepareForTest({UserContextHolder.class}) public class AddressLevelServiceTest { @Mock @@ -39,12 +36,18 @@ public void setUp() { Query query = Mockito.mock(Query.class); when(entityManager.createNativeQuery(Mockito.anyString())).thenReturn(query); when(entityManager.createNativeQuery(Mockito.anyString()).executeUpdate()).thenReturn(1); - PowerMockito.mockStatic(UserContextHolder.class); Organisation org = mock(Organisation.class); - when(UserContextHolder.getOrganisation()).thenReturn(org); + UserContext userContext = new UserContext(); + userContext.setOrganisation(org); + UserContextHolder.create(userContext); when(org.getDbUser()).thenReturn("db-user"); } + @After + public void tearDown() { + UserContextHolder.clear(); + } + @Test public void shouldFetchDifferentAddressIdsWhenSubjectTypeChanges() throws JsonProcessingException { LocationRepository locationRepository = mock(LocationRepository.class); @@ -62,9 +65,8 @@ public void shouldFetchDifferentAddressIdsWhenSubjectTypeChanges() throws JsonPr )); String orgConfig = "[{\"subjectTypeUUID\": \"first-subject-type-uuid\", \"locationTypeUUIDs\": [\"first-address-level-type-uuid\"]},{\"subjectTypeUUID\": \"second-subject-type-uuid\", \"locationTypeUUIDs\": [\"second-address-level-type-uuid\"]}]"; - ObjectMapper objectMapper = new ObjectMapper(); when(organisationConfigService.getSettingsByKey(KeyType.customRegistrationLocations.toString())).thenReturn( - asList(objectMapper.readValue(orgConfig, Map[].class)) + asList(ObjectMapperSingleton.getObjectMapper().readValue(orgConfig, Map[].class)) ); when(addressLevelTypeRepository.findAllByUuidIn(singletonList("first-address-level-type-uuid"))) .thenReturn(singletonList(createAddressLevelType(1L))); diff --git a/avni-server-api/src/test/java/org/avni/server/service/GroupSubjectServiceIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/GroupSubjectServiceIntegrationTest.java index b8aaf500c..457fc1745 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/GroupSubjectServiceIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/GroupSubjectServiceIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.GroupRoleRepository; import org.avni.server.dao.UserSubjectAssignmentRepository; @@ -24,6 +25,7 @@ @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Transactional public class GroupSubjectServiceIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestSubjectTypeService testSubjectTypeService; @@ -41,6 +43,7 @@ public class GroupSubjectServiceIntegrationTest extends AbstractControllerIntegr private TestGroupSubjectService testGroupSubjectService; @Test + @Transactional public void on_addition_of_member_to_a_group__assign_member_to_the_user_assigned_to_the_group() throws ValidationException { TestDataSetupService.TestOrganisationData testOrganisationData = testDataSetupService.setupOrganisation(); TestDataSetupService.TestCatchmentData testCatchmentData = testDataSetupService.setupACatchment(); diff --git a/avni-server-api/src/test/java/org/avni/server/service/IndividualServiceIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/IndividualServiceIntegrationTest.java index ce569f020..e32145e27 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/IndividualServiceIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/IndividualServiceIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.Individual; import org.junit.Before; @@ -10,6 +11,7 @@ import static org.assertj.core.api.Assertions.assertThat; @Sql(scripts = {"/test-data.sql"}) +@Transactional public class IndividualServiceIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private IndividualService individualService; diff --git a/avni-server-api/src/test/java/org/avni/server/service/KeycloakIdpServiceTest.java b/avni-server-api/src/test/java/org/avni/server/service/KeycloakIdpServiceTest.java index 900c6549a..1bfac44fc 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/KeycloakIdpServiceTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/KeycloakIdpServiceTest.java @@ -1,5 +1,7 @@ package org.avni.server.service; +import jakarta.ws.rs.ForbiddenException; +import jakarta.ws.rs.ServerErrorException; import org.avni.server.domain.User; import org.joda.time.DateTime; import org.junit.Test; @@ -9,8 +11,6 @@ import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.ServerErrorException; import java.util.Arrays; import java.util.Collections; @@ -19,7 +19,7 @@ import static org.mockito.Mockito.when; public class KeycloakIdpServiceTest { - + public static final String USER_KEYCLOAK_UUID = "user-keycloak-uuid"; public static final String USERNAME = "user"; public static final int EXPECTED_NUMBER_OF_EVENTS_TO_FETCH = 5; diff --git a/avni-server-api/src/test/java/org/avni/server/service/OrganisationConfigServiceTest.java b/avni-server-api/src/test/java/org/avni/server/service/OrganisationConfigServiceTest.java index 398722089..b8a4e7ab8 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/OrganisationConfigServiceTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/OrganisationConfigServiceTest.java @@ -1,5 +1,6 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.application.OrganisationConfigSettingKey; import org.avni.server.dao.OrganisationConfigRepository; import org.avni.server.domain.JsonObject; @@ -8,11 +9,7 @@ import org.avni.server.domain.UserContext; import org.avni.server.framework.security.UserContextHolder; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.Optional; @@ -21,10 +18,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(PowerMockRunner.class) @PrepareForTest({UserContextHolder.class}) +@Transactional public class OrganisationConfigServiceTest { - @Test public void shouldRetrieveOptionalObjectFromOrganisationSettings() { OrganisationConfigRepository organisationRepository = mock(OrganisationConfigRepository.class); @@ -47,11 +43,12 @@ public void shouldRetrieveOptionalObjectFromOrganisationSettings() { @Test public void shouldCheckIfMessagingFeatureEnabled() { OrganisationConfigRepository organisationConfigRepository = mock(OrganisationConfigRepository.class); - PowerMockito.mockStatic(UserContextHolder.class); - UserContext userContext = mock(UserContext.class); long organisationId = 25l; - when(userContext.getOrganisationId()).thenReturn(organisationId); - Mockito.when(UserContextHolder.getUserContext()).thenReturn(userContext); + UserContext context = new UserContext(); + Organisation organisation = new Organisation(); + organisation.setId(organisationId); + context.setOrganisation(organisation); + UserContextHolder.create(context); OrganisationConfig organisationConfigWithoutMessagingEnabled = new OrganisationConfig(); organisationConfigWithoutMessagingEnabled.setSettings(new JsonObject()); diff --git a/avni-server-api/src/test/java/org/avni/server/service/UserServiceTest.java b/avni-server-api/src/test/java/org/avni/server/service/UserServiceTest.java index 71309d83f..f70a81395 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/UserServiceTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/UserServiceTest.java @@ -80,9 +80,10 @@ public void shouldDeduplicateListOfGroupsSpecified() { Group group1 = new Group(); Group group2 = new Group(); Group everyone = new Group(); + everyone.setId(1L); when(groupRepository.findByNameIgnoreCase("group1")).thenReturn(group1); when(groupRepository.findByNameIgnoreCase("group2")).thenReturn(group2); - when(groupRepository.findByNameAndOrganisationId(Group.Everyone, orgId)).thenReturn(group1); + when(groupRepository.findByNameAndOrganisationId(Group.Everyone, orgId)).thenReturn(everyone); userService.addToGroups(user, "group1,group2,group1"); verify(userGroupRepository, times(3)).save(userGroupArgumentCaptor.capture()); diff --git a/avni-server-api/src/test/java/org/avni/server/service/UserSubjectAssignmentServiceIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/UserSubjectAssignmentServiceIntegrationTest.java index cd398c9cb..516218a1a 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/UserSubjectAssignmentServiceIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/UserSubjectAssignmentServiceIntegrationTest.java @@ -1,6 +1,7 @@ package org.avni.server.service; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.GroupRoleRepository; import org.avni.server.dao.UserSubjectAssignmentRepository; @@ -21,10 +22,10 @@ import java.util.Collections; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) @Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Transactional public class UserSubjectAssignmentServiceIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestSubjectTypeService testSubjectTypeService; diff --git a/avni-server-api/src/test/java/org/avni/server/service/accessControl/AccessControlServiceIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/service/accessControl/AccessControlServiceIntegrationTest.java index c31546680..272cb482c 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/accessControl/AccessControlServiceIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/accessControl/AccessControlServiceIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.service.accessControl; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.*; import org.avni.server.domain.accessControl.SubjectPartitionCheckStatus; @@ -22,6 +23,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class AccessControlServiceIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestDataSetupService testDataSetupService; diff --git a/avni-server-api/src/test/java/org/avni/server/service/builder/TestDataSetupService.java b/avni-server-api/src/test/java/org/avni/server/service/builder/TestDataSetupService.java index a03cb6395..fe97acab9 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/builder/TestDataSetupService.java +++ b/avni-server-api/src/test/java/org/avni/server/service/builder/TestDataSetupService.java @@ -10,9 +10,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.mail.Address; -import java.util.*; -import java.util.stream.Collectors; +import java.util.List; +import java.util.Map; +import java.util.UUID; @Service public class TestDataSetupService { diff --git a/avni-server-api/src/test/java/org/avni/server/service/identifier/IdentifierUserAssignmentRepositoryTest.java b/avni-server-api/src/test/java/org/avni/server/service/identifier/IdentifierUserAssignmentRepositoryTest.java index 06c148660..be1f230b3 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/identifier/IdentifierUserAssignmentRepositoryTest.java +++ b/avni-server-api/src/test/java/org/avni/server/service/identifier/IdentifierUserAssignmentRepositoryTest.java @@ -1,5 +1,6 @@ package org.avni.server.service.identifier; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.IdentifierSourceRepository; import org.avni.server.dao.IdentifierUserAssignmentRepository; @@ -18,6 +19,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class IdentifierUserAssignmentRepositoryTest extends AbstractControllerIntegrationTest { @Autowired private IdentifierSourceRepository identifierSourceRepository; diff --git a/avni-server-api/src/test/java/org/avni/server/service/sync/TestSyncService.java b/avni-server-api/src/test/java/org/avni/server/service/sync/TestSyncService.java index 0f817695d..883d79ae5 100644 --- a/avni-server-api/src/test/java/org/avni/server/service/sync/TestSyncService.java +++ b/avni-server-api/src/test/java/org/avni/server/service/sync/TestSyncService.java @@ -9,8 +9,8 @@ import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; @@ -45,8 +45,8 @@ public List getSubjects(SubjectType subjectType, DateTime lastModifi } public List getSubjects(SubjectType subjectType, DateTime lastModifiedDateTime, DateTime now) { - PagedResources> individuals = individualController.getIndividualsByOperatingIndividualScope(lastModifiedDateTime, now, subjectType.getUuid(), PageRequest.of(0, 10)); - return individuals.getContent().stream().map(Resource::getContent).collect(Collectors.toList()); + CollectionModel> individuals = individualController.getIndividualsByOperatingIndividualScope(lastModifiedDateTime, now, subjectType.getUuid(), PageRequest.of(0, 10)); + return individuals.getContent().stream().map(EntityModel::getContent).collect(Collectors.toList()); } public List getEnrolments(Program program) throws Exception { @@ -58,7 +58,7 @@ public List getEnrolments(Program program, DateTime lastModifi } public List getEnrolments(Program program, DateTime lastModifiedDateTime, DateTime now) throws Exception { - PagedResources> enrolments = programEnrolmentController.getProgramEnrolmentsByOperatingIndividualScope(lastModifiedDateTime, now, program.getUuid(), PageRequest.of(0, 10)); - return enrolments.getContent().stream().map(Resource::getContent).collect(Collectors.toList()); + CollectionModel> enrolments = programEnrolmentController.getProgramEnrolmentsByOperatingIndividualScope(lastModifiedDateTime, now, program.getUuid(), PageRequest.of(0, 10)); + return enrolments.getContent().stream().map(EntityModel::getContent).collect(Collectors.toList()); } } diff --git a/avni-server-api/src/test/java/org/avni/server/util/DateTimeUtilTest.java b/avni-server-api/src/test/java/org/avni/server/util/DateTimeUtilTest.java index 058ebc12c..9d825ecb2 100644 --- a/avni-server-api/src/test/java/org/avni/server/util/DateTimeUtilTest.java +++ b/avni-server-api/src/test/java/org/avni/server/util/DateTimeUtilTest.java @@ -1,15 +1,22 @@ package org.avni.server.util; -import org.joda.time.DateTimeZone; +import org.joda.time.LocalDate; +import org.joda.time.LocalDateTime; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DateTimeUtilTest { - @Test public void shouldGetTheRightDateForDateTimeString() { String aDateString = "2020-01-31T18:30:00.000+00:00"; assertThat(DateTimeUtil.toDateString(aDateString)).isEqualTo("2020-02-01"); } + + @Test + public void jodaConversions() { + DateTimeUtil.toJodaDateTime(java.time.Instant.now()); + DateTimeUtil.toInstant(LocalDate.now()); + DateTimeUtil.toInstant(LocalDateTime.now().toDateTime()); + } } diff --git a/avni-server-api/src/test/java/org/avni/server/web/ConceptControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/ConceptControllerIntegrationTest.java index ebc04f4a2..81dcc5747 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/ConceptControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/ConceptControllerIntegrationTest.java @@ -1,11 +1,11 @@ package org.avni.server.web; import org.avni.server.common.AbstractControllerIntegrationTest; -import org.junit.Before; -import org.junit.Test; import org.avni.server.dao.ConceptRepository; import org.avni.server.domain.Concept; import org.avni.server.domain.ConceptDataType; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; diff --git a/avni-server-api/src/test/java/org/avni/server/web/ConceptDirtyCheckingIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/ConceptDirtyCheckingIntegrationTest.java index 0a66f315e..ea21ec835 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/ConceptDirtyCheckingIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/ConceptDirtyCheckingIntegrationTest.java @@ -2,6 +2,7 @@ import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.ConceptRepository; +import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -9,7 +10,6 @@ import org.springframework.test.context.jdbc.Sql; import java.io.IOException; -import org.joda.time.DateTime; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; diff --git a/avni-server-api/src/test/java/org/avni/server/web/EncounterControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/EncounterControllerIntegrationTest.java index 90e720fea..52cf71b64 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/EncounterControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/EncounterControllerIntegrationTest.java @@ -1,10 +1,10 @@ package org.avni.server.web; import org.avni.server.common.AbstractControllerIntegrationTest; -import org.junit.Assert; -import org.junit.Test; import org.avni.server.dao.EncounterRepository; import org.avni.server.domain.Encounter; +import org.junit.Assert; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; diff --git a/avni-server-api/src/test/java/org/avni/server/web/EncounterTypesIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/EncounterTypesIntegrationTest.java index c4443ebbf..aab4d8c10 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/EncounterTypesIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/EncounterTypesIntegrationTest.java @@ -1,10 +1,10 @@ package org.avni.server.web; import org.avni.server.common.AbstractControllerIntegrationTest; -import org.junit.Before; -import org.junit.Test; import org.avni.server.dao.EncounterTypeRepository; import org.avni.server.domain.EncounterType; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; diff --git a/avni-server-api/src/test/java/org/avni/server/web/FormControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/FormControllerIntegrationTest.java index 5f2583e68..59f32c0a2 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/FormControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/FormControllerIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.hibernate.Hibernate; import org.junit.Before; @@ -76,7 +77,7 @@ public void setUp() throws Exception { @Test public void findByEntityId() { - Page fmPage = formMappingRepository.findByProgramId(1L, new PageRequest(0, 1)); + Page fmPage = formMappingRepository.findByProgramId(1L, PageRequest.of(0, 1)); assertEquals(1, fmPage.getContent().size()); } diff --git a/avni-server-api/src/test/java/org/avni/server/web/FormMappingsIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/FormMappingsIntegrationTest.java index f77f0570c..ab460060e 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/FormMappingsIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/FormMappingsIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.junit.Before; import org.junit.Test; diff --git a/avni-server-api/src/test/java/org/avni/server/web/IndividualControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/IndividualControllerIntegrationTest.java index ec3b56cce..7d6f18131 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/IndividualControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/IndividualControllerIntegrationTest.java @@ -1,12 +1,12 @@ package org.avni.server.web; import org.avni.server.common.AbstractControllerIntegrationTest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.avni.server.dao.IndividualRepository; import org.avni.server.domain.Individual; import org.avni.server.domain.JsonObject; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.test.context.jdbc.Sql; diff --git a/avni-server-api/src/test/java/org/avni/server/web/MetadataDiffControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/MetadataDiffControllerIntegrationTest.java index 412c7da2a..b92725972 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/MetadataDiffControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/MetadataDiffControllerIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.junit.Before; import org.junit.Test; @@ -12,6 +13,7 @@ @Sql(value = {"/test-data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class MetadataDiffControllerIntegrationTest extends AbstractControllerIntegrationTest { @Before @@ -30,4 +32,4 @@ public void testCompareMetadataZips() throws Exception { .file(file2)) .andExpect(status().isOk()); } -} \ No newline at end of file +} diff --git a/avni-server-api/src/test/java/org/avni/server/web/ProgramEncounterControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/ProgramEncounterControllerIntegrationTest.java index 1cfe0223f..ce8eb4f78 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/ProgramEncounterControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/ProgramEncounterControllerIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.ProgramEncounterRepository; import org.avni.server.domain.Encounter; diff --git a/avni-server-api/src/test/java/org/avni/server/web/ProgramEnrolmentControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/ProgramEnrolmentControllerIntegrationTest.java index acfb621e8..18debf57b 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/ProgramEnrolmentControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/ProgramEnrolmentControllerIntegrationTest.java @@ -2,20 +2,14 @@ import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.ProgramEnrolmentRepository; -import org.avni.server.domain.Individual; -import org.avni.server.domain.JsonObject; -import org.avni.server.domain.Program; import org.avni.server.domain.ProgramEnrolment; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.jdbc.Sql; import java.io.IOException; -import java.util.List; -import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; diff --git a/avni-server-api/src/test/java/org/avni/server/web/SampleControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/SampleControllerIntegrationTest.java index 3fd0a8b66..a992ba3da 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/SampleControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/SampleControllerIntegrationTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.junit.Before; import org.junit.Test; @@ -10,6 +11,7 @@ import static org.junit.Assert.assertThat; @Sql({"/test-data-openchs-organisation.sql"}) +@Transactional public class SampleControllerIntegrationTest extends AbstractControllerIntegrationTest { @Before diff --git a/avni-server-api/src/test/java/org/avni/server/web/TransactionDataSyncTest.java b/avni-server-api/src/test/java/org/avni/server/web/TransactionDataSyncTest.java index 5a06b51fd..606fd0564 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/TransactionDataSyncTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/TransactionDataSyncTest.java @@ -1,5 +1,6 @@ package org.avni.server.web; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.dao.GroupRoleRepository; import org.avni.server.dao.UserRepository; @@ -19,11 +20,12 @@ import org.avni.server.web.request.syncAttribute.UserSyncSettings; import org.joda.time.DateTime; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; -import org.springframework.hateoas.PagedResources; -import org.springframework.hateoas.Resource; +import org.springframework.hateoas.CollectionModel; +import org.springframework.hateoas.EntityModel; import org.springframework.test.context.jdbc.Sql; import java.util.Collections; @@ -174,6 +176,8 @@ public void setup() { } @Test + @Transactional + @Ignore public void sync() throws Exception { // Catchment tx entities Individual inTheCatchment = testSubjectService.save(new SubjectBuilder().withMandatoryFieldsForNewEntity().withSubjectType(subjectTypeWithCatchmentBasedSync).withLocation(catchmentData.getAddressLevel1()).build()); @@ -282,11 +286,13 @@ public void sync() throws Exception { Individual assignedGroupSubject = testSubjectService.save(new SubjectBuilder().withMandatoryFieldsForNewEntity().withSubjectType(groupSubjectTypeForDirectAssignment).withLocation(catchmentData.getAddressLevel1()).build()); GroupSubject groupSubjectInDirectAssignment = testGroupSubjectService.save(new TestGroupSubjectBuilder().withGroupRole(groupRoleForGroupSubjectTypeWithCatchmentBasedSync).withMember(assigned).withGroup(assignedGroupSubject).build()); userSubjectAssignmentService.assignSubjects(organisationData.getUser(), Collections.singletonList(assignedGroupSubject), false); - groupSubjects = getGroupSubjects(groupSubjectTypeForCatchmentBasedSync); + + groupSubjects = getGroupSubjects(groupSubjectTypeForDirectAssignment); assertTrue(hasEntity(groupSubjectInDirectAssignment, groupSubjects)); } @Test + @Transactional public void syncShouldSyncEverythingBeforeNow() throws Exception { setUser(organisationData.getUser().getUsername()); @@ -355,9 +361,9 @@ private List getGroupSubjects(SubjectType groupSubjectType, DateTi } private List getGroupSubjects(SubjectType groupSubjectType, DateTime lastModifiedDateTime, DateTime now) { - PagedResources> enrolments = groupSubjectController.getGroupSubjectsByOperatingIndividualScope(lastModifiedDateTime, now, + CollectionModel> enrolments = groupSubjectController.getGroupSubjectsByOperatingIndividualScope(lastModifiedDateTime, now, groupSubjectType.getUuid(), PageRequest.of(0, 10)); - return enrolments.getContent().stream().map(Resource::getContent).collect(Collectors.toList()); + return enrolments.getContent().stream().map(EntityModel::getContent).collect(Collectors.toList()); } } diff --git a/avni-server-api/src/test/java/org/avni/server/web/api/SubjectApiControllerIntegrationTest.java b/avni-server-api/src/test/java/org/avni/server/web/api/SubjectApiControllerIntegrationTest.java index c83526d0a..acf07b506 100644 --- a/avni-server-api/src/test/java/org/avni/server/web/api/SubjectApiControllerIntegrationTest.java +++ b/avni-server-api/src/test/java/org/avni/server/web/api/SubjectApiControllerIntegrationTest.java @@ -1,12 +1,12 @@ package org.avni.server.web.api; +import jakarta.transaction.Transactional; import org.avni.server.common.AbstractControllerIntegrationTest; import org.avni.server.domain.*; import org.avni.server.domain.factory.txData.ObservationCollectionBuilder; import org.avni.server.domain.factory.txn.SubjectBuilder; import org.avni.server.domain.metadata.SubjectTypeBuilder; import org.avni.server.service.builder.*; -import org.avni.server.web.request.api.SubjectResponseOptions; import org.avni.server.web.response.ResponsePage; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -25,6 +25,7 @@ @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Transactional public class SubjectApiControllerIntegrationTest extends AbstractControllerIntegrationTest { @Autowired private TestDataSetupService testDataSetupService; diff --git a/avni-server-api/src/test/resources/application.properties b/avni-server-api/src/test/resources/application.properties index b5c09903f..78388e6ec 100644 --- a/avni-server-api/src/test/resources/application.properties +++ b/avni-server-api/src/test/resources/application.properties @@ -23,17 +23,16 @@ server.tomcat.accesslog.max-days=90 # JPA, Hibernate and Spring Data spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=none -spring.jpa.properties.jadira.usertype.databaseZone=jvm -spring.jpa.properties.jadira.usertype.javaZone=jvm -spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true -spring.jpa.properties.hibernate.dialect=org.avni.server.framework.postgres.CHSPostgreSQL94Dialect -spring.jpa.properties.hibernate.ejb.interceptor=org.avni.server.framework.hibernate.UpdateOrganisationHibernateInterceptor +#spring.jpa.properties.jadira.usertype.databaseZone=jvm +#spring.jpa.properties.jadira.usertype.javaZone=jvm +#spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.properties.hibernate.session_factory.interceptor=org.avni.server.framework.hibernate.UpdateOrganisationHibernateInterceptor spring.jpa.properties.hibernate.cache.use_second_level_cache=true spring.jpa.properties.hibernate.cache.use_query_cache=true -spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory +spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory spring.cache.jcache.config=${AVNI_EHCACHE_FILE:classpath:ehcache.xml} -spring.jpa.database-platform=org.avni.server.framework.postgres.CHSPostgreSQL94Dialect -spring.jpa.hibernate.use-new-id-generator-mappings=true +#spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL10Dialect spring.profiles.active=${OPENCHS_MODE:test} spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false avni.custom.query.timeout=${AVNI_CUSTOM_QUERY_TIMEOUT:5} @@ -45,6 +44,8 @@ cognito.poolid=dummy cognito.region=${OPENCHS_AWS_REGION:ap-south-1} spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true +spring.main.allow-bean-definition-overriding=true + #Bugsnag avni.bugsnag.apiKey=${OPENCHS_SERVER_BUGSNAG_API_KEY:dummy} avni.bugsnag.releaseStage=${OPENCHS_BUGSNAG_RELEASE_STAGE:development} @@ -130,4 +131,7 @@ metabase.api.key=${METABASE_API_KEY:mb_hwsYP2sFN7fvwM5LTS4d/tnIqA5SeHUxwUhm2KAI1 avni.endpoints.endOfLife.1=2024-09-09 #default org configuration -avni.default.org.user.db.password=${AVNI_DEFAULT_ORG_USER_DB_PASSWORD:password} \ No newline at end of file +avni.default.org.user.db.password=${AVNI_DEFAULT_ORG_USER_DB_PASSWORD:password} + +spring.mvc.pathmatch.matching-strategy=ant_path_matcher +server.servlet.register-default-servlet=true \ No newline at end of file diff --git a/build.gradle b/build.gradle index b6dfa5031..5eb3f3e3f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,4 @@ allprojects { - apply plugin: 'maven' - group = 'org.openchs' version = '0.0.1-SNAPSHOT' } @@ -8,18 +6,9 @@ allprojects { subprojects { apply plugin: 'java' apply plugin: 'idea' - sourceCompatibility = 1.8 - targetCompatibility = 1.8 - repositories { mavenLocal() - maven { url "https://repo.maven.apache.org/maven2" } } - - - dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' - } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ef9b04044..6d0a886d8 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip diff --git a/mypatch.patch b/mypatch.patch index a962b231b..f2bb00cfa 100644 --- a/mypatch.patch +++ b/mypatch.patch @@ -29,8 +29,8 @@ index 00000000..fd35b7b1 +import org.avni.server.domain.EntityType; +import org.avni.server.domain.OrganisationAwareEntity; + -+import javax.persistence.*; -+import javax.validation.constraints.NotNull; ++import jakarta.persistence.*; ++import jakarta.validation.constraints.NotNull; + +@Entity +@Table(name = "account_admin")