From 22fa1316aa64091f14d7674d22c90556abc0ead9 Mon Sep 17 00:00:00 2001 From: Jim Bethancourt Date: Thu, 29 Jun 2023 14:49:30 -0500 Subject: [PATCH] #292 Migrated to Spring Boot 3 using OpenRewrite Please note: - Galapagos is now on Java 17 - KafkaSenderImpl no longer needs KafkaFutureDecoupler since kafkaTemlate.send() now returns a CompletableFuture - KafkaSenderImplTest now performs an assertFalse() as a result - SecurityConfig has been commented out since Keycloak is deprecated and not supported in Spring Boot 3 / Spring 6. Unfortunately I don't know how to implement OAuth 2 at this time either. I can't seem to figure out how to run it locally - I get a 401 error when I try to run it from my IDE with the demo,democonf,actuator profiles: Could not access or read /service_accounts workaround endpoint: Server returned 401 for /service_accounts OpenRewrite configuration used to perform migration: ```xml org.openrewrite.maven rewrite-maven-plugin 5.2.4 org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_0 org.openrewrite.recipe rewrite-spring 5.0.2 ``` --- .github/workflows/dockerhub.yml | 4 +- .github/workflows/maven.yml | 4 +- pom.xml | 322 +++++++++--------- .../CleanupDeveloperAuthenticationsJob.java | 2 - .../adminjobs/impl/CreateBackupJob.java | 2 - .../adminjobs/impl/DeleteAclsJob.java | 6 +- .../impl/GenerateToolingApiKeyJob.java | 2 - .../impl/GenerateToolingCertificateJob.java | 10 +- .../adminjobs/impl/ImportBackupJob.java | 2 - .../impl/ImportKnownApplicationsJob.java | 6 +- .../impl/MarkTopicApprovalRequiredJob.java | 2 - .../impl/ResetApplicationPrefixesJob.java | 2 - .../impl/UpdateApplicationAclsJob.java | 2 - .../impl/UpdateConfluentAuthMetadataJob.java | 2 - .../galapagos/adminjobs/impl/ViewAclsJob.java | 2 - .../controller/ApplicationsController.java | 11 +- .../impl/ApplicationsServiceImpl.java | 5 +- .../impl/UpdateApplicationAclsListener.java | 2 - .../CertificatesAuthenticationModule.java | 5 +- .../controller/TrustStoreController.java | 6 +- .../impl/CertificateExpiryReminderRunner.java | 2 - .../CertificateExpiryReminderServiceImpl.java | 2 - .../changes/controller/ChangesController.java | 2 - .../changes/impl/ChangesServiceImpl.java | 2 - .../DeveloperAuthenticationServiceImpl.java | 18 +- .../impl/GalapagosEventManagerImpl.java | 2 - .../controller/EnvironmentsController.java | 2 - .../kafka/impl/ConnectedKafkaCluster.java | 35 +- .../kafka/impl/ConnectedKafkaClusters.java | 4 +- .../kafka/impl/KafkaConnectionManager.java | 2 +- .../impl/KafkaRepositoryContainerImpl.java | 5 +- .../galapagos/kafka/impl/KafkaSenderImpl.java | 8 +- .../kafka/util/KafkaTopicConfigHelper.java | 5 +- .../galapagos/naming/config/CaseStrategy.java | 3 +- .../galapagos/naming/config/NamingConfig.java | 3 +- .../naming/impl/NamingServiceImpl.java | 2 - .../notifications/impl/MailConfig.java | 2 +- .../impl/NotificationEventListener.java | 4 +- .../impl/NotificationServiceImpl.java | 13 +- .../ais/galapagos/schemas/SchemaUtil.java | 6 +- .../galapagos/security/SecurityConfig.java | 168 ++++----- .../impl/AuditEventRepositoryImpl.java | 2 +- .../security/impl/AuditEventsListener.java | 2 - .../impl/DefaultCurrentUserService.java | 4 +- .../staging/impl/StagingServiceImpl.java | 2 - .../controller/SubscriptionsController.java | 8 +- .../service/impl/SubscriptionServiceImpl.java | 2 - .../impl/SubscriptionTopicListener.java | 2 - .../controller/ChangeTopicOwnerDto.java | 2 +- .../topics/controller/TopicController.java | 4 +- .../topics/service/impl/TopicServiceImpl.java | 17 +- .../impl/ValidatingTopicServiceImpl.java | 2 - .../controller/UISupportController.java | 2 - .../util/controller/BackupController.java | 2 - .../impl/StartupRepositoryInitializer.java | 2 - .../ais/galapagos/ContextStartupTest.java | 19 +- .../adminjobs/impl/CreateBackupJobTest.java | 42 +-- .../GenerateToolingCertificateJobTest.java | 21 +- .../adminjobs/impl/ImportBackupJobTest.java | 51 ++- .../impl/ImportKnownApplicationsJobTest.java | 37 +- .../adminjobs/impl/ViewAclsJobTest.java | 28 +- .../ApplicationsControllerTest.java | 6 +- .../ApplicationsControllerTest.java | 8 +- .../impl/ApplicationsServiceImplTest.java | 18 +- ...licationsServiceRequestStatesImplTest.java | 94 ++--- .../UpdateApplicationAclsListenerTest.java | 20 +- .../ccloud/ConfluentCloudApiClientTest.java | 30 +- ...onfluentCloudAuthenticationModuleTest.java | 46 +-- .../certificates/impl/CaManagerImplTest.java | 16 +- ...teExpiryReminderRunnerIntegrationTest.java | 27 +- .../CertificateExpiryReminderServiceTest.java | 29 +- .../changes/impl/ChangeBaseTest.java | 12 +- .../changes/impl/ChangeDeserializerTest.java | 8 +- .../changes/impl/ChangesServiceImplTest.java | 25 +- .../devauth/impl/DevUserAclListenerTest.java | 14 +- ...eveloperAuthenticationServiceImplTest.java | 20 +- .../kafka/impl/ConnectedKafkaClusterTest.java | 11 +- .../kafka/impl/KafkaFutureDecouplerTest.java | 35 +- .../kafka/impl/KafkaSenderImplTest.java | 25 +- .../impl/TopicBasedRepositoryImplTest.java | 46 +-- .../galapagos/kafka/util/AclSupportTest.java | 22 +- ...rategyConverterBindingIntegrationTest.java | 11 +- .../CaseStrategyConverterBindingTest.java | 39 ++- .../naming/impl/NamingServiceImplTest.java | 26 +- .../impl/NotificationEventListenerTest.java | 24 +- .../impl/NotificationServiceImplTest.java | 37 +- .../request/ApplicationOwnerRequestTest.java | 11 +- .../ais/galapagos/schema/SchemaUtilTest.java | 110 +++--- .../staging/impl/StagingImplTest.java | 53 ++- .../SubscriptionsControllerTest.java | 30 +- .../impl/SubscriptionServiceImplTest.java | 38 ++- .../controller/TopicControllerTest.java | 41 +-- .../impl/ValidatingTopicServiceImplTest.java | 35 +- .../impl/TopicServiceImplIntegrationTest.java | 25 +- .../service/impl/TopicServiceImplTest.java | 104 +++--- .../controller/CustomLinksConfigTest.java | 57 ++-- .../controller/UISupportControllerTest.java | 13 +- .../ais/galapagos/util/CnUtilTest.java | 8 +- 98 files changed, 1032 insertions(+), 1082 deletions(-) diff --git a/.github/workflows/dockerhub.yml b/.github/workflows/dockerhub.yml index 96543b50..e74d2d0a 100644 --- a/.github/workflows/dockerhub.yml +++ b/.github/workflows/dockerhub.yml @@ -9,10 +9,10 @@ jobs: steps: - name: Check out the repo uses: actions/checkout@v2 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 11 + java-version: 17 - name: Build and push Docker Image shell: bash env: diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 634f58b0..881b78f0 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -29,10 +29,10 @@ jobs: - name: Run ESLint run: npm run lint working-directory: ui - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 11 + java-version: 17 - name: Build with Maven run: mvn -B -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN package --file pom.xml diff --git a/pom.xml b/pom.xml index 61d105e1..c390c149 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.6 + 3.0.8 com.hermesworld.ais @@ -16,180 +16,188 @@ A self-service tool for managing Kafka Topics and associated JSON schemas. - 11 + 17 20.0.0 - 1.18.24 + 1.18.28 2.7.2 v16.14.0 3.7.0.1746 src/main/java src/main/resources/* - 0.8.5 + 0.8.8 - - - org.springframework.boot - spring-boot-starter-web - - - - org.yaml - snakeyaml - 2.0 - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-mail - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.kafka - spring-kafka - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - net.logstash.logback - logstash-logback-encoder - 6.3 - - - com.ibm.icu - icu4j - 68.2 - + + + org.springframework.boot + spring-boot-starter-web + + + + org.yaml + snakeyaml + 2.0 + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.kafka + spring-kafka + + + org.springframework.boot + spring-boot-configuration-processor + provided + true + + + net.logstash.logback + logstash-logback-encoder + 6.3 + + + com.ibm.icu + icu4j + 68.2 + - - org.keycloak - keycloak-spring-security-adapter - ${keycloak.version} - + + org.keycloak + keycloak-spring-security-adapter + ${keycloak.version} + - - org.projectlombok - lombok - ${lombok.version} - provided - - - com.google.code.findbugs - jsr305 - 3.0.2 - provided - + + org.projectlombok + lombok + ${lombok.version} + provided + + + com.google.code.findbugs + jsr305 + 3.0.2 + provided + - - org.apache.kafka - kafka-clients - - - - org.thymeleaf - thymeleaf - - - org.thymeleaf - thymeleaf-spring5 - - - org.thymeleaf.extras - thymeleaf-extras-java8time - - - org.bouncycastle - bcpkix-jdk15on - 1.70 - - - org.bouncycastle - bcprov-jdk15on - 1.70 - - - org.json - json - 20230227 - - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - - - com.github.erosb - everit-json-schema - 1.14.2 - - - com.auth0 - java-jwt - 4.2.1 - + + org.thymeleaf + thymeleaf + + + org.thymeleaf + thymeleaf-spring6 + + + org.thymeleaf.extras + thymeleaf-extras-java8time + 3.0.4.RELEASE + + + org.bouncycastle + bcpkix-jdk15on + 1.70 + + + org.bouncycastle + bcprov-jdk15on + 1.70 + + + org.json + json + 20230227 + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.github.erosb + everit-json-schema + 1.14.2 + + + com.auth0 + java-jwt + 4.2.1 + - - org.glassfish.jersey.inject - jersey-hk2 - - - jakarta.activation - jakarta.activation-api - - - org.jsoup - jsoup - 1.15.3 - + + org.glassfish.jersey.inject + jersey-hk2 + + + jakarta.activation + jakarta.activation-api + + + jakarta.mail + jakarta.mail-api + + + jakarta.servlet + jakarta.servlet-api + + + org.jsoup + jsoup + 1.15.3 + - - org.springframework.boot - spring-boot-starter-test - test - - - io.projectreactor - reactor-test - test - + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + jakarta.mail + jakarta.mail-api + test + + + org.glassfish.jaxb + jaxb-runtime + test + org.mockito mockito-core - 3.7.7 - test - - - org.junit.vintage - junit-vintage-engine + 4.11.0 test - - - org.hamcrest - hamcrest-core - - com.squareup.okhttp3 diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CleanupDeveloperAuthenticationsJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CleanupDeveloperAuthenticationsJob.java index 11609898..4b82726b 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CleanupDeveloperAuthenticationsJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CleanupDeveloperAuthenticationsJob.java @@ -2,7 +2,6 @@ import com.hermesworld.ais.galapagos.adminjobs.AdminJob; import com.hermesworld.ais.galapagos.devauth.DeveloperAuthenticationService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -11,7 +10,6 @@ public class CleanupDeveloperAuthenticationsJob implements AdminJob { private final DeveloperAuthenticationService developerAuthenticationService; - @Autowired public CleanupDeveloperAuthenticationsJob(DeveloperAuthenticationService developerAuthenticationService) { this.developerAuthenticationService = developerAuthenticationService; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJob.java index 0b069b17..80ff8425 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJob.java @@ -10,7 +10,6 @@ import com.hermesworld.ais.galapagos.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -25,7 +24,6 @@ public class CreateBackupJob implements AdminJob { private final ObjectMapper objectMapper = JsonUtil.newObjectMapper(); - @Autowired public CreateBackupJob(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/DeleteAclsJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/DeleteAclsJob.java index de328067..24fc3d6d 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/DeleteAclsJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/DeleteAclsJob.java @@ -8,10 +8,9 @@ import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.KafkaUser; import org.apache.kafka.common.acl.AclBinding; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; /** * Admin job to explicitly delete ACLs from a Kafka Cluster. This job is useful if something went terribly wrong with @@ -31,7 +30,6 @@ @Component public class DeleteAclsJob extends SingleClusterAdminJob { - @Autowired public DeleteAclsJob(KafkaClusters kafkaClusters) { super(kafkaClusters); } @@ -46,7 +44,7 @@ public void runOnCluster(KafkaCluster cluster, ApplicationArguments allArguments String certificateDn = Optional.ofNullable(allArguments.getOptionValues("certificate.dn")) .flatMap(ls -> ls.stream().findFirst()).orElse(null); - if (StringUtils.isEmpty(certificateDn)) { + if (ObjectUtils.isEmpty(certificateDn)) { throw new IllegalArgumentException("Please provide --certificate.dn= for DN of certificate."); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingApiKeyJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingApiKeyJob.java index e356819b..5f6b9e31 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingApiKeyJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingApiKeyJob.java @@ -13,7 +13,6 @@ import com.hermesworld.ais.galapagos.naming.ApplicationPrefixes; import com.hermesworld.ais.galapagos.naming.NamingService; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -42,7 +41,6 @@ public class GenerateToolingApiKeyJob extends SingleClusterAdminJob { private final AclSupport aclSupport; - @Autowired public GenerateToolingApiKeyJob(KafkaClusters kafkaClusters, AclSupport aclSupport, NamingService namingService, KafkaEnvironmentsConfig kafkaConfig) { super(kafkaClusters); diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJob.java index 27dd86e2..410db6df 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJob.java @@ -16,10 +16,9 @@ import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; @@ -57,7 +56,6 @@ public class GenerateToolingCertificateJob extends SingleClusterAdminJob { private final KafkaEnvironmentsConfig kafkaConfig; - @Autowired public GenerateToolingCertificateJob(KafkaClusters kafkaClusters, AclSupport aclSupport, NamingService namingService, KafkaEnvironmentsConfig kafkaConfig) { super(kafkaClusters); @@ -82,7 +80,7 @@ public void runOnCluster(KafkaCluster cluster, ApplicationArguments allArguments + " does not use certificates for authentication. Cannot generate tooling certificate."); } - if (!StringUtils.isEmpty(outputFilename)) { + if (!ObjectUtils.isEmpty(outputFilename)) { try { new FileOutputStream(outputFilename).close(); } @@ -122,7 +120,7 @@ public void runOnCluster(KafkaCluster cluster, ApplicationArguments allArguments cluster.updateUserAcls(new ToolingUser(toolMetadata, cluster.getId(), authModule, aclSupport)).get(); - if (!StringUtils.isEmpty(outputFilename)) { + if (!ObjectUtils.isEmpty(outputFilename)) { try (FileOutputStream fos = new FileOutputStream(outputFilename)) { fos.write(p12Data); } @@ -135,7 +133,7 @@ public void runOnCluster(KafkaCluster cluster, ApplicationArguments allArguments System.out.println(); System.out.println("==================== Galapagos Tooling Certificate CREATED ===================="); System.out.println(); - if (!StringUtils.isEmpty(outputFilename)) { + if (!ObjectUtils.isEmpty(outputFilename)) { System.out.println("You can now use the certificate in " + outputFilename + " for Galapagos external tooling on " + metadata.getName()); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJob.java index adb902d6..20ba5f51 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJob.java @@ -8,7 +8,6 @@ import com.hermesworld.ais.galapagos.util.HasKey; import com.hermesworld.ais.galapagos.util.JsonUtil; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; import org.springframework.util.StreamUtils; @@ -44,7 +43,6 @@ public class ImportBackupJob implements AdminJob { private final ObjectMapper objectMapper; - @Autowired public ImportBackupJob(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; this.objectMapper = JsonUtil.newObjectMapper(); diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJob.java index 1aeb34ff..5fada7ef 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJob.java @@ -19,11 +19,10 @@ import com.hermesworld.ais.galapagos.kafka.util.TopicBasedRepository; import com.hermesworld.ais.galapagos.util.JsonUtil; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; +import org.springframework.util.ObjectUtils; import org.springframework.util.StreamUtils; -import org.springframework.util.StringUtils; /** * Admin job to import known applications from a JSON file (or STDIN) to the global Galapagos topic @@ -46,7 +45,6 @@ public class ImportKnownApplicationsJob implements AdminJob { private KafkaClusters kafkaClusters; - @Autowired public ImportKnownApplicationsJob(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } @@ -65,7 +63,7 @@ public void run(ApplicationArguments allArguments) throws Exception { .map(ls -> ls.stream().findFirst().orElse(null)).map(s -> s == null ? false : Boolean.parseBoolean(s)) .orElse(false); - if (StringUtils.isEmpty(jsonFile)) { + if (ObjectUtils.isEmpty(jsonFile)) { throw new IllegalArgumentException("Please provide --applications.import.file= for JSON to import"); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/MarkTopicApprovalRequiredJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/MarkTopicApprovalRequiredJob.java index dec55bac..64bb1940 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/MarkTopicApprovalRequiredJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/MarkTopicApprovalRequiredJob.java @@ -7,7 +7,6 @@ import com.hermesworld.ais.galapagos.adminjobs.AdminJob; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.topics.service.TopicService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -19,7 +18,6 @@ public class MarkTopicApprovalRequiredJob implements AdminJob { private final TopicService topicService; - @Autowired public MarkTopicApprovalRequiredJob(KafkaClusters kafkaClusters, @Qualifier("nonvalidating") TopicService topicService) { this.kafkaClusters = kafkaClusters; diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ResetApplicationPrefixesJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ResetApplicationPrefixesJob.java index 1c4027f4..8ee15462 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ResetApplicationPrefixesJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ResetApplicationPrefixesJob.java @@ -4,7 +4,6 @@ import com.hermesworld.ais.galapagos.kafka.KafkaCluster; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.util.AclSupport; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -44,7 +43,6 @@ public class ResetApplicationPrefixesJob extends SingleClusterAdminJob { private final AclSupport aclSupport; - @Autowired public ResetApplicationPrefixesJob(KafkaClusters kafkaClusters, ApplicationsService applicationsService, AclSupport aclSupport) { super(kafkaClusters); diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateApplicationAclsJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateApplicationAclsJob.java index f9b7b5ef..14cd8692 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateApplicationAclsJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateApplicationAclsJob.java @@ -14,7 +14,6 @@ import org.apache.kafka.common.acl.AclBinding; import org.apache.kafka.common.acl.AclBindingFilter; import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @@ -47,7 +46,6 @@ public class UpdateApplicationAclsJob extends SingleClusterAdminJob { private final ApplicationsService applicationsService; - @Autowired public UpdateApplicationAclsJob(KafkaClusters kafkaClusters, AclSupport aclSupport, ApplicationsService applicationsService) { super(kafkaClusters); diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateConfluentAuthMetadataJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateConfluentAuthMetadataJob.java index 74498ca2..a66349d7 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateConfluentAuthMetadataJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/UpdateConfluentAuthMetadataJob.java @@ -11,7 +11,6 @@ import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import com.hermesworld.ais.galapagos.kafka.util.TopicBasedRepository; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -26,7 +25,6 @@ public class UpdateConfluentAuthMetadataJob implements AdminJob { private final DeveloperAuthenticationService devAuthService; - @Autowired public UpdateConfluentAuthMetadataJob(KafkaClusters kafkaClusters, ApplicationsService applicationsService, DeveloperAuthenticationService devAuthService) { this.kafkaClusters = kafkaClusters; diff --git a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJob.java b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJob.java index e697f3da..68939694 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJob.java +++ b/src/main/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJob.java @@ -5,7 +5,6 @@ import org.apache.kafka.common.acl.AclBinding; import org.json.JSONArray; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @@ -24,7 +23,6 @@ @Component public class ViewAclsJob extends SingleClusterAdminJob { - @Autowired public ViewAclsJob(KafkaClusters kafkaClusters) { super(kafkaClusters); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsController.java b/src/main/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsController.java index b13b1104..23956fa8 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsController.java @@ -17,10 +17,10 @@ import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @@ -43,7 +43,6 @@ public class ApplicationsController { private final KafkaClusters kafkaClusters; - @Autowired public ApplicationsController(ApplicationsService applicationsService, StagingService stagingService, KafkaClusters kafkaClusters) { this.applicationsService = applicationsService; @@ -53,7 +52,7 @@ public ApplicationsController(ApplicationsService applicationsService, StagingSe @GetMapping(value = "/api/applications", produces = MediaType.APPLICATION_JSON_VALUE) public List listApplications( - @RequestParam(name = "excludeUserApps", required = false, defaultValue = "false") boolean excludeUserApps) { + @RequestParam(required = false, defaultValue = "false") boolean excludeUserApps) { return applicationsService.getKnownApplications(excludeUserApps).stream().map(app -> toKnownAppDto(app)) .collect(Collectors.toList()); } @@ -159,7 +158,7 @@ public CertificateResponseDto updateApplicationCertificate(@PathVariable String String filename = CertificateUtil.toAppCn(app.getName()) + "_" + environmentId; if (!request.isGenerateKey()) { String csrData = request.getCsrData(); - if (StringUtils.isEmpty(csrData)) { + if (ObjectUtils.isEmpty(csrData)) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No CSR (csrData) present! Set generateKey to true if you want the server to generate a private key for you (not recommended)."); } @@ -211,7 +210,7 @@ public CreatedApiKeyDto createApiKeyForApplication(@PathVariable String environm try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - JSONObject params = StringUtils.isEmpty(request) ? new JSONObject() : new JSONObject(request); + JSONObject params = ObjectUtils.isEmpty(request) ? new JSONObject() : new JSONObject(request); ApplicationMetadata metadata = applicationsService .registerApplicationOnEnvironment(environmentId, applicationId, params, baos).get(); CreatedApiKeyDto dto = new CreatedApiKeyDto(); @@ -279,7 +278,7 @@ public List performStaging(@PathVariable String environmentId, @P } List stagingFilter = null; - if (!StringUtils.isEmpty(stagingFilterRaw)) { + if (!ObjectUtils.isEmpty(stagingFilterRaw)) { try { stagingFilter = JsonUtil.newObjectMapper().readValue(stagingFilterRaw, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, Change.class)); diff --git a/src/main/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImpl.java index 8085a614..2bcda47a 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImpl.java @@ -15,9 +15,9 @@ import com.hermesworld.ais.galapagos.util.TimeService; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import java.io.IOException; @@ -55,7 +55,6 @@ public class ApplicationsServiceImpl implements ApplicationsService, InitPerClus private static final Comparator requestComparator = (r1, r2) -> r2.getLastStatusChangeAt() .compareTo(r1.getLastStatusChangeAt()); - @Autowired public ApplicationsServiceImpl(KafkaClusters kafkaClusters, CurrentUserService currentUserService, TimeService timeService, NamingService namingService, GalapagosEventManager eventManager) { this.kafkaClusters = kafkaClusters; @@ -257,7 +256,7 @@ public CompletableFuture registerApplicationOnEnvironment(S if (existing != null) { String json = existing.getAuthenticationJson(); - if (!StringUtils.isEmpty(json)) { + if (!ObjectUtils.isEmpty(json)) { updateOrCreateFuture = authModule.updateApplicationAuthentication(applicationId, applicationName, registerParams, new JSONObject(json)); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListener.java b/src/main/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListener.java index 6e38fe0a..ff971a84 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListener.java +++ b/src/main/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListener.java @@ -22,7 +22,6 @@ import org.json.JSONException; import org.json.JSONObject; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.thymeleaf.util.StringUtils; @@ -44,7 +43,6 @@ public class UpdateApplicationAclsListener private final AclSupport aclSupport; - @Autowired public UpdateApplicationAclsListener(KafkaClusters kafkaClusters, SubscriptionService subscriptionService, ApplicationsService applicationsService, AclSupport aclSupport) { this.kafkaClusters = kafkaClusters; diff --git a/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationModule.java b/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationModule.java index 6d7eb7dc..b4c50e97 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationModule.java +++ b/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationModule.java @@ -11,6 +11,7 @@ import org.bouncycastle.pkcs.PKCSException; import org.json.JSONException; import org.json.JSONObject; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import java.io.*; @@ -89,7 +90,7 @@ public CompletableFuture updateApplicationAuthentica if (extendCertificate) { dn = existingAuthData.optString(DN); - if (StringUtils.isEmpty(dn)) { + if (ObjectUtils.isEmpty(dn)) { return CompletableFuture.failedFuture(new IllegalArgumentException( "Cannot extend certificate - no certificate information available for application")); } @@ -106,7 +107,7 @@ private CompletableFuture createOrUpdateApplicationA if (!generateKey) { String csr = createParameters.optString("csrData"); - if (StringUtils.isEmpty(csr)) { + if (ObjectUtils.isEmpty(csr)) { return CompletableFuture.failedFuture(new IllegalArgumentException( "No CSR (csrData) present! Set generateKey to true if you want the server to generate a private key for you (not recommended).")); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/certificates/controller/TrustStoreController.java b/src/main/java/com/hermesworld/ais/galapagos/certificates/controller/TrustStoreController.java index 1e7a816f..75383aa4 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/certificates/controller/TrustStoreController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/certificates/controller/TrustStoreController.java @@ -4,12 +4,11 @@ import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.common.config.SslConfigs; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.util.ObjectUtils; import org.springframework.util.StreamUtils; -import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @@ -29,7 +28,6 @@ public class TrustStoreController { private final Supplier notFound = () -> new ResponseStatusException(HttpStatus.NOT_FOUND); - @Autowired public TrustStoreController(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } @@ -49,7 +47,7 @@ public ResponseEntity getTrustStore(@PathVariable String environmentId) module.addRequiredKafkaProperties(props); String trustStoreLocation = props.getProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG); - if (StringUtils.isEmpty(trustStoreLocation)) { + if (ObjectUtils.isEmpty(trustStoreLocation)) { throw notFound.get(); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunner.java b/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunner.java index 874c63db..775bf7fd 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunner.java +++ b/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunner.java @@ -11,7 +11,6 @@ import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -45,7 +44,6 @@ public class CertificateExpiryReminderRunner { private final String timezone; - @Autowired public CertificateExpiryReminderRunner(CertificateExpiryReminderService reminderService, NotificationService notificationService, ApplicationsService applicationsService, KafkaClusters kafkaClusters, @Value("${galapagos.timezone:GMT}") String timezone) { diff --git a/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceImpl.java index 567a5683..a3e9239e 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceImpl.java @@ -14,7 +14,6 @@ import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -31,7 +30,6 @@ public class CertificateExpiryReminderServiceImpl implements CertificateExpiryRe private static final String REPOSITORY_NAME = "reminders"; - @Autowired public CertificateExpiryReminderServiceImpl(KafkaClusters kafkaClusters, ApplicationsService applicationsService) { this.kafkaClusters = kafkaClusters; this.applicationsService = applicationsService; diff --git a/src/main/java/com/hermesworld/ais/galapagos/changes/controller/ChangesController.java b/src/main/java/com/hermesworld/ais/galapagos/changes/controller/ChangesController.java index 525ddcad..bf659649 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/changes/controller/ChangesController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/changes/controller/ChangesController.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; @@ -17,7 +16,6 @@ public class ChangesController { private ChangesService changesService; - @Autowired public ChangesController(ChangesService changesService) { this.changesService = changesService; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImpl.java index c6ae3383..9df5910a 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImpl.java @@ -13,7 +13,6 @@ import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.util.JsonUtil; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.time.ZonedDateTime; @@ -31,7 +30,6 @@ public class ChangesServiceImpl private final KafkaClusters kafkaClusters; - @Autowired public ChangesServiceImpl(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImpl.java index aede819e..a949a30d 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImpl.java @@ -13,12 +13,14 @@ import com.hermesworld.ais.galapagos.util.TimeService; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.OutputStream; -import java.util.*; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -35,7 +37,6 @@ public class DeveloperAuthenticationServiceImpl implements DeveloperAuthenticati private final TimeService timeService; - @Autowired public DeveloperAuthenticationServiceImpl(KafkaClusters kafkaClusters, CurrentUserService currentUserService, DevUserAclListener aclUpdater, TimeService timeService) { this.kafkaClusters = kafkaClusters; @@ -70,12 +71,9 @@ public CompletableFuture createDeveloperAuthenticatio TopicBasedRepository repository = getRepository(cluster); - CompletableFuture removeFuture = repository - .getObject( - userName) - .map(oldMeta -> aclUpdater.removeAcls(cluster, Collections.singleton(oldMeta)) - .thenCompose(o -> authModule.deleteDeveloperAuthentication(userName, - new JSONObject(oldMeta.getAuthenticationJson())))) + CompletableFuture removeFuture = repository.getObject(userName) + .map(oldMeta -> aclUpdater.removeAcls(cluster, Set.of(oldMeta)).thenCompose(o -> authModule + .deleteDeveloperAuthentication(userName, new JSONObject(oldMeta.getAuthenticationJson())))) .orElse(FutureUtil.noop()); return removeFuture.thenCompose(o -> authModule.createDeveloperAuthentication(userName, new JSONObject())) @@ -95,7 +93,7 @@ public CompletableFuture createDeveloperAuthenticatio return meta; }).thenCompose(meta -> meta == null ? CompletableFuture.failedFuture(new NoSuchElementException("No authentication received")) - : aclUpdater.updateAcls(cluster, Collections.singleton(meta)) + : aclUpdater.updateAcls(cluster, Set.of(meta)) .thenCompose(o -> clearExpiredDeveloperAuthenticationsOnAllClusters()) .thenApply(o -> meta))); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/events/impl/GalapagosEventManagerImpl.java b/src/main/java/com/hermesworld/ais/galapagos/events/impl/GalapagosEventManagerImpl.java index 1aa721b3..d9022d48 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/events/impl/GalapagosEventManagerImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/events/impl/GalapagosEventManagerImpl.java @@ -9,7 +9,6 @@ import com.hermesworld.ais.galapagos.topics.SchemaMetadata; import com.hermesworld.ais.galapagos.topics.TopicMetadata; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @@ -28,7 +27,6 @@ public class GalapagosEventManagerImpl implements GalapagosEventManager { private final List contextSources; - @Autowired public GalapagosEventManagerImpl(@Lazy List topicListeners, @Lazy List subscriptionListeners, @Lazy List applicationListeners, @Lazy List contextSources) { diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/controller/EnvironmentsController.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/controller/EnvironmentsController.java index f92b5d16..f4299629 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/controller/EnvironmentsController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/controller/EnvironmentsController.java @@ -2,7 +2,6 @@ import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.config.KafkaEnvironmentConfig; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -17,7 +16,6 @@ public class EnvironmentsController { private final KafkaClusters kafkaEnvironments; - @Autowired public EnvironmentsController(KafkaClusters kafkaEnvironments) { this.kafkaEnvironments = kafkaEnvironments; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaCluster.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaCluster.java index 04e7f85b..3154f48d 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaCluster.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaCluster.java @@ -24,7 +24,7 @@ import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourcePatternFilter; import org.apache.kafka.common.resource.ResourceType; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; import java.time.Duration; import java.util.*; @@ -101,8 +101,8 @@ public CompletableFuture removeUserAcls(KafkaUser user) { if (user.getKafkaUserName() == null) { return FutureUtil.noop(); } - return toCompletableFuture(adminClient - .deleteAcls(Collections.singletonList(userAclFilter(user.getKafkaUserName(), ResourceType.ANY))).all()) + return toCompletableFuture( + adminClient.deleteAcls(List.of(userAclFilter(user.getKafkaUserName(), ResourceType.ANY))).all()) .thenApply(o -> null); } @@ -134,7 +134,7 @@ public CompletableFuture createTopic(String topicName, TopicCreateParams t NewTopic newTopic = new NewTopic(topicName, topicCreateParams.getNumberOfPartitions(), (short) topicCreateParams.getReplicationFactor()).configs(topicCreateParams.getTopicConfigs()); - return toCompletableFuture(this.adminClient.createTopics(Collections.singleton(newTopic)).all()); + return toCompletableFuture(this.adminClient.createTopics(Set.of(newTopic)).all()); } @Override @@ -143,10 +143,10 @@ public CompletableFuture deleteTopic(String topicName) { new ResourcePatternFilter(ResourceType.TOPIC, topicName, PatternType.LITERAL), new AccessControlEntryFilter(null, null, AclOperation.ANY, AclPermissionType.ANY)); - KafkaFuture deleteTopicFuture = this.adminClient.deleteTopics(Collections.singleton(topicName)).all(); + KafkaFuture deleteTopicFuture = this.adminClient.deleteTopics(Set.of(topicName)).all(); return toCompletableFuture(deleteTopicFuture) - .thenCompose(o -> toCompletableFuture(adminClient.deleteAcls(Collections.singleton(aclFilter)).all())) + .thenCompose(o -> toCompletableFuture(adminClient.deleteAcls(Set.of(aclFilter)).all())) .thenApply(o -> null); } @@ -154,7 +154,7 @@ public CompletableFuture deleteTopic(String topicName) { public CompletableFuture> getTopicConfig(String topicName) { ConfigResource cres = new ConfigResource(ConfigResource.Type.TOPIC, topicName); - return toCompletableFuture(adminClient.describeConfigs(Collections.singleton(cres)).all()) + return toCompletableFuture(adminClient.describeConfigs(Set.of(cres)).all()) .thenApply(map -> map.getOrDefault(cres, new Config(Collections.emptyList())).entries().stream() .map(entry -> new TopicConfigEntryImpl(entry)).collect(Collectors.toSet())); } @@ -165,11 +165,10 @@ public CompletableFuture> getDefaultTopicConfig() { if (nodes.isEmpty()) { return CompletableFuture.failedFuture(new KafkaException("No nodes in cluster")); } - return toCompletableFuture( - adminClient - .describeConfigs(Collections.singleton( - new ConfigResource(ConfigResource.Type.BROKER, "" + nodes.iterator().next().id()))) - .all()); + return toCompletableFuture(adminClient + .describeConfigs( + Set.of(new ConfigResource(ConfigResource.Type.BROKER, "" + nodes.iterator().next().id()))) + .all()); }).thenApply(map -> KafkaTopicConfigHelper.getTopicDefaultValues(map.values().iterator().next())); } @@ -179,9 +178,7 @@ public CompletableFuture setTopicConfig(String topicName, Map getActiveBrokerCount() { @Override public CompletableFuture buildTopicCreateParams(String topicName) { - return toCompletableFuture(adminClient.describeTopics(Collections.singleton(topicName)).all()) + return toCompletableFuture(adminClient.describeTopics(Set.of(topicName)).all()) .thenCompose(map -> buildCreateTopicParams(map.get(topicName))); } @@ -203,7 +200,7 @@ public CompletableFuture>> peekTopicData(Str Runnable r = () -> { KafkaConsumer consumer = kafkaConsumerFactory.newConsumer(); - consumer.subscribe(Collections.singleton(topicName), new ConsumerRebalanceListener() { + consumer.subscribe(Set.of(topicName), new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection partitions) { } @@ -267,7 +264,7 @@ private CompletableFuture buildCreateTopicParams(TopicDescrip } private CompletableFuture> getUserAcls(String username) { - if (StringUtils.isEmpty(username)) { + if (ObjectUtils.isEmpty(username)) { return CompletableFuture.completedFuture(List.of()); } return toCompletableFuture(adminClient.describeAcls(userAclFilter(username, ResourceType.ANY)).values()); @@ -291,7 +288,7 @@ public CompletableFuture getKafkaServerVersion() { String nodeName = coll.iterator().next().idString(); return toCompletableFuture(adminClient.describeConfigs( - Collections.singleton(new ConfigResource(Type.BROKER, nodeName))).all()).thenApply(map -> map + Set.of(new ConfigResource(Type.BROKER, nodeName))).all()).thenApply(map -> map .values().stream() .map(config -> config.get("inter.broker.protocol.version") == null ? "UNKNOWN_VERSION" : config.get("inter.broker.protocol.version").value()) diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusters.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusters.java index 609b2a93..64d5a29e 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusters.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusters.java @@ -7,7 +7,7 @@ import com.hermesworld.ais.galapagos.kafka.config.KafkaEnvironmentConfig; import com.hermesworld.ais.galapagos.kafka.util.TopicBasedRepository; import com.hermesworld.ais.galapagos.util.HasKey; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -81,7 +81,7 @@ public String getProductionEnvironmentId() { @Override public Optional getEnvironment(String environmentId) { - if (StringUtils.isEmpty(environmentId)) { + if (ObjectUtils.isEmpty(environmentId)) { return Optional.empty(); } return Optional.ofNullable(clusters.get(environmentId)); diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaConnectionManager.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaConnectionManager.java index 61d6243a..0262b00d 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaConnectionManager.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaConnectionManager.java @@ -115,7 +115,7 @@ private KafkaSenderImpl buildKafkaSender(KafkaEnvironmentConfig environment, props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1"); ProducerFactory factory = new DefaultKafkaProducerFactory<>(toMap(props)); - return new KafkaSenderImpl(new KafkaTemplate<>(factory), futureDecoupler); + return new KafkaSenderImpl(new KafkaTemplate<>(factory)); } private Properties buildKafkaProperties(KafkaEnvironmentConfig environment, diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaRepositoryContainerImpl.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaRepositoryContainerImpl.java index f1901e48..b65f7f32 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaRepositoryContainerImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaRepositoryContainerImpl.java @@ -24,6 +24,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -111,7 +112,7 @@ private void ensureTopicExists(String topic) { Map desc; try { - desc = this.adminClient.describeTopics(Collections.singleton(topic)).all().get(); + desc = this.adminClient.describeTopics(Set.of(topic)).all().get(); } catch (Exception e) { desc = Collections.emptyMap(); @@ -125,7 +126,7 @@ private void ensureTopicExists(String topic) { NewTopic newTopic = new NewTopic(topic, 1, (short) replicationFactor); newTopic = newTopic .configs(Map.of(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT)); - this.adminClient.createTopics(Collections.singleton(newTopic)).all().get(); + this.adminClient.createTopics(Set.of(newTopic)).all().get(); } } catch (InterruptedException e) { diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImpl.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImpl.java index a602d2ab..3a474e9c 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImpl.java @@ -17,17 +17,13 @@ public class KafkaSenderImpl implements KafkaSender { private KafkaTemplate kafkaTemplate; - private KafkaFutureDecoupler futureDecoupler; - - public KafkaSenderImpl(KafkaTemplate template, KafkaFutureDecoupler futureDecoupler) { + public KafkaSenderImpl(KafkaTemplate template) { this.kafkaTemplate = template; - this.futureDecoupler = futureDecoupler; } @Override public CompletableFuture send(String topic, String key, String message) { - return futureDecoupler.toCompletableFuture(kafkaTemplate.send(new ProducerRecord<>(topic, key, message))) - .thenApply(o -> null); + return kafkaTemplate.send(new ProducerRecord<>(topic, key, message)).thenApply(o -> null); } } diff --git a/src/main/java/com/hermesworld/ais/galapagos/kafka/util/KafkaTopicConfigHelper.java b/src/main/java/com/hermesworld/ais/galapagos/kafka/util/KafkaTopicConfigHelper.java index a27fe952..819417cb 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/kafka/util/KafkaTopicConfigHelper.java +++ b/src/main/java/com/hermesworld/ais/galapagos/kafka/util/KafkaTopicConfigHelper.java @@ -1,7 +1,6 @@ package com.hermesworld.ais.galapagos.kafka.util; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -87,9 +86,9 @@ public class KafkaTopicConfigHelper { .valueOf(TimeUnit.MINUTES.toMillis(Long.valueOf(minutes, 10)))), new SecondaryServerProp("log.retention.hours", hoursToMillis))); SECONDARY_SERVER_PROPS.put(TopicConfig.SEGMENT_MS_CONFIG, - Collections.singletonList(new SecondaryServerProp("log.roll.hours", hoursToMillis))); + List.of(new SecondaryServerProp("log.roll.hours", hoursToMillis))); SECONDARY_SERVER_PROPS.put(TopicConfig.SEGMENT_JITTER_MS_CONFIG, - Collections.singletonList(new SecondaryServerProp("log.roll.jitter.hours", hoursToMillis))); + List.of(new SecondaryServerProp("log.roll.jitter.hours", hoursToMillis))); } private KafkaTopicConfigHelper() { diff --git a/src/main/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategy.java b/src/main/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategy.java index 70c3465b..d9a457b5 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategy.java +++ b/src/main/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategy.java @@ -1,5 +1,6 @@ package com.hermesworld.ais.galapagos.naming.config; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import java.util.List; @@ -45,7 +46,7 @@ public String configValue() { } public boolean matches(String input) { - if (StringUtils.isEmpty(input)) { + if (ObjectUtils.isEmpty(input)) { return false; } return input.matches(validatorRegex); diff --git a/src/main/java/com/hermesworld/ais/galapagos/naming/config/NamingConfig.java b/src/main/java/com/hermesworld/ais/galapagos/naming/config/NamingConfig.java index 66920ddc..4a26b54a 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/naming/config/NamingConfig.java +++ b/src/main/java/com/hermesworld/ais/galapagos/naming/config/NamingConfig.java @@ -52,8 +52,7 @@ public void validate(@NonNull Object target, @NonNull Errors errors) { if (target instanceof String && objName.endsWith("-format")) { checkValidFormat(target.toString(), errors); } - else if (target instanceof AdditionNamingRules) { - AdditionNamingRules rules = (AdditionNamingRules) target; + else if (target instanceof AdditionNamingRules rules) { if (!StringUtils.isEmpty(rules.getAllowedSeparators()) && !rules.getAllowedSeparators().matches(KAFKA_VALID_NAMES_REGEX)) { errors.rejectValue("allowedSeparators", "invalid.value", diff --git a/src/main/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImpl.java index 1b35b8be..070f9088 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImpl.java @@ -11,7 +11,6 @@ import com.hermesworld.ais.galapagos.naming.config.TopicNamingConfig; import com.hermesworld.ais.galapagos.topics.TopicType; import com.ibm.icu.text.Transliterator; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -28,7 +27,6 @@ public class NamingServiceImpl implements NamingService { private final NamingConfig config; - @Autowired public NamingServiceImpl(NamingConfig config) { this.config = config; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/MailConfig.java b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/MailConfig.java index 25afb2ad..a6b8def6 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/MailConfig.java +++ b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/MailConfig.java @@ -4,7 +4,7 @@ import org.springframework.context.annotation.Configuration; import org.thymeleaf.TemplateEngine; import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; -import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring6.SpringTemplateEngine; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.thymeleaf.templateresolver.ITemplateResolver; diff --git a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListener.java b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListener.java index 430270d0..6a1ec806 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListener.java +++ b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListener.java @@ -13,12 +13,11 @@ import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.FutureUtil; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; @@ -60,7 +59,6 @@ public class NotificationEventListener private static final String IS_ADMIN_KEY = NotificationEventListener.class.getName() + "_isAdmin"; - @Autowired public NotificationEventListener(NotificationService notificationService, ApplicationsService applicationsService, TopicService topicService, CurrentUserService userService, KafkaClusters kafkaClusters) { this.notificationService = notificationService; diff --git a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImpl.java index 93bb76fe..72ae08ef 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImpl.java @@ -11,7 +11,6 @@ import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.task.TaskExecutor; @@ -19,14 +18,15 @@ import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.thymeleaf.ITemplateEngine; import org.thymeleaf.context.Context; -import javax.mail.MessagingException; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.AddressException; +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeMessage; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @@ -51,7 +51,6 @@ public class NotificationServiceImpl implements NotificationService { private final List adminMailRecipients; - @Autowired public NotificationServiceImpl(SubscriptionService subscriptionService, ApplicationsService applicationsService, TopicService topicService, JavaMailSender mailSender, TaskExecutor taskExecutor, @Qualifier("emailTemplateEngine") ITemplateEngine templateEngine, @@ -236,7 +235,7 @@ private List safeToRecipientsList(Collection recipients } private static List toRecipientsList(String recipients) throws AddressException { - if (StringUtils.isEmpty(recipients)) { + if (ObjectUtils.isEmpty(recipients)) { return Collections.emptyList(); } diff --git a/src/main/java/com/hermesworld/ais/galapagos/schemas/SchemaUtil.java b/src/main/java/com/hermesworld/ais/galapagos/schemas/SchemaUtil.java index 85493d5a..f5a49252 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/schemas/SchemaUtil.java +++ b/src/main/java/com/hermesworld/ais/galapagos/schemas/SchemaUtil.java @@ -89,8 +89,10 @@ else if (newSchema.getClass() == NullSchema.class || newSchema.getClass() == Boo private static void verifyCompatibleTo(ObjectSchema oldSchema, ObjectSchema newSchema, String prefix) throws IncompatibleSchemaException { if (!oldSchema.permitsAdditionalProperties() && newSchema.permitsAdditionalProperties()) { - throw new IncompatibleSchemaException("additionalProperties must not be introduced " - + "in a newer schema version (old consumers could rely on no additional properties being present)"); + throw new IncompatibleSchemaException(""" + additionalProperties must not be introduced \ + in a newer schema version (old consumers could rely on no additional properties being present)\ + """); } // required properties must still be required diff --git a/src/main/java/com/hermesworld/ais/galapagos/security/SecurityConfig.java b/src/main/java/com/hermesworld/ais/galapagos/security/SecurityConfig.java index e3e61aaa..2f4fa1df 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/security/SecurityConfig.java +++ b/src/main/java/com/hermesworld/ais/galapagos/security/SecurityConfig.java @@ -12,99 +12,103 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; import org.springframework.web.context.request.RequestContextListener; -@KeycloakConfiguration -@EnableGlobalMethodSecurity(securedEnabled = true) -public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { +//@Configuration +//@KeycloakConfiguration +//@EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) +public class SecurityConfig { /** * Registers the KeycloakAuthenticationProvider with the authentication manager. */ - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider(); - SimpleAuthorityMapper mapper = new SimpleAuthorityMapper(); - mapper.setConvertToUpperCase(true); - mapper.setConvertToLowerCase(false); - provider.setGrantedAuthoritiesMapper(mapper); - auth.authenticationProvider(provider); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); - // TODO is CSRF necessary for a stateless backend without sessions? - http.csrf().disable(); - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); - http.authorizeRequests().antMatchers("/api/**").hasRole("USER").anyRequest().permitAll(); - } - - // The following four beans shall avoid a double registration of the Keycloak filters. - // See https://www.keycloak.org/docs/latest/securing_apps/index.html#spring-boot-integration for details. - // (Google Keywords: keycloak "avoid double bean registration") - - @Bean - public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean( - KeycloakAuthenticationProcessingFilter filter) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( - filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - @Bean - public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean( - KeycloakPreAuthActionsFilter filter) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - @Bean - public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean( - KeycloakAuthenticatedActionsFilter filter) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( - filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - @Bean - public FilterRegistrationBean keycloakSecurityContextRequestFilterBean( - KeycloakSecurityContextRequestFilter filter) { - FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( - filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - @Override - @Bean - @ConditionalOnMissingBean(HttpSessionManager.class) - protected HttpSessionManager httpSessionManager() { - // this method only exists for the @ConditionalOnMissingBean annotation, which is missing from the base class. - return super.httpSessionManager(); - } - - @Bean - public RequestContextListener requestContextListener() { - return new RequestContextListener(); - } - - @Override - protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { - // this makes sure that no JSESSIONID cookie is sent. Keycloak authentication of the token is done with each - // request, as - // it should be. - return new NullAuthenticatedSessionStrategy(); - } +// @Autowired +// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { +// KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider(); +// SimpleAuthorityMapper mapper = new SimpleAuthorityMapper(); +// mapper.setConvertToUpperCase(true); +// mapper.setConvertToLowerCase(false); +// provider.setGrantedAuthoritiesMapper(mapper); +// auth.authenticationProvider(provider); +// } +// +// @Bean +// SecurityFilterChain filterChain(HttpSecurity http) throws Exception { +// super.configure(http); +// // TODO is CSRF necessary for a stateless backend without sessions? +// http.csrf().disable(); +// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); +// http.authorizeRequests().antMatchers("/api/**").hasRole("USER").anyRequest().permitAll(); +// return http.build(); +// } +// +// // The following four beans shall avoid a double registration of the Keycloak filters. +// // See https://www.keycloak.org/docs/latest/securing_apps/index.html#spring-boot-integration for details. +// // (Google Keywords: keycloak "avoid double bean registration") +// +// @Bean +// public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean( +// KeycloakAuthenticationProcessingFilter filter) { +// FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( +// filter); +// registrationBean.setEnabled(false); +// return registrationBean; +// } +// +// @Bean +// public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean( +// KeycloakPreAuthActionsFilter filter) { +// FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(filter); +// registrationBean.setEnabled(false); +// return registrationBean; +// } +// +// @Bean +// public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean( +// KeycloakAuthenticatedActionsFilter filter) { +// FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( +// filter); +// registrationBean.setEnabled(false); +// return registrationBean; +// } +// +// @Bean +// public FilterRegistrationBean keycloakSecurityContextRequestFilterBean( +// KeycloakSecurityContextRequestFilter filter) { +// FilterRegistrationBean registrationBean = new FilterRegistrationBean<>( +// filter); +// registrationBean.setEnabled(false); +// return registrationBean; +// } +// +// @Override +// @Bean +// @ConditionalOnMissingBean(HttpSessionManager.class) +// protected HttpSessionManager httpSessionManager() { +// // this method only exists for the @ConditionalOnMissingBean annotation, which is missing from the base class. +// return super.httpSessionManager(); +// } +// +// @Bean +// public RequestContextListener requestContextListener() { +// return new RequestContextListener(); +// } +// +// @Override +// protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { +// // this makes sure that no JSESSIONID cookie is sent. Keycloak authentication of the token is done with each +// // request, as +// // it should be. +// return new NullAuthenticatedSessionStrategy(); +// } } \ No newline at end of file diff --git a/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventRepositoryImpl.java b/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventRepositoryImpl.java index 90c14351..7e502e22 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventRepositoryImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventRepositoryImpl.java @@ -17,7 +17,7 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Collections; import java.util.HashMap; diff --git a/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventsListener.java b/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventsListener.java index f49c1c56..65fab8a2 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventsListener.java +++ b/src/main/java/com/hermesworld/ais/galapagos/security/impl/AuditEventsListener.java @@ -7,7 +7,6 @@ import com.hermesworld.ais.galapagos.subscriptions.SubscriptionMetadata; import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.util.FutureUtil; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.actuate.audit.AuditEventRepository; import org.springframework.stereotype.Component; @@ -27,7 +26,6 @@ public class AuditEventsListener implements TopicEventsListener, SubscriptionEve private static final String NAME = "name"; - @Autowired public AuditEventsListener(AuditEventRepository auditRepository) { this.auditRepository = auditRepository; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/security/impl/DefaultCurrentUserService.java b/src/main/java/com/hermesworld/ais/galapagos/security/impl/DefaultCurrentUserService.java index 18cbee5e..d2628fb0 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/security/impl/DefaultCurrentUserService.java +++ b/src/main/java/com/hermesworld/ais/galapagos/security/impl/DefaultCurrentUserService.java @@ -9,7 +9,7 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; +import org.springframework.util.ObjectUtils; import java.util.HashMap; import java.util.Map; @@ -36,7 +36,7 @@ public Optional getCurrentPrincipal() { @Override public Optional getCurrentUserEmailAddress() { return getKeycloakIDToken().map(token -> token.getEmail()) - .flatMap(s -> StringUtils.isEmpty(s) ? Optional.empty() : Optional.of(s)); + .flatMap(s -> ObjectUtils.isEmpty(s) ? Optional.empty() : Optional.of(s)); } private Optional getKeycloakIDToken() { diff --git a/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingServiceImpl.java index 30e03fa3..5c558da1 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingServiceImpl.java @@ -8,7 +8,6 @@ import com.hermesworld.ais.galapagos.staging.StagingService; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.topics.service.TopicService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @@ -26,7 +25,6 @@ public class StagingServiceImpl implements StagingService { private final SubscriptionService subscriptionService; - @Autowired public StagingServiceImpl(KafkaClusters kafkaClusters, ApplicationsService applicationsService, @Qualifier("nonvalidating") TopicService topicService, SubscriptionService subscriptionService) { this.kafkaClusters = kafkaClusters; diff --git a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/controller/SubscriptionsController.java b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/controller/SubscriptionsController.java index c025af77..0d66d407 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/controller/SubscriptionsController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/controller/SubscriptionsController.java @@ -14,7 +14,6 @@ import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.service.TopicService; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; @@ -34,7 +33,6 @@ public class SubscriptionsController { private final Supplier notFound = () -> new ResponseStatusException(HttpStatus.NOT_FOUND); - @Autowired public SubscriptionsController(SubscriptionService subscriptionService, ApplicationsService applicationsService, TopicService topicService, KafkaClusters kafkaEnvironments) { this.subscriptionService = subscriptionService; @@ -45,8 +43,7 @@ public SubscriptionsController(SubscriptionService subscriptionService, Applicat @GetMapping(value = "/api/applications/{applicationId}/subscriptions/{environmentId}", produces = MediaType.APPLICATION_JSON_VALUE) public List getApplicationSubscriptions(@PathVariable String applicationId, - @PathVariable String environmentId, - @RequestParam(name = "includeNonApproved", defaultValue = "false") boolean includeNonApproved) { + @PathVariable String environmentId, @RequestParam(defaultValue = "false") boolean includeNonApproved) { applicationsService.getKnownApplication(applicationId).orElseThrow(notFound); kafkaEnvironments.getEnvironmentMetadata(environmentId).orElseThrow(notFound); return subscriptionService.getSubscriptionsOfApplication(environmentId, applicationId, includeNonApproved) @@ -134,8 +131,7 @@ public void deleteApplicationSubscription(@PathVariable String applicationId, @P @GetMapping(value = "/api/topics/{environmentId}/{topicName}/subscriptions", produces = MediaType.APPLICATION_JSON_VALUE) public List getTopicSubscriptions(@PathVariable String environmentId, - @PathVariable String topicName, - @RequestParam(name = "includeNonApproved", defaultValue = "false") boolean includeNonApproved) { + @PathVariable String topicName, @RequestParam(defaultValue = "false") boolean includeNonApproved) { kafkaEnvironments.getEnvironmentMetadata(environmentId).orElseThrow(notFound); topicService.getTopic(environmentId, topicName).orElseThrow(notFound); diff --git a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImpl.java index 60404751..f7e07943 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImpl.java @@ -15,7 +15,6 @@ import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.FutureUtil; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @@ -38,7 +37,6 @@ public class SubscriptionServiceImpl implements SubscriptionService, InitPerClus private static final String TOPIC_NAME = "subscriptions"; - @Autowired public SubscriptionServiceImpl(KafkaClusters kafkaEnvironments, ApplicationsService applicationsService, @Qualifier(value = "nonvalidating") TopicService topicService, GalapagosEventManager eventManager) { this.kafkaEnvironments = kafkaEnvironments; diff --git a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionTopicListener.java b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionTopicListener.java index 7c69d582..fb643449 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionTopicListener.java +++ b/src/main/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionTopicListener.java @@ -6,7 +6,6 @@ import com.hermesworld.ais.galapagos.subscriptions.SubscriptionState; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.util.FutureUtil; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.CompletableFuture; @@ -29,7 +28,6 @@ public class SubscriptionTopicListener implements TopicEventsListener { private final SubscriptionService subscriptionService; - @Autowired public SubscriptionTopicListener(SubscriptionService subscriptionService) { this.subscriptionService = subscriptionService; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/topics/controller/ChangeTopicOwnerDto.java b/src/main/java/com/hermesworld/ais/galapagos/topics/controller/ChangeTopicOwnerDto.java index abcca90e..0939a05d 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/topics/controller/ChangeTopicOwnerDto.java +++ b/src/main/java/com/hermesworld/ais/galapagos/topics/controller/ChangeTopicOwnerDto.java @@ -3,7 +3,7 @@ import lombok.Getter; import lombok.Setter; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; @Getter @Setter diff --git a/src/main/java/com/hermesworld/ais/galapagos/topics/controller/TopicController.java b/src/main/java/com/hermesworld/ais/galapagos/topics/controller/TopicController.java index 44f9ba2a..98df1f91 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/topics/controller/TopicController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/topics/controller/TopicController.java @@ -21,7 +21,6 @@ import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.header.Header; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -29,7 +28,7 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; -import javax.validation.Valid; +import jakarta.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -61,7 +60,6 @@ public class TopicController { private static final int PEEK_LIMIT = 100; - @Autowired public TopicController(ValidatingTopicService topicService, KafkaClusters kafkaEnvironments, ApplicationsService applicationsService, NamingService namingService, CurrentUserService userService) { this.topicService = topicService; diff --git a/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImpl.java index 5bc96bb8..cdeee88a 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImpl.java @@ -26,7 +26,6 @@ import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @@ -62,7 +61,6 @@ public class TopicServiceImpl implements TopicService, InitPerCluster { static final String SCHEMA_TOPIC_NAME = "schemas"; - @Autowired public TopicServiceImpl(KafkaClusters kafkaClusters, ApplicationsService applicationsService, NamingService namingService, CurrentUserService userService, GalapagosTopicConfig topicSettings, GalapagosEventManager eventManager) { @@ -360,9 +358,10 @@ public CompletableFuture deleteLatestTopicSchemaVersion(String environment } if (schemaOnNextStage != null) { - return CompletableFuture.failedFuture( - new IllegalStateException("The selected schema already exists on the next stage! To delete " - + "this schema you have to delete it there first!")); + return CompletableFuture.failedFuture(new IllegalStateException(""" + The selected schema already exists on the next stage! To delete \ + this schema you have to delete it there first!\ + """)); } GalapagosEventSink eventSink = eventManager.newEventSink(kafkaCluster); @@ -418,9 +417,11 @@ public CompletableFuture addTopicSchemaVersion(String environmen if (newSchema.definesProperty("data") && (metadata.getType() == TopicType.EVENTS || metadata.getType() == TopicType.COMMANDS)) { - return CompletableFuture.failedFuture( - new IllegalArgumentException("The JSON Schema must not declare a \"data\" object on first level." - + " The JSON Schema must not contain the CloudEvents fields, but only the contents of the \"data\" field.")); + return CompletableFuture.failedFuture(new IllegalArgumentException( + """ + The JSON Schema must not declare a "data" object on first level.\ + The JSON Schema must not contain the CloudEvents fields, but only the contents of the "data" field.\ + """)); } if (existingVersions.isEmpty() && schemaMetadata.getSchemaVersion() != 1) { diff --git a/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/ValidatingTopicServiceImpl.java b/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/ValidatingTopicServiceImpl.java index a6982d16..8c0df26b 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/ValidatingTopicServiceImpl.java +++ b/src/main/java/com/hermesworld/ais/galapagos/topics/service/impl/ValidatingTopicServiceImpl.java @@ -11,7 +11,6 @@ import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.topics.service.ValidatingTopicService; import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; @@ -45,7 +44,6 @@ public class ValidatingTopicServiceImpl implements ValidatingTopicService { private final boolean schemaDeleteWithSub; - @Autowired public ValidatingTopicServiceImpl(@Qualifier(value = "nonvalidating") TopicService topicService, SubscriptionService subscriptionService, ApplicationsService applicationsService, KafkaClusters kafkaClusters, GalapagosTopicConfig topicConfig, diff --git a/src/main/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportController.java b/src/main/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportController.java index e7204f87..44158b7a 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportController.java @@ -17,7 +17,6 @@ import com.hermesworld.ais.galapagos.util.CertificateUtil; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.common.config.TopicConfig; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.StreamUtils; @@ -77,7 +76,6 @@ public class UISupportController { private static final long ONE_WEEK = TimeUnit.DAYS.toMillis(7); - @Autowired public UISupportController(ApplicationsService applicationsService, TopicService topicService, KafkaClusters kafkaClusters, NamingService namingService, GalapagosTopicConfig topicConfig, CustomLinksConfig customLinksConfig, GalapagosChangesConfig changesConfig) { diff --git a/src/main/java/com/hermesworld/ais/galapagos/util/controller/BackupController.java b/src/main/java/com/hermesworld/ais/galapagos/util/controller/BackupController.java index 19358b58..8fe7dd42 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/util/controller/BackupController.java +++ b/src/main/java/com/hermesworld/ais/galapagos/util/controller/BackupController.java @@ -10,7 +10,6 @@ import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; @@ -26,7 +25,6 @@ public class BackupController { private final ObjectMapper objectMapper = JsonUtil.newObjectMapper(); - @Autowired public BackupController(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } diff --git a/src/main/java/com/hermesworld/ais/galapagos/util/impl/StartupRepositoryInitializer.java b/src/main/java/com/hermesworld/ais/galapagos/util/impl/StartupRepositoryInitializer.java index 65680811..f5a4931c 100644 --- a/src/main/java/com/hermesworld/ais/galapagos/util/impl/StartupRepositoryInitializer.java +++ b/src/main/java/com/hermesworld/ais/galapagos/util/impl/StartupRepositoryInitializer.java @@ -10,7 +10,6 @@ import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.util.InitPerCluster; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; @@ -35,7 +34,6 @@ public class StartupRepositoryInitializer { private final Duration repositoryLoadIdleTime; - @Autowired public StartupRepositoryInitializer(KafkaClusters kafkaClusters, @Value("${galapagos.initialRepositoryLoadWaitTime:5s}") Duration initialRepositoryLoadWaitTime, @Value("${galapagos.repositoryLoadIdleTime:2s}") Duration repositoryLoadIdleTime) { diff --git a/src/test/java/com/hermesworld/ais/galapagos/ContextStartupTest.java b/src/test/java/com/hermesworld/ais/galapagos/ContextStartupTest.java index 44eeb18d..91743fe5 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/ContextStartupTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/ContextStartupTest.java @@ -1,24 +1,21 @@ package com.hermesworld.ais.galapagos; -import static org.junit.Assert.assertNotNull; - import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; -@RunWith(SpringRunner.class) @SpringBootTest -public class ContextStartupTest { +class ContextStartupTest { @Autowired private ApplicationContext context; @@ -27,14 +24,14 @@ public class ContextStartupTest { @MockBean private KafkaClusters kafkaClusters; - @BeforeClass - public static void setupSecurity() { + @BeforeAll + static void setupSecurity() { Security.setProperty("crypto.policy", "unlimited"); Security.addProvider(new BouncyCastleProvider()); } @Test - public void testStartupContext() { + void testStartupContext() { assertNotNull(kafkaClusters); assertNotNull(context); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJobTest.java b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJobTest.java index 99e4b566..bff0b6b9 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJobTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/CreateBackupJobTest.java @@ -12,9 +12,9 @@ import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.util.JsonUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.springframework.boot.ApplicationArguments; import java.nio.file.Files; @@ -24,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; -public class CreateBackupJobTest { +class CreateBackupJobTest { private KafkaClusters kafkaClusters; @@ -34,8 +34,8 @@ public class CreateBackupJobTest { private ObjectMapper mapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { testRepo.put("topics", new TopicBasedRepositoryMock() { @Override public Class getValueClass() { @@ -187,10 +187,10 @@ public Collection getObjects() { @Test @DisplayName("it should create a backup from all the metadata currently saved within Galapagos") - public void createBackUp_success() throws Exception { + void createBackUp_success() throws Exception { CreateBackupJob job = new CreateBackupJob(kafkaClusters); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("create.backup.file")).thenReturn(Collections.singletonList("true")); + when(args.getOptionValues("create.backup.file")).thenReturn(List.of("true")); try { job.run(args); @@ -222,21 +222,21 @@ public void createBackUp_success() throws Exception { .toString(); // test data - assertEquals(topicName, "\"topic-1\""); - assertEquals(topicType, "\"EVENTS\""); - assertEquals(clientApplicationIdSub, "\"app-1\""); - assertEquals(subId, "\"123\""); - assertEquals(aorId, "\"1\""); - assertEquals(aorState, "\"APPROVED\""); - assertEquals(username, "\"myUser\""); + assertEquals("\"topic-1\"", topicName); + assertEquals("\"EVENTS\"", topicType); + assertEquals("\"app-1\"", clientApplicationIdSub); + assertEquals("\"123\"", subId); + assertEquals("\"1\"", aorId); + assertEquals("\"APPROVED\"", aorState); + assertEquals("\"myUser\"", username); // prod data - assertEquals(topicNameProd, "\"topic-2\""); - assertEquals(topicTypeProd, "\"EVENTS\""); - assertEquals(clientApplicationIdSubProd, "\"app-12\""); - assertEquals(subIdProd, "\"12323\""); - assertEquals(aorIdProd, "\"2\""); - assertEquals(aorStateProd, "\"APPROVED\""); - assertEquals(usernameProd, "\"myUser2\""); + assertEquals("\"topic-2\"", topicNameProd); + assertEquals("\"EVENTS\"", topicTypeProd); + assertEquals("\"app-12\"", clientApplicationIdSubProd); + assertEquals("\"12323\"", subIdProd); + assertEquals("\"2\"", aorIdProd); + assertEquals("\"APPROVED\"", aorStateProd); + assertEquals("\"myUser2\"", usernameProd); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJobTest.java b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJobTest.java index 3d55df5c..f0f7e5aa 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJobTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/GenerateToolingCertificateJobTest.java @@ -32,7 +32,10 @@ import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; -import java.util.*; +import java.util.Base64; +import java.util.Enumeration; +import java.util.List; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.*; @@ -40,7 +43,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -public class GenerateToolingCertificateJobTest { +class GenerateToolingCertificateJobTest { @Mock private KafkaClusters kafkaClusters; @@ -66,7 +69,7 @@ public class GenerateToolingCertificateJobTest { private static final String DATA_MARKER = "CERTIFICATE DATA: "; @BeforeEach - public void feedMocks() throws Exception { + void feedMocks() throws Exception { Security.setProperty("crypto.policy", "unlimited"); Security.addProvider(new BouncyCastleProvider()); @@ -106,20 +109,20 @@ public void feedMocks() throws Exception { } @AfterEach - public void cleanup() { + void cleanup() { // noinspection ResultOfMethodCallIgnored testFile.delete(); System.setOut(oldOut); } @Test - public void testStandard() throws Exception { + void testStandard() throws Exception { GenerateToolingCertificateJob job = new GenerateToolingCertificateJob(kafkaClusters, aclSupport, namingService, kafkaConfig); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("output.filename")).thenReturn(Collections.singletonList(testFile.getPath())); - when(args.getOptionValues("kafka.environment")).thenReturn(Collections.singletonList("test")); + when(args.getOptionValues("output.filename")).thenReturn(List.of(testFile.getPath())); + when(args.getOptionValues("kafka.environment")).thenReturn(List.of("test")); job.run(args); @@ -144,12 +147,12 @@ public void testStandard() throws Exception { } @Test - public void testDataOnStdout() throws Exception { + void testDataOnStdout() throws Exception { GenerateToolingCertificateJob job = new GenerateToolingCertificateJob(kafkaClusters, aclSupport, namingService, kafkaConfig); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("kafka.environment")).thenReturn(Collections.singletonList("test")); + when(args.getOptionValues("kafka.environment")).thenReturn(List.of("test")); job.run(args); diff --git a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJobTest.java b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJobTest.java index 6fc634b2..b5ae9d3f 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJobTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportBackupJobTest.java @@ -11,7 +11,6 @@ import org.springframework.boot.ApplicationArguments; import java.io.File; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -20,7 +19,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ImportBackupJobTest { +class ImportBackupJobTest { private ImportBackupJob job; @@ -33,7 +32,7 @@ public class ImportBackupJobTest { private TopicBasedRepositoryMock topicRepository; @BeforeEach - public void setUp() { + void setUp() { kafkaClusters = mock(KafkaClusters.class); testCluster = mock(KafkaCluster.class); when(testCluster.getId()).thenReturn("prod"); @@ -55,12 +54,12 @@ public String getTopicName() { @Test @DisplayName("should import backup from import file") - public void importBackupTest() throws Exception { + void importBackupTest() throws Exception { // given ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("import.file")).thenReturn(Collections.singletonList(testFile.getPath())); - when(args.getOptionValues("clearRepos")).thenReturn(Collections.singletonList("false")); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("import.file")).thenReturn(List.of(testFile.getPath())); + when(args.getOptionValues("clearRepos")).thenReturn(List.of("false")); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); // when job.run(args); @@ -70,11 +69,11 @@ public void importBackupTest() throws Exception { @Test @DisplayName("should not clear non-imported environments") - public void importBackup_noClearOnOtherEnv() throws Exception { + void importBackup_noClearOnOtherEnv() throws Exception { ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("import.file")).thenReturn(Collections.singletonList(testFile.getPath())); - when(args.getOptionValues("clearRepos")).thenReturn(Collections.singletonList("true")); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("import.file")).thenReturn(List.of(testFile.getPath())); + when(args.getOptionValues("clearRepos")).thenReturn(List.of("true")); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); KafkaCluster devCluster = mock(KafkaCluster.class); when(devCluster.getId()).thenReturn("dev"); @@ -108,14 +107,14 @@ public CompletableFuture delete(TopicMetadata value) { @Test @DisplayName("should import backup from import file and old metadata in repos should still be present") - public void importBackupWithoutClearingExistingRepos() throws Exception { + void importBackupWithoutClearingExistingRepos() throws Exception { // given ApplicationArguments args = mock(ApplicationArguments.class); topicRepository.save(buildTopicMetadata()).get(); // when - when(args.getOptionValues("import.file")).thenReturn(Collections.singletonList(testFile.getPath())); - when(args.getOptionValues("clearRepos")).thenReturn(Collections.singletonList("false")); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("import.file")).thenReturn(List.of(testFile.getPath())); + when(args.getOptionValues("clearRepos")).thenReturn(List.of("false")); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); // then job.run(args); @@ -126,14 +125,14 @@ public void importBackupWithoutClearingExistingRepos() throws Exception { @Test @DisplayName("should import backup from import file and old metadata in repos should be not present") - public void importBackupWithClearingExistingRepos() throws Exception { + void importBackupWithClearingExistingRepos() throws Exception { // given ApplicationArguments args = mock(ApplicationArguments.class); topicRepository.save(buildTopicMetadata()).get(); // when - when(args.getOptionValues("import.file")).thenReturn(Collections.singletonList(testFile.getPath())); - when(args.getOptionValues("clearRepos")).thenReturn(Collections.singletonList("true")); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("import.file")).thenReturn(List.of(testFile.getPath())); + when(args.getOptionValues("clearRepos")).thenReturn(List.of("true")); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); // then job.run(args); @@ -144,13 +143,13 @@ public void importBackupWithClearingExistingRepos() throws Exception { @Test @DisplayName("should throw exception because no import file is set") - public void importBackupTest_noFileOption() throws Exception { + void importBackupTest_noFileOption() throws Exception { // given ApplicationArguments args = mock(ApplicationArguments.class); topicRepository.save(buildTopicMetadata()).get(); // when - when(args.getOptionValues("clearRepos")).thenReturn(Collections.singletonList("true")); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("clearRepos")).thenReturn(List.of("true")); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); // then try { @@ -165,13 +164,13 @@ public void importBackupTest_noFileOption() throws Exception { @Test @DisplayName("should throw exception because no clearRepos option given") - public void importBackupTest_noClearReposOption() throws Exception { + void importBackupTest_noClearReposOption() throws Exception { // given ApplicationArguments args = mock(ApplicationArguments.class); topicRepository.save(buildTopicMetadata()).get(); // when - when(args.getOptionValues("import.file")).thenReturn(Collections.singletonList(testFile.getPath())); - when(testCluster.getRepositories()).thenReturn(Collections.singletonList(topicRepository)); + when(args.getOptionValues("import.file")).thenReturn(List.of(testFile.getPath())); + when(testCluster.getRepositories()).thenReturn(List.of(topicRepository)); // then try { @@ -186,7 +185,7 @@ public void importBackupTest_noClearReposOption() throws Exception { @Test @DisplayName("should return correct job name") - public void importBackupTest_correctJobName() { + void importBackupTest_correctJobName() { assertEquals("import-backup", job.getJobName()); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJobTest.java b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJobTest.java index ae3ce136..8ad6dcbb 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJobTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ImportKnownApplicationsJobTest.java @@ -4,7 +4,6 @@ import java.io.File; import java.io.PrintStream; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -15,15 +14,18 @@ import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.impl.TopicBasedRepositoryMock; import com.hermesworld.ais.galapagos.util.JsonUtil; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.springframework.boot.ApplicationArguments; -public class ImportKnownApplicationsJobTest { +class ImportKnownApplicationsJobTest { private KafkaClusters kafkaClusters; @@ -35,8 +37,8 @@ public class ImportKnownApplicationsJobTest { private ObjectMapper mapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { mapper = JsonUtil.newObjectMapper(); kafkaClusters = mock(KafkaClusters.class); @@ -50,7 +52,7 @@ public void setUp() { } @Test - public void reImportAfterAppChanges() throws Exception { + void reImportAfterAppChanges() throws Exception { List knownApplications = mapper.readValue(fileWithOutInfoUrl, new TypeReference>() { @@ -58,8 +60,7 @@ public void reImportAfterAppChanges() throws Exception { ImportKnownApplicationsJob job = new ImportKnownApplicationsJob(kafkaClusters); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("applications.import.file")) - .thenReturn(Collections.singletonList(fileWithInfoUrl.getPath())); + when(args.getOptionValues("applications.import.file")).thenReturn(List.of(fileWithInfoUrl.getPath())); knownApplications.forEach(app -> appRepository.save(app)); // redirect STDOUT to check update count @@ -82,7 +83,7 @@ public void reImportAfterAppChanges() throws Exception { } @Test - public void importApps_alreadyIdentical() throws Exception { + void importApps_alreadyIdentical() throws Exception { List knownApplications = mapper.readValue(fileWithOutInfoUrl, new TypeReference>() { @@ -90,8 +91,7 @@ public void importApps_alreadyIdentical() throws Exception { ImportKnownApplicationsJob job = new ImportKnownApplicationsJob(kafkaClusters); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("applications.import.file")) - .thenReturn(Collections.singletonList(fileWithOutInfoUrl.getPath())); + when(args.getOptionValues("applications.import.file")).thenReturn(List.of(fileWithOutInfoUrl.getPath())); TopicBasedRepositoryMock appRepository = new TopicBasedRepositoryMock<>(); knownApplications.forEach(app -> appRepository.save(app)); when(kafkaClusters.getGlobalRepository("known-applications", KnownApplicationImpl.class)) @@ -116,12 +116,11 @@ public void importApps_alreadyIdentical() throws Exception { } @Test - public void importApps_positiv() throws Exception { + void importApps_positiv() throws Exception { ImportKnownApplicationsJob job = new ImportKnownApplicationsJob(kafkaClusters); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("applications.import.file")) - .thenReturn(Collections.singletonList(fileWithOutInfoUrl.getPath())); + when(args.getOptionValues("applications.import.file")).thenReturn(List.of(fileWithOutInfoUrl.getPath())); TopicBasedRepositoryMock appRepository = new TopicBasedRepositoryMock<>(); when(kafkaClusters.getGlobalRepository("known-applications", KnownApplicationImpl.class)) .thenReturn(appRepository); @@ -141,9 +140,9 @@ public void importApps_positiv() throws Exception { String output = new String(buffer.toByteArray(), StandardCharsets.UTF_8); assertTrue(output.contains("\n5 new application(s) imported.")); - assertEquals(appRepository.getObjects().size(), 5); + assertEquals(5, appRepository.getObjects().size()); assertTrue(appRepository.getObject("2222").isPresent()); - assertEquals(appRepository.getObject("F.I.V.E").get().getName(), "High Five"); + assertEquals("High Five", appRepository.getObject("F.I.V.E").get().getName()); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJobTest.java b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJobTest.java index b77beaeb..af452924 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJobTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/adminjobs/impl/ViewAclsJobTest.java @@ -1,12 +1,14 @@ package com.hermesworld.ais.galapagos.adminjobs.impl; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -19,34 +21,34 @@ import org.apache.kafka.common.resource.ResourceType; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ApplicationArguments; import com.hermesworld.ais.galapagos.kafka.KafkaCluster; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.util.FutureUtil; -public class ViewAclsJobTest { +class ViewAclsJobTest { private ByteArrayOutputStream stdoutData = new ByteArrayOutputStream(); private PrintStream oldOut; - @Before - public void setup() { + @BeforeEach + void setup() { oldOut = System.out; System.setOut(new PrintStream(stdoutData)); } - @After - public void cleanup() { + @AfterEach + void cleanup() { System.setOut(oldOut); } @Test - public void testJsonMapping() throws Exception { + void testJsonMapping() throws Exception { KafkaClusters clusters = mock(KafkaClusters.class); KafkaCluster cluster = mock(KafkaCluster.class); @@ -67,7 +69,7 @@ public void testJsonMapping() throws Exception { ViewAclsJob job = new ViewAclsJob(clusters); ApplicationArguments args = mock(ApplicationArguments.class); - when(args.getOptionValues("kafka.environment")).thenReturn(Collections.singletonList("test")); + when(args.getOptionValues("kafka.environment")).thenReturn(List.of("test")); job.run(args); diff --git a/src/test/java/com/hermesworld/ais/galapagos/applications/ApplicationsControllerTest.java b/src/test/java/com/hermesworld/ais/galapagos/applications/ApplicationsControllerTest.java index 048df59e..ba5ab0fa 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/applications/ApplicationsControllerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/applications/ApplicationsControllerTest.java @@ -28,7 +28,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -public class ApplicationsControllerTest { +class ApplicationsControllerTest { private final ApplicationsService applicationsService = mock(ApplicationsService.class); @@ -37,7 +37,7 @@ public class ApplicationsControllerTest { private final KafkaClusters kafkaClusters = mock(KafkaClusters.class); @Test - public void testUpdateApplicationCertificateDependentOnStageName() { + void testUpdateApplicationCertificateDependentOnStageName() { // Arrange String applicationId = "testapp-1"; String environmentId = "devtest"; @@ -70,7 +70,7 @@ public void testUpdateApplicationCertificateDependentOnStageName() { } @Test - public void testStagingWithoutSchema_include_failure() throws Exception { + void testStagingWithoutSchema_include_failure() throws Exception { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); diff --git a/src/test/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsControllerTest.java b/src/test/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsControllerTest.java index defbb6d1..27f1c26b 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsControllerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/applications/controller/ApplicationsControllerTest.java @@ -15,7 +15,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ApplicationsControllerTest { +class ApplicationsControllerTest { private ApplicationsService applicationsService; @@ -24,14 +24,14 @@ public class ApplicationsControllerTest { private KafkaClusters kafkaClusters; @BeforeEach - public void feedMocks() { + void feedMocks() { applicationsService = mock(ApplicationsService.class); stagingService = mock(StagingService.class); kafkaClusters = mock(KafkaClusters.class); } @Test - public void getRegisteredApplications_knownAppMissing() { + void getRegisteredApplications_knownAppMissing() { ApplicationsController controller = new ApplicationsController(applicationsService, stagingService, kafkaClusters); @@ -51,7 +51,7 @@ public void getRegisteredApplications_knownAppMissing() { when(applicationsService.getKnownApplication("nex1")).thenReturn(Optional.empty()); List regApps = controller.getRegisteredApplications("test"); - assertEquals(regApps.size(), 1); + assertEquals(1, regApps.size()); assertEquals("ex1", regApps.get(0).getId()); } } diff --git a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImplTest.java index 3843832c..388a8a2d 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceImplTest.java @@ -37,7 +37,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -public class ApplicationsServiceImplTest { +class ApplicationsServiceImplTest { private KafkaClusters kafkaClusters; @@ -51,7 +51,7 @@ public class ApplicationsServiceImplTest { private KafkaAuthenticationModule authenticationModule; @BeforeEach - public void feedMocks() { + void feedMocks() { kafkaClusters = mock(KafkaClusters.class); when(kafkaClusters.getGlobalRepository("application-owner-requests", ApplicationOwnerRequest.class)) @@ -81,7 +81,7 @@ public void feedMocks() { } @Test - public void testRemoveOldRequests() { + void testRemoveOldRequests() { List daos = new ArrayList<>(); ZonedDateTime createdAt = ZonedDateTime.of(LocalDateTime.of(2019, 1, 1, 10, 0), ZoneId.systemDefault()); @@ -136,7 +136,7 @@ public void testRemoveOldRequests() { } @Test - public void testKnownApplicationAfterSubmitting() { + void testKnownApplicationAfterSubmitting() { ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); String testUserName = "test"; String appId = "42"; @@ -166,7 +166,7 @@ public void testKnownApplicationAfterSubmitting() { } @Test - public void testReplaceCertificate_appChanges() throws Exception { + void testReplaceCertificate_appChanges() throws Exception { // Application changed e.g. in external Architecture system KnownApplicationImpl app = new KnownApplicationImpl("quattro-1", "Quattro"); app.setAliases(List.of("q2")); @@ -223,7 +223,7 @@ public void testReplaceCertificate_appChanges() throws Exception { } @Test - public void testRegisterNewFiresEvent() throws Exception { + void testRegisterNewFiresEvent() throws Exception { KnownApplicationImpl app = new KnownApplicationImpl("quattro-1", "Quattro"); app.setAliases(List.of("q2")); knownApplicationRepository.save(app).get(); @@ -245,7 +245,7 @@ public void testRegisterNewFiresEvent() throws Exception { } @Test - public void testPrefix() throws Exception { + void testPrefix() throws Exception { KnownApplicationImpl app = new KnownApplicationImpl("quattro-1", "Quattro"); app.setAliases(List.of("q2")); knownApplicationRepository.save(app).get(); @@ -276,7 +276,7 @@ public void testPrefix() throws Exception { } @Test - public void testExtendCertificate() throws Exception { + void testExtendCertificate() throws Exception { // TODO move to CertificeAuthenticationModuleTest // KnownApplicationImpl app = new KnownApplicationImpl("quattro-1", "Quattro"); @@ -324,7 +324,7 @@ public void testExtendCertificate() throws Exception { } @Test - public void testUpdateAuthentication() throws Exception { + void testUpdateAuthentication() throws Exception { // WHEN an already registered application is re-registered on an environment... KnownApplicationImpl app = new KnownApplicationImpl("quattro-1", "Quattro"); knownApplicationRepository.save(app).get(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceRequestStatesImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceRequestStatesImplTest.java index 3c00e6fb..f0ac3909 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceRequestStatesImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/ApplicationsServiceRequestStatesImplTest.java @@ -10,8 +10,8 @@ import com.hermesworld.ais.galapagos.naming.NamingService; import com.hermesworld.ais.galapagos.security.CurrentUserService; import com.hermesworld.ais.galapagos.util.TimeService; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.ZoneId; @@ -23,7 +23,7 @@ import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,8 +41,8 @@ public class ApplicationsServiceRequestStatesImplTest { private final TopicBasedRepositoryMock repository = new TopicBasedRepositoryMock<>(); - @Before - public void feedCommonMocks() { + @BeforeEach + void feedCommonMocks() { currentUserService = mock(CurrentUserService.class); when(currentUserService.getCurrentUserName()).thenReturn(Optional.of(testUserName)); @@ -278,52 +278,58 @@ public void testFromRejectedToSubmitted() throws Exception { assertEquals(RequestState.SUBMITTED, savedRequests.get(0).getState()); } - @Test(expected = IllegalStateException.class) + @Test public void testImpossibleTransitionRevoked() throws Throwable { - ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); - ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.REVOKED, now); - repository.save(applicationOwnerRequest); - - ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, - mock(TimeService.class), mock(NamingService.class), eventManager); - try { - appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); - } - catch (ExecutionException e) { - throw e.getCause(); - } + assertThrows(IllegalStateException.class, () -> { + ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); + ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.REVOKED, now); + repository.save(applicationOwnerRequest); + + ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, + mock(TimeService.class), mock(NamingService.class), eventManager); + try { + appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); + } + catch (ExecutionException e) { + throw e.getCause(); + } + }); } - @Test(expected = IllegalStateException.class) + @Test public void testImpossibleTransitionRejected() throws Throwable { - ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); - ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.REJECTED, now); - repository.save(applicationOwnerRequest); - - ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, - mock(TimeService.class), mock(NamingService.class), eventManager); - try { - appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); - } - catch (ExecutionException e) { - throw e.getCause(); - } + assertThrows(IllegalStateException.class, () -> { + ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); + ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.REJECTED, now); + repository.save(applicationOwnerRequest); + + ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, + mock(TimeService.class), mock(NamingService.class), eventManager); + try { + appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); + } + catch (ExecutionException e) { + throw e.getCause(); + } + }); } - @Test(expected = IllegalStateException.class) + @Test public void testImpossibleTransitionResigned() throws Throwable { - ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); - ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.RESIGNED, now); - repository.save(applicationOwnerRequest); - - ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, - mock(TimeService.class), mock(NamingService.class), eventManager); - try { - appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); - } - catch (ExecutionException e) { - throw e.getCause(); - } + assertThrows(IllegalStateException.class, () -> { + ZonedDateTime now = ZonedDateTime.of(LocalDateTime.of(2020, 3, 25, 10, 0), ZoneOffset.UTC); + ApplicationOwnerRequest applicationOwnerRequest = createRequest(RequestState.RESIGNED, now); + repository.save(applicationOwnerRequest); + + ApplicationsServiceImpl appsServImpl = new ApplicationsServiceImpl(kafkaEnvironments, currentUserService, + mock(TimeService.class), mock(NamingService.class), eventManager); + try { + appsServImpl.cancelUserApplicationOwnerRequest(applicationOwnerRequest.getId()).get(); + } + catch (ExecutionException e) { + throw e.getCause(); + } + }); } private static ApplicationOwnerRequest createRequest(RequestState reqState, ZonedDateTime createdAt) { diff --git a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListenerTest.java b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListenerTest.java index 6a914f55..e88a064c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListenerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/applications/impl/UpdateApplicationAclsListenerTest.java @@ -40,7 +40,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -public class UpdateApplicationAclsListenerTest { +class UpdateApplicationAclsListenerTest { @Mock private KafkaClusters kafkaClusters; @@ -63,7 +63,7 @@ public class UpdateApplicationAclsListenerTest { private AclBinding dummyBinding; @BeforeEach - public void feedMocks() { + void feedMocks() { when(cluster.getId()).thenReturn("_test"); lenient().when(kafkaClusters.getEnvironment("_test")).thenReturn(Optional.of(cluster)); lenient().when(kafkaClusters.getAuthenticationModule("_test")).thenReturn(Optional.of(authenticationModule)); @@ -80,7 +80,7 @@ public void feedMocks() { } @Test - public void testUpdateApplicationAcls() throws InterruptedException, ExecutionException { + void testUpdateApplicationAcls() throws InterruptedException, ExecutionException { when(authenticationModule .extractKafkaUserName(ArgumentMatchers.argThat(obj -> obj.getString("dn").equals("CN=testapp")))) .thenReturn("User:CN=testapp"); @@ -115,7 +115,7 @@ public void testUpdateApplicationAcls() throws InterruptedException, ExecutionEx } @Test - public void testHandleTopicCreated() throws ExecutionException, InterruptedException { + void testHandleTopicCreated() throws ExecutionException, InterruptedException { GalapagosEventContext context = mock(GalapagosEventContext.class); when(context.getKafkaCluster()).thenReturn(cluster); when(cluster.getId()).thenReturn("_test"); @@ -149,7 +149,7 @@ public void testHandleTopicCreated() throws ExecutionException, InterruptedExcep } @Test - public void testHandleAddProducer() throws ExecutionException, InterruptedException { + void testHandleAddProducer() throws ExecutionException, InterruptedException { GalapagosEventContext context = mock(GalapagosEventContext.class); when(context.getKafkaCluster()).thenReturn(cluster); when(cluster.getId()).thenReturn("_test"); @@ -182,7 +182,7 @@ public void testHandleAddProducer() throws ExecutionException, InterruptedExcept } @Test - public void testHandleRemoveProducer() throws ExecutionException, InterruptedException { + void testHandleRemoveProducer() throws ExecutionException, InterruptedException { // more or less, this is same as add() - updateUserAcls for the removed producer must be called. GalapagosEventContext context = mock(GalapagosEventContext.class); when(context.getKafkaCluster()).thenReturn(cluster); @@ -211,7 +211,7 @@ public void testHandleRemoveProducer() throws ExecutionException, InterruptedExc } @Test - public void testSubscriptionCreated() throws ExecutionException, InterruptedException { + void testSubscriptionCreated() throws ExecutionException, InterruptedException { GalapagosEventContext context = mock(GalapagosEventContext.class); when(context.getKafkaCluster()).thenReturn(cluster); when(cluster.getId()).thenReturn("_test"); @@ -245,7 +245,7 @@ public void testSubscriptionCreated() throws ExecutionException, InterruptedExce } @Test - public void testNoDeleteAclsWhenUserNameIsSame() throws Exception { + void testNoDeleteAclsWhenUserNameIsSame() throws Exception { // tests that, when an AuthenticationChanged event occurs but the resulting Kafka User Name is the same, the // listener does not delete the ACLs of the user after updating them (because that would result in zero ACLs). GalapagosEventContext context = mock(GalapagosEventContext.class); @@ -276,7 +276,7 @@ public void testNoDeleteAclsWhenUserNameIsSame() throws Exception { } @Test - public void testNoDeleteAclsWhenNoPreviousUser() throws Exception { + void testNoDeleteAclsWhenNoPreviousUser() throws Exception { GalapagosEventContext context = mock(GalapagosEventContext.class); when(context.getKafkaCluster()).thenReturn(cluster); @@ -305,7 +305,7 @@ public void testNoDeleteAclsWhenNoPreviousUser() throws Exception { } @Test - public void testNoApplicationAclUpdates() throws Exception { + void testNoApplicationAclUpdates() throws Exception { // GIVEN a configuration where noUpdateApplicationAcls flag is active KafkaEnvironmentConfig config = mock(KafkaEnvironmentConfig.class); when(config.isNoUpdateApplicationAcls()).thenReturn(true); diff --git a/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudApiClientTest.java b/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudApiClientTest.java index a876b97e..07f0c22c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudApiClientTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudApiClientTest.java @@ -29,7 +29,7 @@ import static org.junit.jupiter.api.Assertions.*; -public class ConfluentCloudApiClientTest { +class ConfluentCloudApiClientTest { private static MockWebServer mockBackEnd; @@ -47,12 +47,12 @@ static void tearDown() throws IOException { } @BeforeEach - public void init() { - baseUrl = String.format("http://localhost:%s", mockBackEnd.getPort()); + void init() { + baseUrl = "http://localhost:%s".formatted(mockBackEnd.getPort()); } @AfterEach - public void consumeRequests() throws Exception { + void consumeRequests() throws Exception { RecordedRequest request; while ((request = mockBackEnd.takeRequest(10, TimeUnit.MILLISECONDS)) != null) { System.err.println( @@ -71,7 +71,7 @@ private String readTestResource(String resourceName) throws IOException { } @Test - public void testListServiceAccounts() throws Exception { + void testListServiceAccounts() throws Exception { mockBackEnd.enqueue(new MockResponse().setBody(readTestResource("ccloud/service-accounts.json")) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); @@ -93,7 +93,7 @@ public void testListServiceAccounts() throws Exception { } @Test - public void testPagination() throws Exception { + void testPagination() throws Exception { mockBackEnd.enqueue(new MockResponse() .setBody(readTestResource("ccloud/service-accounts-page1.json").replace("${baseurl}", baseUrl)) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); @@ -128,7 +128,7 @@ public void testPagination() throws Exception { } @Test - public void testListApiKeys() throws Exception { + void testListApiKeys() throws Exception { mockBackEnd.enqueue(new MockResponse().setBody(readTestResource("ccloud/api-keys.json")) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); @@ -152,7 +152,7 @@ public void testListApiKeys() throws Exception { } @Test - public void testCreateServiceAccount() throws Exception { + void testCreateServiceAccount() throws Exception { mockBackEnd.enqueue(new MockResponse().setBody(readTestResource("ccloud/service-account.json")) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(HttpStatus.CREATED.value())); @@ -178,7 +178,7 @@ public void testCreateServiceAccount() throws Exception { } @Test - public void testCreateServiceAccount_withNumericId() throws Exception { + void testCreateServiceAccount_withNumericId() throws Exception { mockBackEnd.enqueue(new MockResponse().setBody(readTestResource("ccloud/service-account.json")) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(HttpStatus.CREATED.value())); @@ -203,7 +203,7 @@ public void testCreateServiceAccount_withNumericId() throws Exception { } @Test - public void testCreateApiKey() throws Exception { + void testCreateApiKey() throws Exception { mockBackEnd.enqueue(new MockResponse().setBody(readTestResource("ccloud/api-key.json")) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(HttpStatus.ACCEPTED.value())); @@ -240,7 +240,7 @@ public void testCreateApiKey() throws Exception { } @Test - public void testDeleteApiKey() throws Exception { + void testDeleteApiKey() throws Exception { mockBackEnd.enqueue(new MockResponse().setResponseCode(HttpStatus.NO_CONTENT.value())); ConfluentCloudApiClient apiClient = new ConfluentCloudApiClient(baseUrl, "myKey", "mySecret", false); @@ -258,7 +258,7 @@ public void testDeleteApiKey() throws Exception { } @Test - public void testErrorStatusCode() throws Exception { + void testErrorStatusCode() throws Exception { mockBackEnd.enqueue(new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.value())); ConfluentCloudApiClient apiClient = new ConfluentCloudApiClient(baseUrl, "myKey", "mySecret", false); @@ -272,7 +272,7 @@ public void testErrorStatusCode() throws Exception { } @Test - public void testErrorMessage_singleError() throws Exception { + void testErrorMessage_singleError() throws Exception { JSONObject errorObj = new JSONObject(Map.of("error", "something went wrong")); mockBackEnd.enqueue(new MockResponse().setResponseCode(HttpStatus.BAD_REQUEST.value()) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(errorObj.toString())); @@ -288,7 +288,7 @@ public void testErrorMessage_singleError() throws Exception { } @Test - public void testErrorMessage_errorsArray() throws Exception { + void testErrorMessage_errorsArray() throws Exception { JSONObject errorObj = new JSONObject(Map.of("detail", "something went wrong")); JSONObject errorObj2 = new JSONObject(Map.of("detail", "all is broken")); JSONArray errors = new JSONArray(); @@ -310,7 +310,7 @@ public void testErrorMessage_errorsArray() throws Exception { } @Test - public void testError_textOnlyResponse() throws Exception { + void testError_textOnlyResponse() throws Exception { mockBackEnd.enqueue(new MockResponse().setResponseCode(HttpStatus.BAD_REQUEST.value()) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) .setBody("This is your friendly error message in text only.")); diff --git a/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudAuthenticationModuleTest.java b/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudAuthenticationModuleTest.java index db6df417..cd88287e 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudAuthenticationModuleTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/ccloud/ConfluentCloudAuthenticationModuleTest.java @@ -27,16 +27,17 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.*; -public class ConfluentCloudAuthenticationModuleTest { +class ConfluentCloudAuthenticationModuleTest { private KafkaAuthenticationModule authenticationModule; private ConfluentCloudApiClient client; @BeforeEach - public void init() { + void init() { authenticationModule = new ConfluentCloudAuthenticationModule(basicConfig()); client = mock(ConfluentCloudApiClient.class); @@ -81,19 +82,19 @@ private String toAuthJson(Map fields) { } @Test - public void extractKafkaUserNameTest_positive() { + void extractKafkaUserNameTest_positive() { String kafkaUserName = authenticationModule.extractKafkaUserName(new JSONObject("{userId:1234}")); assertEquals("User:1234", kafkaUserName); } @Test - public void extractKafkaUserNameTest_negative() { + void extractKafkaUserNameTest_negative() { assertThrows(JSONException.class, () -> authenticationModule.extractKafkaUserName(new JSONObject("{}"))); } @Test - public void fillCorrectProps_positive() { + void fillCorrectProps_positive() { ConfluentCloudAuthConfig config = basicConfig(); config.setClusterApiSecret("secretPassword"); config.setClusterApiKey("someApiKey"); @@ -108,7 +109,7 @@ public void fillCorrectProps_positive() { } @Test - public void fillCorrectProps_negative() { + void fillCorrectProps_negative() { Properties props = new Properties(); authenticationModule.addRequiredKafkaProperties(props); @@ -117,7 +118,7 @@ public void fillCorrectProps_negative() { } @Test - public void testDeleteApplicationAuthentication_positive() throws ExecutionException, InterruptedException { + void testDeleteApplicationAuthentication_positive() throws ExecutionException, InterruptedException { ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); ApiKeySpec apiKey2 = newApiKey("someKey2", "someSecret2", "sa-xy124"); @@ -131,7 +132,7 @@ public void testDeleteApplicationAuthentication_positive() throws ExecutionExcep } @Test - public void deleteApplicationAuthenticationTest_negativeNoApiKeyObjectInAuthJson() + void deleteApplicationAuthenticationTest_negativeNoApiKeyObjectInAuthJson() throws ExecutionException, InterruptedException { ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); ApiKeySpec apiKey2 = newApiKey("someKey2", "someSecret2", "sa-xy124"); @@ -144,7 +145,7 @@ public void deleteApplicationAuthenticationTest_negativeNoApiKeyObjectInAuthJson } @Test - public void createApplicationAuthenticationTest_createServiceAccForAppThatHasNoAcc() + void createApplicationAuthenticationTest_createServiceAccForAppThatHasNoAcc() throws ExecutionException, InterruptedException { ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); ApiKeySpec apiKey2 = newApiKey("someKey2", "someSecret2", "sa-xy124"); @@ -174,8 +175,7 @@ public void createApplicationAuthenticationTest_createServiceAccForAppThatHasNoA } @Test - public void createApplicationAuthenticationTest_reuseServiceAccIfExists() - throws ExecutionException, InterruptedException { + void createApplicationAuthenticationTest_reuseServiceAccIfExists() throws ExecutionException, InterruptedException { ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); ApiKeySpec apiKey2 = newApiKey("someKey2", "someSecret2", "sa-xy124"); ApiKeySpec apiKey3 = newApiKey("someKey3", "someSecret3", "sa-xy125"); @@ -193,13 +193,13 @@ public void createApplicationAuthenticationTest_reuseServiceAccIfExists() authenticationModule.createApplicationAuthentication("quattro-1", "normalizedAppNameTest", new JSONObject()) .get(); - verify(client, times(0)).createServiceAccount(anyString(), anyString()); + verify(client, times(0)).createServiceAccount(nullable(String.class), nullable(String.class)); verify(client, times(1)).createApiKey("testEnv", "testCluster", "Application normalizedAppNameTest", "sa-xy125"); } @Test - public void createApplicationAuthenticationTest_queryNumericId() throws ExecutionException, InterruptedException { + void createApplicationAuthenticationTest_queryNumericId() throws ExecutionException, InterruptedException { useIdCompatMode(); ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); @@ -222,14 +222,14 @@ public void createApplicationAuthenticationTest_queryNumericId() throws Executio assertEquals("sa-xy123", result.getPublicAuthenticationData().getString("userId")); assertEquals("12345", result.getPublicAuthenticationData().getString("numericId")); - verify(client, times(0)).createServiceAccount(anyString(), anyString()); + verify(client, times(0)).createServiceAccount(nullable(String.class), nullable(String.class)); verify(client, times(1)).createApiKey("testEnv", "testCluster", "Application normalizedAppNameTest", "sa-xy123"); verify(client, times(1)).getServiceAccountInternalIds(); } @Test - public void updateApplicationAuthenticationTest() throws ExecutionException, InterruptedException { + void updateApplicationAuthenticationTest() throws ExecutionException, InterruptedException { ApiKeySpec apiKey1 = newApiKey("someKey1", "someSecret1", "sa-xy123"); ApiKeySpec apiKey2 = newApiKey("someKey2", "someSecret2", "sa-xy124"); ApiKeySpec apiKey3 = newApiKey("someKey3", "someSecret3", "sa-xy123"); @@ -255,13 +255,13 @@ public void updateApplicationAuthenticationTest() throws ExecutionException, Int new JSONObject(auth)).get(); verify(client).deleteApiKey(apiKey1); - verify(client, times(0)).createServiceAccount(anyString(), anyString()); + verify(client, times(0)).createServiceAccount(nullable(String.class), nullable(String.class)); verify(client, times(1)).createApiKey("testEnv", "testCluster", "Application normalizedAppNameTest", "sa-xy123"); } @Test - public void testLookupNumericId_positive() { + void testLookupNumericId_positive() { useIdCompatMode(); JSONObject authData = new JSONObject(Map.of("userId", "sa-xy125", "apiKey", "ABC123")); @@ -273,7 +273,7 @@ public void testLookupNumericId_positive() { } @Test - public void testLookupNumericId_noLookup_noCompatMode() { + void testLookupNumericId_noLookup_noCompatMode() { // idCompatMode is by default false in config! JSONObject authData = new JSONObject(Map.of("userId", "sa-xy125", "apiKey", "ABC123")); Map internalIdMapping = Map.of("sa-xy123", "12399", "sa-xy125", "12345"); @@ -285,7 +285,7 @@ public void testLookupNumericId_noLookup_noCompatMode() { } @Test - public void testLookupNumericId_noLookup_numericUserId() { + void testLookupNumericId_noLookup_numericUserId() { useIdCompatMode(); JSONObject authData = new JSONObject(Map.of("userId", "12345", "apiKey", "ABC123")); @@ -298,7 +298,7 @@ public void testLookupNumericId_noLookup_numericUserId() { } @Test - public void testLookupNumericId_noLookup_explicitNumericId() { + void testLookupNumericId_noLookup_explicitNumericId() { useIdCompatMode(); JSONObject authData = new JSONObject(Map.of("userId", "sa-xy123", "apiKey", "ABC123", "numericId", "12345")); @@ -311,7 +311,7 @@ public void testLookupNumericId_noLookup_explicitNumericId() { } @Test - public void testLookupNumericId_noUseOfNumericId() { + void testLookupNumericId_noUseOfNumericId() { // idCompatMode is by default false in config! JSONObject authData = new JSONObject(Map.of("userId", "sa-xy123", "apiKey", "ABC123", "numericId", "12345")); Map internalIdMapping = Map.of("sa-xy123", "12399", "sa-xy125", "12346"); @@ -323,7 +323,7 @@ public void testLookupNumericId_noUseOfNumericId() { } @Test - public void testDevAuth_positive() throws Exception { + void testDevAuth_positive() throws Exception { Instant now = Instant.now(); // make sure that there really is slight delay Thread.sleep(100); @@ -361,7 +361,7 @@ public void testDevAuth_positive() throws Exception { } @Test - public void testDevAuth_notEnabled() throws Exception { + void testDevAuth_notEnabled() throws Exception { ServiceAccountSpec testServiceAccount = new ServiceAccountSpec(); testServiceAccount.setDisplayName("Test Display Name"); testServiceAccount.setResourceId("sa-xy123"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/certificates/impl/CaManagerImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/certificates/impl/CaManagerImplTest.java index 5fd9d659..f2c4771e 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/certificates/impl/CaManagerImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/certificates/impl/CaManagerImplTest.java @@ -16,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.*; -public class CaManagerImplTest { +class CaManagerImplTest { private final static String testAppId = "four"; @@ -27,13 +27,13 @@ public class CaManagerImplTest { private CertificatesAuthenticationConfig authConfig; @BeforeEach - public void init() { + void init() { Security.addProvider(new BouncyCastleProvider()); authConfig = mockAuthConfig(); } @Test - public void testCreateApplicationFromCsrWithValidCn() throws Exception { + void testCreateApplicationFromCsrWithValidCn() throws Exception { String testCsrData = StreamUtils.copyToString( new ClassPathResource("/certificates/test_quattroValidCn.csr").getInputStream(), StandardCharsets.UTF_8); @@ -48,7 +48,7 @@ public void testCreateApplicationFromCsrWithValidCn() throws Exception { } @Test - public void testCreateApplicationFromCsrWithInvalidCn() throws Exception { + void testCreateApplicationFromCsrWithInvalidCn() throws Exception { String testCsrData = StreamUtils.copyToString( new ClassPathResource("/certificates/test_quattroInvalidCn.csr").getInputStream(), StandardCharsets.UTF_8); @@ -64,7 +64,7 @@ public void testCreateApplicationFromCsrWithInvalidCn() throws Exception { } @Test - public void testCreateApplicationFromCsrWithInvalidAppId() throws Exception { + void testCreateApplicationFromCsrWithInvalidAppId() throws Exception { String testCsrData = StreamUtils.copyToString( new ClassPathResource("/certificates/test_quattroInvalidAppId.csr").getInputStream(), StandardCharsets.UTF_8); @@ -80,7 +80,7 @@ public void testCreateApplicationFromCsrWithInvalidAppId() throws Exception { } @Test - public void testCreateApplicationFromInvalidCsr() throws Exception { + void testCreateApplicationFromInvalidCsr() throws Exception { CaManagerImpl testCaManagerImpl = new CaManagerImpl("test", authConfig); try { testCaManagerImpl.createApplicationCertificateFromCsr(testAppId, "testCsrData", testAppName).get(); @@ -92,7 +92,7 @@ public void testCreateApplicationFromInvalidCsr() throws Exception { } @Test - public void testExtendCertificate() throws Exception { + void testExtendCertificate() throws Exception { CaManagerImpl testCaManagerImpl = new CaManagerImpl("test", authConfig); String testCsrData = StreamUtils.copyToString( @@ -108,7 +108,7 @@ public void testExtendCertificate() throws Exception { } @Test - public void testExtendCertificate_wrongDn() throws Exception { + void testExtendCertificate_wrongDn() throws Exception { CaManagerImpl testCaManagerImpl = new CaManagerImpl("test", authConfig); String testCsrData = StreamUtils.copyToString( diff --git a/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunnerIntegrationTest.java b/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunnerIntegrationTest.java index 2217bef5..1d406421 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunnerIntegrationTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunnerIntegrationTest.java @@ -11,24 +11,22 @@ import com.hermesworld.ais.galapagos.certificates.reminders.ReminderType; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.mail.MailHealthContributorAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.test.context.junit4.SpringRunner; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; import java.io.ByteArrayInputStream; import java.util.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; @@ -37,10 +35,9 @@ * This test mainly focuses on the "notification integration" part, i.e., that the mail templates do render correctly * and the correct e-mail recipients are determined and passed to the mail engine. */ -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @EnableAutoConfiguration(exclude = { MailHealthContributorAutoConfiguration.class }) -public class CertificateExpiryReminderRunnerIntegrationTest { +class CertificateExpiryReminderRunnerIntegrationTest { @MockBean private KafkaClusters kafkaClusters; @@ -59,8 +56,8 @@ public class CertificateExpiryReminderRunnerIntegrationTest { private final List sentMessages = new ArrayList<>(); - @Before - public void initMocks() throws MessagingException { + @BeforeEach + void initMocks() throws MessagingException { when(kafkaClusters.getEnvironmentIds()).thenReturn(List.of("test")); doAnswer(inv -> sentMessages.add(inv.getArgument(0))).when(mailSender).send((MimeMessage) any()); @@ -83,7 +80,7 @@ public void initMocks() throws MessagingException { } @Test - public void testSendNotification_threeMonths_success() throws Exception { + void testSendNotification_threeMonths_success() throws Exception { CertificateExpiryReminder reminder = new CertificateExpiryReminder("123", "test", ReminderType.THREE_MONTHS); when(reminderService.calculateDueCertificateReminders()).thenReturn(List.of(reminder)); @@ -95,7 +92,7 @@ public void testSendNotification_threeMonths_success() throws Exception { } @Test - public void testSendNotification_oneMonth_success() throws Exception { + void testSendNotification_oneMonth_success() throws Exception { CertificateExpiryReminder reminder = new CertificateExpiryReminder("123", "test", ReminderType.ONE_MONTH); when(reminderService.calculateDueCertificateReminders()).thenReturn(List.of(reminder)); @@ -107,7 +104,7 @@ public void testSendNotification_oneMonth_success() throws Exception { } @Test - public void testSendNotification_oneWeek_success() throws Exception { + void testSendNotification_oneWeek_success() throws Exception { CertificateExpiryReminder reminder = new CertificateExpiryReminder("123", "test", ReminderType.ONE_WEEK); when(reminderService.calculateDueCertificateReminders()).thenReturn(List.of(reminder)); diff --git a/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceTest.java b/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceTest.java index 5e383706..96584f85 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceTest.java @@ -11,19 +11,18 @@ import com.hermesworld.ais.galapagos.kafka.config.KafkaEnvironmentConfig; import com.hermesworld.ais.galapagos.kafka.impl.TopicBasedRepositoryMock; import org.json.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class CertificateExpiryReminderServiceTest { +class CertificateExpiryReminderServiceTest { private KafkaClusters clusters; @@ -33,8 +32,8 @@ public class CertificateExpiryReminderServiceTest { private final TopicBasedRepositoryMock reminderRepository = new TopicBasedRepositoryMock<>(); - @Before - public void initClusters() { + @BeforeEach + void initClusters() { clusters = mock(KafkaClusters.class); KafkaCluster cluster = mock(KafkaCluster.class); applicationsService = mock(ApplicationsService.class); @@ -57,7 +56,7 @@ public void initClusters() { } @Test - public void testNoReminder() { + void testNoReminder() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); metadata.setAuthenticationJson(authJson("CN=abc", 365)); @@ -69,7 +68,7 @@ public void testNoReminder() { } @Test - public void testSimpleCase() { + void testSimpleCase() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); metadata.setAuthenticationJson(authJson("CN=abc", 40)); @@ -80,11 +79,11 @@ public void testSimpleCase() { assertEquals(1, reminders.size()); assertEquals("123", reminders.get(0).getApplicationId()); assertEquals("test", reminders.get(0).getEnvironmentId()); - Assert.assertEquals(ReminderType.THREE_MONTHS, reminders.get(0).getReminderType()); + assertEquals(ReminderType.THREE_MONTHS, reminders.get(0).getReminderType()); } @Test - public void testMultipleCallsWithoutMarkMustReturnSameReminders() { + void testMultipleCallsWithoutMarkMustReturnSameReminders() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); metadata.setAuthenticationJson(authJson("CN=abc", 40)); @@ -100,7 +99,7 @@ public void testMultipleCallsWithoutMarkMustReturnSameReminders() { } @Test - public void testSimpleMark() { + void testSimpleMark() { List applications = new ArrayList<>(); ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); @@ -126,7 +125,7 @@ public void testSimpleMark() { } @Test - public void testShortTimeAlreadySentShouldNotSendLongerTimeReminder() throws Exception { + void testShortTimeAlreadySentShouldNotSendLongerTimeReminder() throws Exception { List applications = new ArrayList<>(); ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); @@ -148,7 +147,7 @@ public void testShortTimeAlreadySentShouldNotSendLongerTimeReminder() throws Exc } @Test - public void testMultipleEnvironmentsWithExpiredEach() { + void testMultipleEnvironmentsWithExpiredEach() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); metadata.setAuthenticationJson(authJson("CN=abc", 5)); @@ -189,7 +188,7 @@ public void testMultipleEnvironmentsWithExpiredEach() { } @Test - public void testMultipleEnvironmentsWithOnlyOneExpired() { + void testMultipleEnvironmentsWithOnlyOneExpired() { List applications = new ArrayList<>(); ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("123"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeBaseTest.java b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeBaseTest.java index 5ee1ef97..6193db03 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeBaseTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeBaseTest.java @@ -11,14 +11,16 @@ import com.hermesworld.ais.galapagos.subscriptions.SubscriptionMetadata; import com.hermesworld.ais.galapagos.subscriptions.SubscriptionState; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; -import static org.junit.Assert.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.springframework.beans.BeanUtils; -public class ChangeBaseTest { +class ChangeBaseTest { /** * Tests that each private field in all of the subclasses of ChangeBase have a Getter for all of their private @@ -26,7 +28,7 @@ public class ChangeBaseTest { * use of Reflection! */ @Test - public void testGettersForFields() { + void testGettersForFields() { String packageName = ChangeBase.class.getPackageName(); ClassLoader cl = ChangeBaseTest.class.getClassLoader(); @@ -67,7 +69,7 @@ private void assertGettersForFields(Class clazz) { } @Test - public void testStageSubscription() throws Exception { + void testStageSubscription() throws Exception { SubscriptionMetadata sub1 = new SubscriptionMetadata(); sub1.setId("123"); sub1.setClientApplicationId("app-1"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeDeserializerTest.java b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeDeserializerTest.java index 683f1b61..ce269f12 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeDeserializerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangeDeserializerTest.java @@ -8,18 +8,18 @@ import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.util.JsonUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ChangeDeserializerTest { +class ChangeDeserializerTest { @Test - public void testCompoundChangeDeser() throws Exception { + void testCompoundChangeDeser() throws Exception { // ChangesDeserializer is registered in the ObjectMapper by this method ObjectMapper mapper = JsonUtil.newObjectMapper(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImplTest.java index bceba3d8..234c56eb 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/changes/impl/ChangesServiceImplTest.java @@ -22,14 +22,15 @@ import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.util.HasKey; -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ChangesServiceImplTest { +class ChangesServiceImplTest { private GalapagosEventContext context; @@ -37,8 +38,8 @@ public class ChangesServiceImplTest { private AuditPrincipal principal; - @Before - public void buildMocks() { + @BeforeEach + void buildMocks() { KafkaClusters clusters = mock(KafkaClusters.class); impl = new ChangesServiceImpl(clusters); @@ -52,7 +53,7 @@ public void buildMocks() { } @Test - public void testChangeListener_createTopic() { + void testChangeListener_createTopic() { TopicMetadata metadata = buildTopicMetadata(); TopicCreateParams params = new TopicCreateParams(2, 2); @@ -68,7 +69,7 @@ public void testChangeListener_createTopic() { } @Test - public void testChangeListener_deleteTopic() { + void testChangeListener_deleteTopic() { TopicMetadata metadata = buildTopicMetadata(); TopicEvent event = new TopicEvent(context, metadata); impl.handleTopicDeleted(event); @@ -82,7 +83,7 @@ public void testChangeListener_deleteTopic() { } @Test - public void testChangeListener_topicDescriptionChanged() { + void testChangeListener_topicDescriptionChanged() { TopicMetadata metadata = buildTopicMetadata(); TopicEvent event = new TopicEvent(context, metadata); impl.handleTopicDescriptionChanged(event); @@ -96,7 +97,7 @@ public void testChangeListener_topicDescriptionChanged() { } @Test - public void testChangeListener_topicDeprecated() { + void testChangeListener_topicDeprecated() { TopicMetadata metadata = buildTopicMetadata(); metadata.setDeprecated(true); metadata.setDeprecationText("do not use"); @@ -114,7 +115,7 @@ public void testChangeListener_topicDeprecated() { } @Test - public void testChangeListener_topicUndeprecated() { + void testChangeListener_topicUndeprecated() { TopicMetadata metadata = buildTopicMetadata(); TopicEvent event = new TopicEvent(context, metadata); impl.handleTopicUndeprecated(event); @@ -128,7 +129,7 @@ public void testChangeListener_topicUndeprecated() { } @Test - public void testChangeListener_topicSchemaVersionPublished() { + void testChangeListener_topicSchemaVersionPublished() { TopicMetadata metadata = buildTopicMetadata(); SchemaMetadata schema = new SchemaMetadata(); schema.setId("99"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DevUserAclListenerTest.java b/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DevUserAclListenerTest.java index 2cb341b5..87f36f12 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DevUserAclListenerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DevUserAclListenerTest.java @@ -18,7 +18,6 @@ import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.util.FutureUtil; import com.hermesworld.ais.galapagos.util.TimeService; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -33,10 +32,11 @@ import java.util.Optional; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -public class DevUserAclListenerTest { +class DevUserAclListenerTest { @Mock private ApplicationsService applicationsService; @@ -58,7 +58,7 @@ public class DevUserAclListenerTest { private ZonedDateTime timestamp; @BeforeEach - public void initMocks() { + void initMocks() { MockitoAnnotations.openMocks(this); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -80,7 +80,7 @@ public void initMocks() { } @Test - public void testApplicationRegistered_invalidCertificate() throws Exception { + void testApplicationRegistered_invalidCertificate() throws Exception { DevAuthenticationMetadata devAuth = new DevAuthenticationMetadata(); devAuth.setUserName("testuser"); devAuth.setAuthenticationJson("{\"expiresAt\":\"2017-02-03T10:37:30Z\"}"); @@ -106,7 +106,7 @@ public void testApplicationRegistered_invalidCertificate() throws Exception { } @Test - public void testApplicationRegistered() throws Exception { + void testApplicationRegistered() throws Exception { DevAuthenticationMetadata devAuth = new DevAuthenticationMetadata(); devAuth.setUserName("testuser"); devAuth.setAuthenticationJson( @@ -138,11 +138,11 @@ public void testApplicationRegistered() throws Exception { verify(cluster, times(1)).updateUserAcls(userCaptor.capture()); KafkaUser user = userCaptor.getValue(); - Assertions.assertEquals("User:CN=testuser", user.getKafkaUserName()); + assertEquals("User:CN=testuser", user.getKafkaUserName()); } @Test - public void testWriteAccessFlag() throws Exception { + void testWriteAccessFlag() throws Exception { KafkaEnvironmentConfig config = mock(KafkaEnvironmentConfig.class); when(config.isDeveloperWriteAccess()).thenReturn(true); when(cluster.getId()).thenReturn("test"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImplTest.java index ae4833f4..b37bb508 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/devauth/impl/DeveloperAuthenticationServiceImplTest.java @@ -32,7 +32,7 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) -public class DeveloperAuthenticationServiceImplTest { +class DeveloperAuthenticationServiceImplTest { @Mock private KafkaClusters kafkaClusters; @@ -61,7 +61,7 @@ public class DeveloperAuthenticationServiceImplTest { private final TopicBasedRepositoryMock metaRepo = new TopicBasedRepositoryMock<>(); @Test - public void testCreateDeveloperAuthentication_positive() throws Exception { + void testCreateDeveloperAuthentication_positive() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -98,7 +98,7 @@ public void testCreateDeveloperAuthentication_positive() throws Exception { } @Test - public void testCreateDeveloperAuthentication_noUser() { + void testCreateDeveloperAuthentication_noUser() { // given when(userService.getCurrentUserName()).thenReturn(Optional.empty()); @@ -113,7 +113,7 @@ public void testCreateDeveloperAuthentication_noUser() { } @Test - public void testCreateDeveloperAuthentication_invalidEnvironmentId() { + void testCreateDeveloperAuthentication_invalidEnvironmentId() { // given lenient().when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); lenient().when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -131,7 +131,7 @@ public void testCreateDeveloperAuthentication_invalidEnvironmentId() { } @Test - public void testCreateDeveloperAuthentication_deletePreviousAuth() throws Exception { + void testCreateDeveloperAuthentication_deletePreviousAuth() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -175,7 +175,7 @@ public void testCreateDeveloperAuthentication_deletePreviousAuth() throws Except } @Test - public void testGetDeveloperAuthenticationForCurrentUser_positive() throws Exception { + void testGetDeveloperAuthenticationForCurrentUser_positive() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -204,7 +204,7 @@ public void testGetDeveloperAuthenticationForCurrentUser_positive() throws Excep } @Test - public void testGetDeveloperAuthenticationForCurrentUser_wrongUserName() throws Exception { + void testGetDeveloperAuthenticationForCurrentUser_wrongUserName() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -229,7 +229,7 @@ public void testGetDeveloperAuthenticationForCurrentUser_wrongUserName() throws } @Test - public void testGetDeveloperAuthenticationForCurrentUser_noCurrentUser() throws Exception { + void testGetDeveloperAuthenticationForCurrentUser_noCurrentUser() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); @@ -255,7 +255,7 @@ public void testGetDeveloperAuthenticationForCurrentUser_noCurrentUser() throws } @Test - public void testGetDeveloperAuthenticationForCurrentUser_expired() throws Exception { + void testGetDeveloperAuthenticationForCurrentUser_expired() throws Exception { // given when(kafkaClusters.getEnvironment("test")).thenReturn(Optional.of(testCluster)); when(testCluster.getRepository("devauth", DevAuthenticationMetadata.class)).thenReturn(metaRepo); @@ -283,7 +283,7 @@ public void testGetDeveloperAuthenticationForCurrentUser_expired() throws Except } @Test - public void testClearExpiredDeveloperAuthenticationsOnAllClusters_positive() throws Exception { + void testClearExpiredDeveloperAuthenticationsOnAllClusters_positive() throws Exception { // given KafkaCluster cluster2 = mock(KafkaCluster.class); TopicBasedRepositoryMock metaRepo2 = new TopicBasedRepositoryMock<>(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusterTest.java b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusterTest.java index 26843a08..f0d8e97c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusterTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/ConnectedKafkaClusterTest.java @@ -1,8 +1,6 @@ package com.hermesworld.ais.galapagos.kafka.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -21,15 +19,14 @@ import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourcePattern; import org.apache.kafka.common.resource.ResourceType; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import com.hermesworld.ais.galapagos.kafka.KafkaExecutorFactory; import com.hermesworld.ais.galapagos.kafka.KafkaUser; -public class ConnectedKafkaClusterTest { +class ConnectedKafkaClusterTest { @Test - public void testUpdateAcls() throws Exception { + void testUpdateAcls() throws Exception { List deletedAcls = new ArrayList<>(); List createdAcls = new ArrayList<>(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaFutureDecouplerTest.java b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaFutureDecouplerTest.java index 3b6e8226..7736f20f 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaFutureDecouplerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaFutureDecouplerTest.java @@ -1,9 +1,6 @@ package com.hermesworld.ais.galapagos.kafka.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.HashSet; @@ -25,9 +22,9 @@ import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourcePattern; import org.apache.kafka.common.resource.ResourceType; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.kafka.KafkaException; import org.springframework.util.concurrent.FailureCallback; import org.springframework.util.concurrent.ListenableFuture; @@ -36,7 +33,7 @@ import com.hermesworld.ais.galapagos.kafka.KafkaExecutorFactory; -public class KafkaFutureDecouplerTest { +class KafkaFutureDecouplerTest { private static ThreadFactory tfAdminClient = new ThreadFactory() { @Override @@ -58,19 +55,19 @@ public Thread newThread(Runnable r) { private AdminClientStub adminClient; - @Before - public void initAdminClient() { + @BeforeEach + void initAdminClient() { adminClient = new AdminClientStub(); adminClient.setKafkaThreadFactory(tfAdminClient); } - @After - public void closeAdminClient() { + @AfterEach + void closeAdminClient() { adminClient.close(); } @Test - public void testDecoupling_kafkaFuture() throws Exception { + void testDecoupling_kafkaFuture() throws Exception { // first, test that the futures usually would complete on our Threads AtomicBoolean onAdminClientThread = new AtomicBoolean(); adminClient.describeCluster().nodes().thenApply(c -> { @@ -93,7 +90,7 @@ public void testDecoupling_kafkaFuture() throws Exception { } @Test - public void testDecoupling_concatenation() throws Exception { + void testDecoupling_concatenation() throws Exception { List threadNames = new ArrayList(); KafkaFutureDecoupler decoupler = new KafkaFutureDecoupler(executorFactory); @@ -115,11 +112,11 @@ public void testDecoupling_concatenation() throws Exception { } // must be two different Threads! - assertTrue(new HashSet<>(threadNames).size() == 2); + assertEquals(2, new HashSet<>(threadNames).size()); } @Test - public void testDecoupling_listenableFuture() throws Exception { + void testDecoupling_listenableFuture() throws Exception { AtomicBoolean onAdminClientThread = new AtomicBoolean(); // after decoupling, future should complete on another Thread @@ -136,7 +133,7 @@ public void testDecoupling_listenableFuture() throws Exception { } @Test - public void testDecoupling_doneFuture() throws Exception { + void testDecoupling_doneFuture() throws Exception { AtomicInteger factoryInvocations = new AtomicInteger(); KafkaExecutorFactory countingExecutorFactory = () -> { @@ -157,7 +154,7 @@ public void testDecoupling_doneFuture() throws Exception { } @Test - public void testDecoupling_failingFuture() throws Exception { + void testDecoupling_failingFuture() throws Exception { AtomicInteger factoryInvocations = new AtomicInteger(); KafkaExecutorFactory countingExecutorFactory = () -> { @@ -184,7 +181,7 @@ public void testDecoupling_failingFuture() throws Exception { } @Test - public void testDecoupling_failedFuture_direct() throws Exception { + void testDecoupling_failedFuture_direct() throws Exception { AtomicInteger factoryInvocations = new AtomicInteger(); KafkaExecutorFactory countingExecutorFactory = () -> { diff --git a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImplTest.java index 7ba673f9..57a8a049 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/KafkaSenderImplTest.java @@ -1,6 +1,7 @@ package com.hermesworld.ais.galapagos.kafka.impl; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -13,28 +14,16 @@ import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.TopicPartition; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import com.hermesworld.ais.galapagos.kafka.KafkaExecutorFactory; -public class KafkaSenderImplTest { - - private static ThreadFactory tfDecoupled = new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "decoupled-" + System.currentTimeMillis()); - } - }; - - private static KafkaExecutorFactory executorFactory = () -> { - return Executors.newSingleThreadExecutor(tfDecoupled); - }; +class KafkaSenderImplTest { @Test - public void testSendDecoupling() throws Exception { - KafkaFutureDecoupler decoupler = new KafkaFutureDecoupler(executorFactory); + void testSendDecoupling() throws Exception { @SuppressWarnings("unchecked") Producer producer = mock(Producer.class); @@ -56,12 +45,12 @@ public void testSendDecoupling() throws Exception { KafkaTemplate template = new KafkaTemplate(factory); - KafkaSenderImpl sender = new KafkaSenderImpl(template, decoupler); + KafkaSenderImpl sender = new KafkaSenderImpl(template); StringBuilder threadName = new StringBuilder(); sender.send("a", "b", "c").thenApply(o -> threadName.append(Thread.currentThread().getName())).get(); - assertTrue(threadName.toString().startsWith("decoupled-")); + assertFalse(threadName.toString().startsWith("decoupled-")); } } diff --git a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/TopicBasedRepositoryImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/TopicBasedRepositoryImplTest.java index 12df0072..436a5e50 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/TopicBasedRepositoryImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/kafka/impl/TopicBasedRepositoryImplTest.java @@ -5,8 +5,8 @@ import com.hermesworld.ais.galapagos.util.FutureUtil; import com.hermesworld.ais.galapagos.util.JsonUtil; import org.json.JSONObject; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.Map; @@ -16,25 +16,25 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class TopicBasedRepositoryImplTest { +class TopicBasedRepositoryImplTest { private final KafkaSender sender = mock(KafkaSender.class); private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1); - @After - public void shutdownExecutor() throws Exception { + @AfterEach + void shutdownExecutor() throws Exception { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.SECONDS); } @Test - public void testMessageReceived() throws Exception { + void testMessageReceived() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); assertEquals(ApplicationMetadata.class, repository.getValueClass()); @@ -54,7 +54,7 @@ public void testMessageReceived() throws Exception { } @Test - public void testMessageReceived_wrongTopic() throws Exception { + void testMessageReceived_wrongTopic() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -70,7 +70,7 @@ public void testMessageReceived_wrongTopic() throws Exception { } @Test - public void testWaitForInitialization_emptyRepository() throws Exception { + void testWaitForInitialization_emptyRepository() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -79,13 +79,13 @@ public void testWaitForInitialization_emptyRepository() throws Exception { Duration.ofMillis(100), executorService); future.get(); - assertTrue("Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 300 ms", - System.currentTimeMillis() >= startTime + 300); + assertTrue(System.currentTimeMillis() >= startTime + 300, + "Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 300 ms"); assertFalse(System.currentTimeMillis() >= startTime + 1000); } @Test - public void testWaitForInitialization_positive() throws Exception { + void testWaitForInitialization_positive() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -99,13 +99,13 @@ public void testWaitForInitialization_positive() throws Exception { future.get(); - assertTrue("Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 350 ms", - System.currentTimeMillis() >= startTime + 350); + assertTrue(System.currentTimeMillis() >= startTime + 350, + "Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 350 ms"); assertFalse(System.currentTimeMillis() >= startTime + 1000); } @Test - public void testWaitForInitialization_tooLateDataStart() throws Exception { + void testWaitForInitialization_tooLateDataStart() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -119,11 +119,11 @@ public void testWaitForInitialization_tooLateDataStart() throws Exception { future.get(); - assertFalse("Repository waited too long", System.currentTimeMillis() >= startTime + 349); + assertFalse(System.currentTimeMillis() >= startTime + 349, "Repository waited too long"); } @Test - public void testWaitForInitialization_tooLateData() throws Exception { + void testWaitForInitialization_tooLateData() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -139,20 +139,20 @@ public void testWaitForInitialization_tooLateData() throws Exception { future.get(); - assertTrue("Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 350 ms", - System.currentTimeMillis() >= startTime + 350); - assertFalse("Repository waited too long", System.currentTimeMillis() >= startTime + 399); + assertTrue(System.currentTimeMillis() >= startTime + 350, + "Implementation only waited " + (System.currentTimeMillis() - startTime) + " ms instead of 350 ms"); + assertFalse(System.currentTimeMillis() >= startTime + 399, "Repository waited too long"); } @Test - public void testGetTopicName() { + void testGetTopicName() { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); assertEquals("testtopic", repository.getTopicName()); } @Test - public void testSave() throws Exception { + void testSave() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); @@ -182,7 +182,7 @@ public void testSave() throws Exception { } @Test - public void testDelete() throws Exception { + void testDelete() throws Exception { TopicBasedRepositoryImpl repository = new TopicBasedRepositoryImpl<>("galapagos.testtopic", "testtopic", ApplicationMetadata.class, sender); diff --git a/src/test/java/com/hermesworld/ais/galapagos/kafka/util/AclSupportTest.java b/src/test/java/com/hermesworld/ais/galapagos/kafka/util/AclSupportTest.java index 3fe1027f..db7dbf6c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/kafka/util/AclSupportTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/kafka/util/AclSupportTest.java @@ -29,7 +29,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -public class AclSupportTest { +class AclSupportTest { private static final List WRITE_TOPIC_OPERATIONS = Arrays.asList( new AclOperationAndType(AclOperation.ALL, AclPermissionType.ALLOW), @@ -49,12 +49,12 @@ public class AclSupportTest { private SubscriptionService subscriptionService; @BeforeEach - public void initMocks() { + void initMocks() { } @Test - public void testGetRequiredAclBindings_simple() { + void testGetRequiredAclBindings_simple() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("app01"); metadata.setConsumerGroupPrefixes(List.of("group.myapp.", "group2.myapp.")); @@ -81,8 +81,7 @@ public void testGetRequiredAclBindings_simple() { when(topicService.listTopics("_test")).thenReturn(List.of(topic1, topic2)); when(topicService.getTopic("_test", "topic2")).thenReturn(Optional.of(topic2)); - when(subscriptionService.getSubscriptionsOfApplication("_test", "app01", false)) - .thenReturn(Collections.singletonList(sub)); + when(subscriptionService.getSubscriptionsOfApplication("_test", "app01", false)).thenReturn(List.of(sub)); AclSupport aclSupport = new AclSupport(kafkaConfig, topicService, subscriptionService); @@ -138,7 +137,7 @@ public void testGetRequiredAclBindings_simple() { } @Test - public void testNoWriteAclsForInternalTopics() { + void testNoWriteAclsForInternalTopics() { ApplicationMetadata app1 = new ApplicationMetadata(); app1.setApplicationId("app-1"); app1.setConsumerGroupPrefixes(List.of("groups.")); @@ -158,7 +157,7 @@ public void testNoWriteAclsForInternalTopics() { } @Test - public void testAdditionalProducerWriteAccess() { + void testAdditionalProducerWriteAccess() { ApplicationMetadata app1 = new ApplicationMetadata(); app1.setApplicationId("app-1"); @@ -187,7 +186,7 @@ public void testAdditionalProducerWriteAccess() { } @Test - public void testDefaultAcls() { + void testDefaultAcls() { ApplicationMetadata app1 = new ApplicationMetadata(); app1.setApplicationId("app-1"); app1.setAuthenticationJson(new JSONObject(Map.of("dn", "CN=testapp")).toString()); @@ -215,7 +214,7 @@ public void testDefaultAcls() { } @Test - public void testReadOnlyAcls() { + void testReadOnlyAcls() { ApplicationMetadata metadata = new ApplicationMetadata(); metadata.setApplicationId("app01"); metadata.setConsumerGroupPrefixes(List.of("group.myapp.", "group2.myapp.")); @@ -242,8 +241,7 @@ public void testReadOnlyAcls() { when(topicService.listTopics("_test")).thenReturn(List.of(topic1, topic2)); when(topicService.getTopic("_test", "topic2")).thenReturn(Optional.of(topic2)); - when(subscriptionService.getSubscriptionsOfApplication("_test", "app01", false)) - .thenReturn(Collections.singletonList(sub)); + when(subscriptionService.getSubscriptionsOfApplication("_test", "app01", false)).thenReturn(List.of(sub)); AclSupport aclSupport = new AclSupport(kafkaConfig, topicService, subscriptionService); @@ -288,7 +286,7 @@ public void testReadOnlyAcls() { } @Test - public void testSimplify() { + void testSimplify() { AclSupport support = new AclSupport(kafkaConfig, topicService, subscriptionService); AclBinding superfluousBinding = new AclBinding( diff --git a/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingIntegrationTest.java b/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingIntegrationTest.java index c79d8721..1623c4d6 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingIntegrationTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingIntegrationTest.java @@ -1,20 +1,17 @@ package com.hermesworld.ais.galapagos.naming.config; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource(locations = "classpath:test-case-strategies.properties") -public class CaseStrategyConverterBindingIntegrationTest { +class CaseStrategyConverterBindingIntegrationTest { @Autowired private NamingConfig config; @@ -23,7 +20,7 @@ public class CaseStrategyConverterBindingIntegrationTest { private KafkaClusters clusters; @Test - public void testConversion() { + void testConversion() { assertEquals(CaseStrategy.PASCAL_CASE, config.getNormalizationStrategy()); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingTest.java b/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingTest.java index 5782057c..4be87c2c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/naming/config/CaseStrategyConverterBindingTest.java @@ -1,13 +1,14 @@ package com.hermesworld.ais.galapagos.naming.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class CaseStrategyConverterBindingTest { +class CaseStrategyConverterBindingTest { @Test - public void testValidValues() { + void testValidValues() { CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); assertEquals(CaseStrategy.PASCAL_CASE, converter.convert("PascalCase")); assertEquals(CaseStrategy.CAMEL_CASE, converter.convert("camelCase")); @@ -16,22 +17,28 @@ public void testValidValues() { assertEquals(CaseStrategy.LOWERCASE, converter.convert("lowercase")); } - @Test(expected = IllegalArgumentException.class) - public void testNoCaseConversion() { - CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); - converter.convert("pascalCase"); + @Test + void testNoCaseConversion() { + assertThrows(IllegalArgumentException.class, () -> { + CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); + converter.convert("pascalCase"); + }); } - @Test(expected = IllegalArgumentException.class) - public void testNoEnumNameUse() { - CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); - converter.convert("PASCAL_CASE"); + @Test + void testNoEnumNameUse() { + assertThrows(IllegalArgumentException.class, () -> { + CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); + converter.convert("PASCAL_CASE"); + }); } - @Test(expected = IllegalArgumentException.class) - public void testInvalidValue() { - CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); - converter.convert("someValue"); + @Test + void testInvalidValue() { + assertThrows(IllegalArgumentException.class, () -> { + CaseStrategyConverterBinding converter = new CaseStrategyConverterBinding(); + converter.convert("someValue"); + }); } } diff --git a/src/test/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImplTest.java index a7d7b1ab..484832f6 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/naming/impl/NamingServiceImplTest.java @@ -9,17 +9,17 @@ import com.hermesworld.ais.galapagos.naming.config.NamingConfig; import com.hermesworld.ais.galapagos.naming.config.TopicNamingConfig; import com.hermesworld.ais.galapagos.topics.TopicType; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class NamingServiceImplTest { +class NamingServiceImplTest { private AdditionNamingRules rules; @@ -31,8 +31,8 @@ public class NamingServiceImplTest { private BusinessCapability cap2; - @Before - public void feedMocks() { + @BeforeEach + void feedMocks() { rules = new AdditionNamingRules(); rules.setAllowedSeparators("."); rules.setAllowPascalCase(true); @@ -63,7 +63,7 @@ public void feedMocks() { } @Test - public void testAllowInternalTopicNamesForConsumerGroups() { + void testAllowInternalTopicNamesForConsumerGroups() { config.setAllowInternalTopicNamesAsConsumerGroups(true); NamingServiceImpl service = new NamingServiceImpl(config); ApplicationPrefixes prefixes = service.getAllowedPrefixes(app); @@ -85,7 +85,7 @@ public void testAllowInternalTopicNamesForConsumerGroups() { } @Test - public void testGetTopicNameSuggestion() { + void testGetTopicNameSuggestion() { NamingServiceImpl service = new NamingServiceImpl(config); assertEquals("de.hlg.events.orders.my-topic", service.getTopicNameSuggestion(TopicType.EVENTS, app, cap1)); @@ -100,7 +100,7 @@ public void testGetTopicNameSuggestion() { } @Test - public void testGetAllowedPrefixes() { + void testGetAllowedPrefixes() { when(app.getAliases()).thenReturn(Set.of("tt")); NamingServiceImpl service = new NamingServiceImpl(config); @@ -131,7 +131,7 @@ public void testGetAllowedPrefixes() { } @Test - public void testValidateTopicName() throws InvalidTopicNameException { + void testValidateTopicName() throws InvalidTopicNameException { NamingServiceImpl service = new NamingServiceImpl(config); service.validateTopicName("de.hlg.events.orders.my-custom-order", TopicType.EVENTS, app); @@ -173,7 +173,7 @@ public void testValidateTopicName() throws InvalidTopicNameException { } @Test - public void testNormalize_simpleCases() { + void testNormalize_simpleCases() { NamingConfig config = mock(NamingConfig.class); when(config.getNormalizationStrategy()).thenReturn(CaseStrategy.PASCAL_CASE); @@ -194,7 +194,7 @@ public void testNormalize_simpleCases() { } @Test - public void testNormalize_lead_trail() { + void testNormalize_lead_trail() { NamingConfig config = mock(NamingConfig.class); when(config.getNormalizationStrategy()).thenReturn(CaseStrategy.KEBAB_CASE); NamingServiceImpl service = new NamingServiceImpl(config); @@ -206,7 +206,7 @@ public void testNormalize_lead_trail() { } @Test - public void testNormalize_localization() { + void testNormalize_localization() { NamingConfig config = mock(NamingConfig.class); when(config.getNormalizationStrategy()).thenReturn(CaseStrategy.KEBAB_CASE); NamingServiceImpl service = new NamingServiceImpl(config); diff --git a/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListenerTest.java b/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListenerTest.java index 3e238d7c..136d54f4 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListenerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationEventListenerTest.java @@ -14,20 +14,20 @@ import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.FutureUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -public class NotificationEventListenerTest { +class NotificationEventListenerTest { private NotificationEventListener listener; @@ -35,8 +35,8 @@ public class NotificationEventListenerTest { private GalapagosEventContext context; - @Before - public void feedMocks() { + @BeforeEach + void feedMocks() { notificationService = spy(mock(NotificationService.class)); KafkaClusters kafkaClusters = mock(KafkaClusters.class); @@ -58,7 +58,7 @@ public void feedMocks() { } @Test - public void testHandleTopicDeprecated() { + void testHandleTopicDeprecated() { AtomicInteger sendCalled = new AtomicInteger(); when(notificationService.notifySubscribers(any(), any(), any(), any())).then(inv -> { sendCalled.incrementAndGet(); @@ -69,11 +69,11 @@ public void testHandleTopicDeprecated() { listener.handleTopicDeprecated(buildTestEvent("test2")); listener.handleTopicDeprecated(buildTestEvent("prod")); - assertEquals("Deprecation mail should only be sent for production environment", 1, sendCalled.get()); + assertEquals(1, sendCalled.get(), "Deprecation mail should only be sent for production environment"); } @Test - public void testHandleTopicUndeprecated() { + void testHandleTopicUndeprecated() { AtomicInteger sendCalled = new AtomicInteger(); when(notificationService.notifySubscribers(any(), any(), any(), any())).then(inv -> { sendCalled.incrementAndGet(); @@ -84,11 +84,11 @@ public void testHandleTopicUndeprecated() { listener.handleTopicUndeprecated(buildTestEvent("test2")); listener.handleTopicUndeprecated(buildTestEvent("prod")); - assertEquals("Undeprecation mail should only be sent for production environment", 1, sendCalled.get()); + assertEquals(1, sendCalled.get(), "Undeprecation mail should only be sent for production environment"); } @Test - public void testHandleSchemaChangeDesc() throws ExecutionException, InterruptedException { + void testHandleSchemaChangeDesc() throws ExecutionException, InterruptedException { TopicMetadata metadata = new TopicMetadata(); metadata.setName("testtopic"); diff --git a/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImplTest.java index 262f20ff..4f95ec51 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/notifications/impl/NotificationServiceImplTest.java @@ -9,10 +9,10 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; -import javax.mail.Address; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMessage.RecipientType; +import jakarta.mail.Address; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import jakarta.mail.internet.MimeMessage.RecipientType; import com.hermesworld.ais.galapagos.applications.ApplicationOwnerRequest; import com.hermesworld.ais.galapagos.applications.ApplicationsService; @@ -21,11 +21,12 @@ import com.hermesworld.ais.galapagos.subscriptions.SubscriptionMetadata; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.topics.service.TopicService; -import org.junit.After; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import static org.mockito.Mockito.*; import org.springframework.mail.MailSendException; @@ -33,7 +34,7 @@ import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; import org.thymeleaf.ITemplateEngine; -public class NotificationServiceImplTest { +class NotificationServiceImplTest { private static final String TEST_ENV = "test-Environment"; @@ -55,8 +56,8 @@ public class NotificationServiceImplTest { private MimeMessageHolder messageHolder; - @Before - public void feedMocks() throws MessagingException { + @BeforeEach + void feedMocks() throws MessagingException { subscriptionService = mock(SubscriptionService.class); applicationService = mock(ApplicationsService.class); topicService = mock(TopicService.class); @@ -70,13 +71,13 @@ public void feedMocks() throws MessagingException { executor = Executors.newSingleThreadExecutor(); } - @After - public void destroyMocks() { + @AfterEach + void destroyMocks() { executor.shutdown(); } @Test - public void testDoSendAsync_NoFailOnMailException() throws Exception { + void testDoSendAsync_NoFailOnMailException() throws Exception { String testFromAddress = "test@abc.de"; String testAdminMailsRecipients = "Test@abc.de"; NotificationParams testNotificationParams = generateNotificationParams(TEST_USER, TEST_TOPIC); @@ -94,7 +95,7 @@ public void testDoSendAsync_NoFailOnMailException() throws Exception { } @Test - public void testNotifySubscribersWithExclusionUser() throws Exception { + void testNotifySubscribersWithExclusionUser() throws Exception { String testFromAddress = "test@abc.de"; String testAdminMailsRecipients = "Test@abc.de"; String testApplicationId = "42"; @@ -123,7 +124,7 @@ public void testNotifySubscribersWithExclusionUser() throws Exception { } @Test - public void testNotifyApplicationTopicOwners_noSubmittedIncluded() throws Exception { + void testNotifyApplicationTopicOwners_noSubmittedIncluded() throws Exception { String testFromAddress = "test@abc.de"; String testAdminMailsRecipients = "Test@abc.de"; String applicationId = "1"; @@ -171,7 +172,7 @@ public void testNotifyApplicationTopicOwners_noSubmittedIncluded() throws Except } @Test - public void testNotifySubscribers_noSubmittedIncluded() throws Exception { + void testNotifySubscribers_noSubmittedIncluded() throws Exception { String testFromAddress = "test@abc.de"; String testAdminMailsRecipients = "Test@abc.de"; NotificationParams testNotificationParams = generateNotificationParams(TEST_USER, TEST_TOPIC); diff --git a/src/test/java/com/hermesworld/ais/galapagos/request/ApplicationOwnerRequestTest.java b/src/test/java/com/hermesworld/ais/galapagos/request/ApplicationOwnerRequestTest.java index 5546e983..8bed6ef0 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/request/ApplicationOwnerRequestTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/request/ApplicationOwnerRequestTest.java @@ -1,19 +1,18 @@ package com.hermesworld.ais.galapagos.request; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.ObjectMapper; import com.hermesworld.ais.galapagos.applications.ApplicationOwnerRequest; import com.hermesworld.ais.galapagos.applications.RequestState; import com.hermesworld.ais.galapagos.util.JsonUtil; +import org.junit.jupiter.api.Test; -public class ApplicationOwnerRequestTest { +class ApplicationOwnerRequestTest { @Test - public void testApplicationOwnerRequestSerializable() throws Exception { + void testApplicationOwnerRequestSerializable() throws Exception { ObjectMapper mapper = JsonUtil.newObjectMapper(); ApplicationOwnerRequest request = new ApplicationOwnerRequest(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/schema/SchemaUtilTest.java b/src/test/java/com/hermesworld/ais/galapagos/schema/SchemaUtilTest.java index 3f46f203..7c604bd6 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/schema/SchemaUtilTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/schema/SchemaUtilTest.java @@ -5,122 +5,144 @@ import org.everit.json.schema.Schema; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.StreamUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -public class SchemaUtilTest { +import static org.junit.jupiter.api.Assertions.assertThrows; - @Test(expected = IncompatibleSchemaException.class) - public void testAddAdditionalPropertiesOnObject_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test01a"), readSchema("test01b")); +class SchemaUtilTest { + + @Test + void testAddAdditionalPropertiesOnObject_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test01a"), readSchema("test01b")); + }); } @Test - public void testAddRequiredPropertyOnObject_success() throws Exception { + void testAddRequiredPropertyOnObject_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test02a"), readSchema("test02b")); } @Test - public void testRemoveOneOfSchema_success() throws Exception { + void testRemoveOneOfSchema_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test03a"), readSchema("test03b")); } - @Test(expected = IncompatibleSchemaException.class) - public void testAddOneOfSchema_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test03a"), readSchema("test03c")); + @Test + void testAddOneOfSchema_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test03a"), readSchema("test03c")); + }); } @Test - public void testAddArrayRestriction_success() throws Exception { + void testAddArrayRestriction_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test03a"), readSchema("test03d")); } - @Test(expected = IncompatibleSchemaException.class) - public void testRelaxArrayRestriction_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test03d"), readSchema("test03e")); + @Test + void testRelaxArrayRestriction_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test03d"), readSchema("test03e")); + }); } @Test - public void testAddPropertyWithAdditionalProperties_success() throws Exception { + void testAddPropertyWithAdditionalProperties_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test04a"), readSchema("test04b")); } @Test - public void testAddStringLimits_success() throws Exception { + void testAddStringLimits_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test04a"), readSchema("test04c")); } - @Test(expected = IncompatibleSchemaException.class) - public void testRelaxStringLimits_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test04c"), readSchema("test04d")); + @Test + void testRelaxStringLimits_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test04c"), readSchema("test04d")); + }); } @Test - public void testRemoveEnumValue_success() throws Exception { + void testRemoveEnumValue_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test05a"), readSchema("test05b")); } - @Test(expected = IncompatibleSchemaException.class) - public void testAddEnumValue_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test05a"), readSchema("test05c")); + @Test + void testAddEnumValue_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test05a"), readSchema("test05c")); + }); } @Test - public void testNotMoreGreedy_success() throws Exception { + void testNotMoreGreedy_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test06a"), readSchema("test06b")); } - @Test(expected = IncompatibleSchemaException.class) - public void testNotMoreStrict_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test06a"), readSchema("test06c")); + @Test + void testNotMoreStrict_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test06a"), readSchema("test06c")); + }); } - @Test(expected = IncompatibleSchemaException.class) - public void testTotallyDifferent_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test01a"), readSchema("test03a")); + @Test + void testTotallyDifferent_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test01a"), readSchema("test03a")); + }); } @Test - public void testAnyOfReplacedBySubschema_success() throws Exception { + void testAnyOfReplacedBySubschema_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test07a"), readSchema("test07b")); } - @Test(expected = IncompatibleSchemaException.class) - public void testAnyOfReplacedByIncompatibleSchema_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test07a"), readSchema("test07c")); + @Test + void testAnyOfReplacedByIncompatibleSchema_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test07a"), readSchema("test07c")); + }); } - @Test(expected = IncompatibleSchemaException.class) - public void testIntegerToNumber_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test08a"), readSchema("test08b")); + @Test + void testIntegerToNumber_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test08a"), readSchema("test08b")); + }); } @Test - public void testIntegerStaysInteger_success() throws Exception { + void testIntegerStaysInteger_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test08a"), readSchema("test08c")); } @Test - public void testNumberToInteger_success() throws Exception { + void testNumberToInteger_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test08b"), readSchema("test08a")); } @Test - public void testRemoveOptionalWithNoAdditionalProperties_success() throws Exception { + void testRemoveOptionalWithNoAdditionalProperties_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test09a"), readSchema("test09b")); } - @Test(expected = IncompatibleSchemaException.class) - public void testRemoveOptionalWithAdditionalProperties_fail() throws Exception { - SchemaUtil.verifyCompatibleTo(readSchema("test09a"), readSchema("test09c")); + @Test + void testRemoveOptionalWithAdditionalProperties_fail() throws Exception { + assertThrows(IncompatibleSchemaException.class, () -> { + SchemaUtil.verifyCompatibleTo(readSchema("test09a"), readSchema("test09c")); + }); } @Test - public void testPatternField_success() throws Exception { + void testPatternField_success() throws Exception { SchemaUtil.verifyCompatibleTo(readSchema("test-pattern-field"), readSchema("test-pattern-field-with-another-prop")); } diff --git a/src/test/java/com/hermesworld/ais/galapagos/staging/impl/StagingImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/staging/impl/StagingImplTest.java index 62284b01..a03b8dd6 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/staging/impl/StagingImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/staging/impl/StagingImplTest.java @@ -11,24 +11,23 @@ import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.JsonUtil; -import org.junit.Test; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class StagingImplTest { +class StagingImplTest { @Test - public void testSubscriptionIdentity() throws Exception { + void testSubscriptionIdentity() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -36,8 +35,8 @@ public void testSubscriptionIdentity() throws Exception { topic1.setOwnerApplicationId("app-2"); topic1.setType(TopicType.EVENTS); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); - when(topicService.listTopics("int")).thenReturn(Collections.singletonList(topic1)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); + when(topicService.listTopics("int")).thenReturn(List.of(topic1)); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -45,8 +44,7 @@ public void testSubscriptionIdentity() throws Exception { sub1.setClientApplicationId("app-1"); sub1.setId("123"); sub1.setTopicName("topic-1"); - when(subscriptionService.getSubscriptionsOfApplication("dev", "app-1", false)) - .thenReturn(Collections.singletonList(sub1)); + when(subscriptionService.getSubscriptionsOfApplication("dev", "app-1", false)).thenReturn(List.of(sub1)); StagingImpl staging = StagingImpl.build("app-1", "dev", "int", null, topicService, subscriptionService).get(); @@ -62,8 +60,7 @@ public void testSubscriptionIdentity() throws Exception { sub2.setClientApplicationId("app-1"); sub2.setId("456"); sub2.setTopicName("topic-1"); - when(subscriptionService.getSubscriptionsOfApplication("int", "app-1", false)) - .thenReturn(Collections.singletonList(sub2)); + when(subscriptionService.getSubscriptionsOfApplication("int", "app-1", false)).thenReturn(List.of(sub2)); staging = StagingImpl.build("app-1", "dev", "int", null, topicService, subscriptionService).get(); changes = staging.getChanges(); @@ -72,7 +69,7 @@ public void testSubscriptionIdentity() throws Exception { @Test @DisplayName("should stage new added producer to next stage") - public void testProducerAddStaging() throws Exception { + void testProducerAddStaging() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -86,8 +83,8 @@ public void testProducerAddStaging() throws Exception { topic2.setOwnerApplicationId("app-1"); topic2.setType(TopicType.EVENTS); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); - when(topicService.listTopics("int")).thenReturn(Collections.singletonList(topic2)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); + when(topicService.listTopics("int")).thenReturn(List.of(topic2)); StagingImpl staging = StagingImpl .build("app-1", "dev", "int", null, topicService, mock(SubscriptionService.class)).get(); @@ -106,7 +103,7 @@ public void testProducerAddStaging() throws Exception { @Test @DisplayName("should stage removed producer to next stage") - public void testProducerRemoveStaging() throws Exception { + void testProducerRemoveStaging() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -121,8 +118,8 @@ public void testProducerRemoveStaging() throws Exception { topic2.setType(TopicType.EVENTS); topic2.setProducers(List.of("producer1")); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); - when(topicService.listTopics("int")).thenReturn(Collections.singletonList(topic2)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); + when(topicService.listTopics("int")).thenReturn(List.of(topic2)); List producers = new ArrayList<>(topic1.getProducers()); producers.remove("producer1"); @@ -138,7 +135,7 @@ public void testProducerRemoveStaging() throws Exception { } @Test - public void testSchemaIdentity() throws Exception { + void testSchemaIdentity() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -146,8 +143,8 @@ public void testSchemaIdentity() throws Exception { topic1.setOwnerApplicationId("app-1"); topic1.setType(TopicType.EVENTS); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); - when(topicService.listTopics("int")).thenReturn(Collections.singletonList(topic1)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); + when(topicService.listTopics("int")).thenReturn(List.of(topic1)); SchemaMetadata schema1 = new SchemaMetadata(); schema1.setId("999"); @@ -155,7 +152,7 @@ public void testSchemaIdentity() throws Exception { schema1.setCreatedBy("test"); schema1.setTopicName("topic-1"); - when(topicService.getTopicSchemaVersions("dev", "topic-1")).thenReturn(Collections.singletonList(schema1)); + when(topicService.getTopicSchemaVersions("dev", "topic-1")).thenReturn(List.of(schema1)); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -174,7 +171,7 @@ public void testSchemaIdentity() throws Exception { schema2.setCreatedBy("test"); schema2.setTopicName("topic-1"); schema2.setSchemaVersion(1); - when(topicService.getTopicSchemaVersions("int", "topic-1")).thenReturn(Collections.singletonList(schema2)); + when(topicService.getTopicSchemaVersions("int", "topic-1")).thenReturn(List.of(schema2)); staging = StagingImpl.build("app-1", "dev", "int", null, topicService, subscriptionService).get(); changes = staging.getChanges(); @@ -182,7 +179,7 @@ public void testSchemaIdentity() throws Exception { } @Test - public void testCompoundChangeForApiTopicCreation() throws Exception { + void testCompoundChangeForApiTopicCreation() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -190,7 +187,7 @@ public void testCompoundChangeForApiTopicCreation() throws Exception { topic1.setOwnerApplicationId("app-1"); topic1.setType(TopicType.EVENTS); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); when(topicService.buildTopicCreateParams("dev", "topic-1")) .thenReturn(CompletableFuture.completedFuture(new TopicCreateParams(2, 2))); @@ -227,7 +224,7 @@ public void testCompoundChangeForApiTopicCreation() throws Exception { } @Test - public void testApiTopicWithoutSchema_fail() throws Exception { + void testApiTopicWithoutSchema_fail() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -235,7 +232,7 @@ public void testApiTopicWithoutSchema_fail() throws Exception { topic1.setOwnerApplicationId("app-1"); topic1.setType(TopicType.EVENTS); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -254,7 +251,7 @@ public void testApiTopicWithoutSchema_fail() throws Exception { } @Test - public void testStageDeprecatedTopic_fail() throws Exception { + void testStageDeprecatedTopic_fail() throws Exception { TopicService topicService = mock(TopicService.class); TopicMetadata topic1 = new TopicMetadata(); @@ -263,7 +260,7 @@ public void testStageDeprecatedTopic_fail() throws Exception { topic1.setType(TopicType.EVENTS); topic1.setDeprecated(true); - when(topicService.listTopics("dev")).thenReturn(Collections.singletonList(topic1)); + when(topicService.listTopics("dev")).thenReturn(List.of(topic1)); SubscriptionService subscriptionService = mock(SubscriptionService.class); diff --git a/src/test/java/com/hermesworld/ais/galapagos/subscriptions/SubscriptionsControllerTest.java b/src/test/java/com/hermesworld/ais/galapagos/subscriptions/SubscriptionsControllerTest.java index 5691b4d7..94310807 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/subscriptions/SubscriptionsControllerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/subscriptions/SubscriptionsControllerTest.java @@ -1,15 +1,17 @@ package com.hermesworld.ais.galapagos.subscriptions; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; @@ -23,7 +25,7 @@ import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.FutureUtil; -public class SubscriptionsControllerTest { +class SubscriptionsControllerTest { private KafkaClusters kafkaClusters; @@ -35,8 +37,8 @@ public class SubscriptionsControllerTest { private SubscriptionMetadata subscription = new SubscriptionMetadata(); - @Before - public void initMocks() { + @BeforeEach + void initMocks() { subscription.setId("sub-1"); subscription.setTopicName("topic-1"); subscription.setClientApplicationId("app-1"); @@ -49,7 +51,7 @@ public void initMocks() { } @Test - public void testUpdateSubscription_positive() throws Exception { + void testUpdateSubscription_positive() throws Exception { TopicMetadata topic1 = new TopicMetadata(); topic1.setName("topic-1"); topic1.setOwnerApplicationId("app-2"); @@ -79,7 +81,7 @@ public void testUpdateSubscription_positive() throws Exception { } @Test - public void testUpdateSubscription_invalidUser_clientAppOwner() throws Exception { + void testUpdateSubscription_invalidUser_clientAppOwner() throws Exception { TopicMetadata topic = new TopicMetadata(); topic.setName("topic-1"); topic.setOwnerApplicationId("app-2"); @@ -104,12 +106,12 @@ public void testUpdateSubscription_invalidUser_clientAppOwner() throws Exception fail("Expected FORBIDDEN for owner of CLIENT application"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); + assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); } } @Test - public void testUpdateSubscription_invalidTopic_forSubscription() throws Exception { + void testUpdateSubscription_invalidTopic_forSubscription() throws Exception { TopicMetadata topic1 = new TopicMetadata(); topic1.setName("topic-1"); topic1.setOwnerApplicationId("app-2"); @@ -137,12 +139,12 @@ public void testUpdateSubscription_invalidTopic_forSubscription() throws Excepti fail("Expected NOT_FOUND as subscription does not match topic"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.NOT_FOUND, e.getStatus()); + assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode()); } } @Test - public void testUpdateSubscription_topicHasFlagNotSet() throws Exception { + void testUpdateSubscription_topicHasFlagNotSet() throws Exception { TopicMetadata topic1 = new TopicMetadata(); topic1.setName("topic-1"); topic1.setOwnerApplicationId("app-2"); @@ -164,7 +166,7 @@ public void testUpdateSubscription_topicHasFlagNotSet() throws Exception { fail("Expected BAD_REQUEST for updating subscription state for topic which does not require subscription approval"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.BAD_REQUEST, e.getStatus()); + assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } } diff --git a/src/test/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImplTest.java index 18d43810..c022f16c 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/subscriptions/service/impl/SubscriptionServiceImplTest.java @@ -15,13 +15,15 @@ import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.topics.service.TopicService; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class SubscriptionServiceImplTest { +class SubscriptionServiceImplTest { private KafkaClusters kafkaClusters; @@ -33,8 +35,8 @@ public class SubscriptionServiceImplTest { private TopicBasedRepositoryMock repository; - @Before - public void setupMocks() { + @BeforeEach + void setupMocks() { kafkaClusters = mock(KafkaClusters.class); KafkaCluster testCluster = mock(KafkaCluster.class); @@ -75,7 +77,7 @@ public void setupMocks() { } @Test - public void testAddSubscription_positive() throws Exception { + void testAddSubscription_positive() throws Exception { SubscriptionServiceImpl service = new SubscriptionServiceImpl(kafkaClusters, applicationsService, topicService, eventManager); @@ -93,7 +95,7 @@ public void testAddSubscription_positive() throws Exception { } @Test - public void testAddSubscription_pending() throws Exception { + void testAddSubscription_pending() throws Exception { SubscriptionServiceImpl service = new SubscriptionServiceImpl(kafkaClusters, applicationsService, topicService, eventManager); @@ -111,7 +113,7 @@ public void testAddSubscription_pending() throws Exception { } @Test - public void testAddSubscription_fail_internalTopic() throws Exception { + void testAddSubscription_fail_internalTopic() throws Exception { SubscriptionServiceImpl service = new SubscriptionServiceImpl(kafkaClusters, applicationsService, topicService, eventManager); @@ -127,7 +129,7 @@ public void testAddSubscription_fail_internalTopic() throws Exception { } @Test - public void testAddSubscription_directMetadata() throws Exception { + void testAddSubscription_directMetadata() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.APPROVED); @@ -145,7 +147,7 @@ public void testAddSubscription_directMetadata() throws Exception { } @Test - public void testUpdateSubscriptionState_positive() throws Exception { + void testUpdateSubscriptionState_positive() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.PENDING); @@ -168,7 +170,7 @@ public void testUpdateSubscriptionState_positive() throws Exception { } @Test - public void testUpdateSubscriptionState_rejected_deletes() throws Exception { + void testUpdateSubscriptionState_rejected_deletes() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.PENDING); @@ -190,7 +192,7 @@ public void testUpdateSubscriptionState_rejected_deletes() throws Exception { } @Test - public void testUpdateSubscriptionState_canceled_deletes() throws Exception { + void testUpdateSubscriptionState_canceled_deletes() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.APPROVED); @@ -212,7 +214,7 @@ public void testUpdateSubscriptionState_canceled_deletes() throws Exception { } @Test - public void testUpdateSubscriptionState_rejected_mapsToCanceled() throws Exception { + void testUpdateSubscriptionState_rejected_mapsToCanceled() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.APPROVED); @@ -236,7 +238,7 @@ public void testUpdateSubscriptionState_rejected_mapsToCanceled() throws Excepti } @Test - public void testUpdateSubscriptionState_noop() throws Exception { + void testUpdateSubscriptionState_noop() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.APPROVED); @@ -255,7 +257,7 @@ public void testUpdateSubscriptionState_noop() throws Exception { } @Test - public void testDeleteSubscription() throws Exception { + void testDeleteSubscription() throws Exception { SubscriptionMetadata sub = new SubscriptionMetadata(); sub.setId("123"); sub.setState(SubscriptionState.APPROVED); @@ -275,7 +277,7 @@ public void testDeleteSubscription() throws Exception { } @Test - public void testGetSubscriptionsForTopic() throws Exception { + void testGetSubscriptionsForTopic() throws Exception { SubscriptionMetadata sub1 = new SubscriptionMetadata(); sub1.setId("123"); sub1.setState(SubscriptionState.APPROVED); @@ -303,7 +305,7 @@ public void testGetSubscriptionsForTopic() throws Exception { } @Test - public void testGetSubscriptionsOfApplication() throws Exception { + void testGetSubscriptionsOfApplication() throws Exception { SubscriptionMetadata sub1 = new SubscriptionMetadata(); sub1.setId("123"); sub1.setState(SubscriptionState.APPROVED); diff --git a/src/test/java/com/hermesworld/ais/galapagos/topics/controller/TopicControllerTest.java b/src/test/java/com/hermesworld/ais/galapagos/topics/controller/TopicControllerTest.java index 5bda2328..c73dd0b1 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/topics/controller/TopicControllerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/topics/controller/TopicControllerTest.java @@ -14,9 +14,9 @@ import com.hermesworld.ais.galapagos.topics.service.ValidatingTopicService; import com.hermesworld.ais.galapagos.util.FutureUtil; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; @@ -26,11 +26,12 @@ import java.util.Map; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.*; -public class TopicControllerTest { +class TopicControllerTest { @MockBean private KafkaClusters kafkaClusters; @@ -51,8 +52,8 @@ public class TopicControllerTest { private TopicBasedRepositoryMock topicRepository; - @Before - public void feedMocks() { + @BeforeEach + void feedMocks() { kafkaClusters = mock(KafkaClusters.class); applicationsService = mock(ApplicationsService.class); namingService = mock(NamingService.class); @@ -71,7 +72,7 @@ public void feedMocks() { @Test @DisplayName("it should not change the deprecation if topic description is changed") - public void testDontResetDeprecationWhenTopicDescChanges() { + void testDontResetDeprecationWhenTopicDescChanges() { TopicMetadata topic = new TopicMetadata(); topic.setOwnerApplicationId("app-1"); topic.setName("topic-1"); @@ -91,12 +92,12 @@ public void testDontResetDeprecationWhenTopicDescChanges() { controller.updateTopic("test", "topic-1", dto); verify(topicService, times(1)).updateTopicDescription("test", "topic-1", "updated description goes here"); - verify(topicService, times(0)).unmarkTopicDeprecated(anyString()); + verify(topicService, times(0)).unmarkTopicDeprecated(nullable(String.class)); } @Test @DisplayName("it should change the owner if current user is authorized") - public void testChangeTopicOwner_positive() throws Exception { + void testChangeTopicOwner_positive() throws Exception { TopicMetadata topic = new TopicMetadata(); topic.setName("topic-1"); topic.setOwnerApplicationId("app-1"); @@ -119,7 +120,7 @@ public void testChangeTopicOwner_positive() throws Exception { @Test @DisplayName("it should not change the owner if current user is not authorized") - public void testChangeTopicOwner_negative() { + void testChangeTopicOwner_negative() { TopicMetadata topic = new TopicMetadata(); topic.setName("topic-1"); topic.setOwnerApplicationId("app-1"); @@ -139,13 +140,13 @@ public void testChangeTopicOwner_negative() { fail("should fail because current user is not authorized"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); + assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); } } @Test @DisplayName("Can add producers for which I am not authorized") - public void testAddTopicProducer_notAuthorizedForProducer_positive() { + void testAddTopicProducer_notAuthorizedForProducer_positive() { ValidatingTopicService topicService = mock(ValidatingTopicService.class); TopicController controller = new TopicController(topicService, kafkaClusters, applicationsService, @@ -172,7 +173,7 @@ public void testAddTopicProducer_notAuthorizedForProducer_positive() { @Test @DisplayName("Cannot add producer if not authorized for topic (but for producer)") - public void testAddTopicProducer_notAuthorizedForTopic_negative() { + void testAddTopicProducer_notAuthorizedForTopic_negative() { ValidatingTopicService topicService = mock(ValidatingTopicService.class); TopicController controller = new TopicController(topicService, kafkaClusters, applicationsService, @@ -198,13 +199,13 @@ public void testAddTopicProducer_notAuthorizedForTopic_negative() { fail("ResponseStatusException expected, but adding producer succeeded"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); + assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); } } @Test @DisplayName("Can remove producers for which I am not authorized") - public void testRemoveTopicProducer_notAuthorizedForProducer_positive() { + void testRemoveTopicProducer_notAuthorizedForProducer_positive() { ValidatingTopicService topicService = mock(ValidatingTopicService.class); TopicController controller = new TopicController(topicService, kafkaClusters, applicationsService, @@ -229,7 +230,7 @@ public void testRemoveTopicProducer_notAuthorizedForProducer_positive() { @Test @DisplayName("user cant skip compability check if not admin") - public void testSkipCombatCheckForSchemas_userNotAuthorized() { + void testSkipCombatCheckForSchemas_userNotAuthorized() { ValidatingTopicService topicService = mock(ValidatingTopicService.class); TopicController controller = new TopicController(topicService, kafkaClusters, applicationsService, @@ -250,13 +251,13 @@ public void testSkipCombatCheckForSchemas_userNotAuthorized() { fail("HttpStatus.FORBIDDEN expected, but skipping check succeeded"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); + assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); } } @Test @DisplayName("Cannot remove producer if not authorized for topic (but for producer)") - public void testRemoveTopicProducer_notAuthorizedForTopic_negative() { + void testRemoveTopicProducer_notAuthorizedForTopic_negative() { ValidatingTopicService topicService = mock(ValidatingTopicService.class); TopicController controller = new TopicController(topicService, kafkaClusters, applicationsService, @@ -279,7 +280,7 @@ public void testRemoveTopicProducer_notAuthorizedForTopic_negative() { fail("ResponseStatusException expected, but removing producer succeeded"); } catch (ResponseStatusException e) { - assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); + assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode()); } } diff --git a/src/test/java/com/hermesworld/ais/galapagos/topics/impl/ValidatingTopicServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/topics/impl/ValidatingTopicServiceImplTest.java index cbc4208d..762abb8e 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/topics/impl/ValidatingTopicServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/topics/impl/ValidatingTopicServiceImplTest.java @@ -10,33 +10,32 @@ import com.hermesworld.ais.galapagos.topics.config.GalapagosTopicConfig; import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.topics.service.impl.ValidatingTopicServiceImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.Period; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ValidatingTopicServiceImplTest { +class ValidatingTopicServiceImplTest { private GalapagosTopicConfig topicConfig; - @Before - public void init() { + @BeforeEach + void init() { topicConfig = mock(GalapagosTopicConfig.class); when(topicConfig.getMinDeprecationTime()).thenReturn(Period.ofDays(10)); } @Test - public void testCannotDeleteSubscribedTopic() { + void testCannotDeleteSubscribedTopic() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); KafkaClusters clusters = mock(KafkaClusters.class); @@ -53,7 +52,7 @@ public void testCannotDeleteSubscribedTopic() { when(topicService.getTopic("_env1", "testtopic")).thenReturn(Optional.of(meta1)); when(subscriptionService.getSubscriptionsForTopic("_env1", "testtopic", false)) - .thenReturn(Collections.singletonList(subscription)); + .thenReturn(List.of(subscription)); ValidatingTopicServiceImpl service = new ValidatingTopicServiceImpl(topicService, subscriptionService, mock(ApplicationsService.class), clusters, topicConfig, false); @@ -62,7 +61,7 @@ public void testCannotDeleteSubscribedTopic() { } @Test - public void testCannotDeleteStagedPublicTopic() { + void testCannotDeleteStagedPublicTopic() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); KafkaClusters clusters = mock(KafkaClusters.class); @@ -85,7 +84,7 @@ public void testCannotDeleteStagedPublicTopic() { } @Test - public void canDeleteTopic_internal_positiv() { + void canDeleteTopic_internal_positiv() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -110,7 +109,7 @@ public void canDeleteTopic_internal_positiv() { } @Test - public void canDeleteTopic_internal_negative() { + void canDeleteTopic_internal_negative() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -136,7 +135,7 @@ public void canDeleteTopic_internal_negative() { @Test @DisplayName("Should throw Exception when trying to add Producer to Topic on staging-only Stage") - public void addTopicProducerOnOnlyStagingEnv_negative() { + void addTopicProducerOnOnlyStagingEnv_negative() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -167,7 +166,7 @@ public void addTopicProducerOnOnlyStagingEnv_negative() { @Test @DisplayName("Should throw Exception when trying to delete Producer from Topic on staging-only Stage") - public void deleteProducerFromTopicOnOnlyStagingEnv_negative() { + void deleteProducerFromTopicOnOnlyStagingEnv_negative() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -200,7 +199,7 @@ public void deleteProducerFromTopicOnOnlyStagingEnv_negative() { } @Test - public void canDeleteTopic_withSubscribersAndEolDatePast() { + void canDeleteTopic_withSubscribersAndEolDatePast() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -220,7 +219,7 @@ public void canDeleteTopic_withSubscribersAndEolDatePast() { subscription.setClientApplicationId("2"); when(subscriptionService.getSubscriptionsForTopic("_env1", "testtopic", false)) - .thenReturn(Collections.singletonList(subscription)); + .thenReturn(List.of(subscription)); when(topicService.getTopic("_env1", "testtopic")).thenReturn(Optional.of(meta1)); ValidatingTopicServiceImpl service = new ValidatingTopicServiceImpl(topicService, subscriptionService, @@ -230,7 +229,7 @@ public void canDeleteTopic_withSubscribersAndEolDatePast() { } @Test - public void canDeleteTopic_withSubscribersAndEolDateInFuture() { + void canDeleteTopic_withSubscribersAndEolDateInFuture() { TopicService topicService = mock(TopicService.class); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -250,7 +249,7 @@ public void canDeleteTopic_withSubscribersAndEolDateInFuture() { subscription.setClientApplicationId("2"); when(subscriptionService.getSubscriptionsForTopic("_env1", "testtopic", false)) - .thenReturn(Collections.singletonList(subscription)); + .thenReturn(List.of(subscription)); when(topicService.getTopic("_env1", "testtopic")).thenReturn(Optional.of(meta1)); ValidatingTopicServiceImpl service = new ValidatingTopicServiceImpl(topicService, subscriptionService, diff --git a/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplIntegrationTest.java b/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplIntegrationTest.java index 8fb632bd..c3f293b9 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplIntegrationTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplIntegrationTest.java @@ -14,10 +14,9 @@ import com.hermesworld.ais.galapagos.topics.config.GalapagosTopicConfig; import com.hermesworld.ais.galapagos.util.FutureUtil; import com.hermesworld.ais.galapagos.util.HasKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -26,7 +25,6 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDate; import java.util.ArrayList; @@ -38,7 +36,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,10 +45,9 @@ * Tests that Security Context data is passed correctly to event context, even when performing the quite complex, * chained markTopicDeprecated and unmarkTopicDeprecated operations. */ -@RunWith(SpringRunner.class) @SpringBootTest @Import(TopicServiceImplIntegrationTest.TestEventListener.class) -public class TopicServiceImplIntegrationTest { +class TopicServiceImplIntegrationTest { @Autowired private CurrentUserService currentUserService; @@ -78,8 +75,8 @@ public class TopicServiceImplIntegrationTest { private final TopicBasedRepositoryMock topicRepository2 = new DecoupledTopicBasedRepositoryMock<>( executorService); - @Before - public void feedMocks() { + @BeforeEach + void feedMocks() { KafkaCluster cluster1 = mock(KafkaCluster.class); KafkaCluster cluster2 = mock(KafkaCluster.class); @@ -103,14 +100,14 @@ public void feedMocks() { when(notificationService.notifySubscribers(any(), any(), any(), any())).thenReturn(FutureUtil.noop()); } - @After - public void shutdown() throws Exception { + @AfterEach + void shutdown() throws Exception { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } @Test - public void testTopicDeprecated_passesCurrentUser() throws Exception { + void testTopicDeprecated_passesCurrentUser() throws Exception { ApplicationsService applicationsService = mock(ApplicationsService.class); NamingService namingService = mock(NamingService.class); GalapagosTopicConfig topicSettings = mock(GalapagosTopicConfig.class); @@ -145,7 +142,7 @@ public void testTopicDeprecated_passesCurrentUser() throws Exception { } @Test - public void testTopicUndeprecated_passesCurrentUser() throws Exception { + void testTopicUndeprecated_passesCurrentUser() throws Exception { ApplicationsService applicationsService = mock(ApplicationsService.class); NamingService namingService = mock(NamingService.class); GalapagosTopicConfig topicSettings = mock(GalapagosTopicConfig.class); diff --git a/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplTest.java b/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplTest.java index e7c18508..67fa6b6e 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/topics/service/impl/TopicServiceImplTest.java @@ -20,9 +20,9 @@ import com.hermesworld.ais.galapagos.topics.config.GalapagosTopicConfig; import com.hermesworld.ais.galapagos.util.FutureUtil; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.ClassPathResource; @@ -34,11 +34,11 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -public class TopicServiceImplTest { +class TopicServiceImplTest { @MockBean private KafkaClusters kafkaClusters; @@ -59,8 +59,8 @@ public class TopicServiceImplTest { private TopicBasedRepositoryMock schemaRepository; - @Before - public void feedMocks() { + @BeforeEach + void feedMocks() { kafkaClusters = mock(KafkaClusters.class); applicationsService = mock(ApplicationsService.class); namingService = mock(NamingService.class); @@ -95,7 +95,7 @@ public void feedMocks() { } @Test - public void testCreateTopic_positive() throws Exception { + void testCreateTopic_positive() throws Exception { List createInvs = new ArrayList<>(); when(kafkaTestCluster.createTopic(any(), any())).then(inv -> { @@ -135,7 +135,7 @@ public void testCreateTopic_positive() throws Exception { } @Test - public void testCreateTopic_downToMaxPartitions() throws Exception { + void testCreateTopic_downToMaxPartitions() throws Exception { List createInvs = new ArrayList<>(); when(kafkaTestCluster.createTopic(any(), any())).then(inv -> { @@ -163,7 +163,7 @@ public void testCreateTopic_downToMaxPartitions() throws Exception { } @Test - public void testCreateTopic_criticalReplicationFactor() throws Exception { + void testCreateTopic_criticalReplicationFactor() throws Exception { List createInvs = new ArrayList<>(); when(kafkaTestCluster.createTopic(any(), any())).then(inv -> { @@ -192,7 +192,7 @@ public void testCreateTopic_criticalReplicationFactor() throws Exception { } @Test - public void testCreateTopic_replicationFactor_downToNumBrokers() throws Exception { + void testCreateTopic_replicationFactor_downToNumBrokers() throws Exception { List createInvs = new ArrayList<>(); // 6 is more than the 5 brokers we have, so should be downed to 5 @@ -224,7 +224,7 @@ public void testCreateTopic_replicationFactor_downToNumBrokers() throws Exceptio } @Test - public void testCreateTopic_useDefaultPartitions() throws Exception { + void testCreateTopic_useDefaultPartitions() throws Exception { List createInvs = new ArrayList<>(); when(kafkaTestCluster.createTopic(any(), any())).then(inv -> { @@ -252,7 +252,7 @@ public void testCreateTopic_useDefaultPartitions() throws Exception { } @Test - public void testCreateTopic_nameValidationFails() throws Exception { + void testCreateTopic_nameValidationFails() throws Exception { List createInvs = new ArrayList<>(); when(kafkaTestCluster.createTopic(any(), any())).then(inv -> { @@ -284,7 +284,7 @@ public void testCreateTopic_nameValidationFails() throws Exception { @Test @DisplayName("should add producer to topic") - public void addTopicProducerTest_positive() throws Exception { + void addTopicProducerTest_positive() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -305,7 +305,7 @@ public void addTopicProducerTest_positive() throws Exception { @Test @DisplayName("should fail adding a producer to commands topic") - public void addTopicProducerTest_negative() throws Exception { + void addTopicProducerTest_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -327,7 +327,7 @@ public void addTopicProducerTest_negative() throws Exception { @Test @DisplayName("should delete producer from topic") - public void deleteTopicProducersTest_positive() throws Exception { + void deleteTopicProducersTest_positive() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -349,7 +349,7 @@ public void deleteTopicProducersTest_positive() throws Exception { @Test @DisplayName("should not be able to delete producer from commands topic") - public void deleteTopicProducersTest_negative() throws Exception { + void deleteTopicProducersTest_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -375,7 +375,7 @@ public void deleteTopicProducersTest_negative() throws Exception { @Test @DisplayName("should promote a producer to new Topic owner") - public void changeOwnerOfTopicTest_positive() throws Exception { + void changeOwnerOfTopicTest_positive() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -398,7 +398,7 @@ public void changeOwnerOfTopicTest_positive() throws Exception { @Test @DisplayName("should not promote a producer to new Topic owner for internal topics") - public void changeOwnerOfTopicTest_negative() throws Exception { + void changeOwnerOfTopicTest_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -421,7 +421,7 @@ public void changeOwnerOfTopicTest_negative() throws Exception { } @Test - public void testDeleteLatestSchemaVersion() throws Exception { + void testDeleteLatestSchemaVersion() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -454,7 +454,7 @@ public void testDeleteLatestSchemaVersion() throws Exception { } @Test - public void testDeleteLatestSchemaVersionStaged_negative() throws Exception { + void testDeleteLatestSchemaVersionStaged_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); KafkaCluster prodCluster = mock(KafkaCluster.class); @@ -496,7 +496,7 @@ public void testDeleteLatestSchemaVersionStaged_negative() throws Exception { } @Test - public void testDeleteLatestSchemaVersionWithSubscriber_negative() throws Exception { + void testDeleteLatestSchemaVersionWithSubscriber_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -520,8 +520,7 @@ public void testDeleteLatestSchemaVersionWithSubscriber_negative() throws Except subscription.setClientApplicationId("2"); SubscriptionService subscriptionService = mock(SubscriptionService.class); - when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)) - .thenReturn(Collections.singletonList(subscription)); + when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)).thenReturn(List.of(subscription)); ValidatingTopicServiceImpl validatingService = new ValidatingTopicServiceImpl(service, subscriptionService, applicationsService, kafkaClusters, topicConfig, false); @@ -540,7 +539,7 @@ public void testDeleteLatestSchemaVersionWithSubscriber_negative() throws Except } @Test - public void testAddSchemaVersion_sameSchema() throws Exception { + void testAddSchemaVersion_sameSchema() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -572,7 +571,7 @@ public void testAddSchemaVersion_sameSchema() throws Exception { } @Test - public void testAddSchemaVersion_incompatibleSchema() throws Exception { + void testAddSchemaVersion_incompatibleSchema() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -605,7 +604,7 @@ public void testAddSchemaVersion_incompatibleSchema() throws Exception { @Test @DisplayName("should not to check for compatibility if skipCompatCheck is set to true") - public void testAddSchemaVersion_skipCompatibleSchemaCheckForAdmins() throws Exception { + void testAddSchemaVersion_skipCompatibleSchemaCheckForAdmins() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -627,7 +626,7 @@ public void testAddSchemaVersion_skipCompatibleSchemaCheckForAdmins() throws Exc } @Test - public void testAddSchemaVersion_withMetadata() throws Exception { + void testAddSchemaVersion_withMetadata() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -664,7 +663,7 @@ public void testAddSchemaVersion_withMetadata() throws Exception { } @Test - public void testAddSchemaVersion_withMetadata_illegalVersionNo_empty() throws Exception { + void testAddSchemaVersion_withMetadata_illegalVersionNo_empty() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -692,7 +691,7 @@ public void testAddSchemaVersion_withMetadata_illegalVersionNo_empty() throws Ex } @Test - public void testAddSchemaVersion_withMetadata_illegalVersionNo_notMatching() throws Exception { + void testAddSchemaVersion_withMetadata_illegalVersionNo_notMatching() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -729,7 +728,7 @@ public void testAddSchemaVersion_withMetadata_illegalVersionNo_notMatching() thr } @Test - public void testAddSchemaVersion_invalidSchema() throws Exception { + void testAddSchemaVersion_invalidSchema() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -751,7 +750,7 @@ public void testAddSchemaVersion_invalidSchema() throws Exception { } @Test - public void testAddSchemaVersion_invalidJson() throws Exception { + void testAddSchemaVersion_invalidJson() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -772,7 +771,7 @@ public void testAddSchemaVersion_invalidJson() throws Exception { } @Test - public void testAddSchemaVersion_DataObjectSimpleAtJSONSchema() throws Exception { + void testAddSchemaVersion_DataObjectSimpleAtJSONSchema() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -798,7 +797,7 @@ public void testAddSchemaVersion_DataObjectSimpleAtJSONSchema() throws Exception } @Test - public void testAddSchemaVersion_DataObjectNestedAtJSONSchema() throws Exception { + void testAddSchemaVersion_DataObjectNestedAtJSONSchema() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -818,7 +817,7 @@ public void testAddSchemaVersion_DataObjectNestedAtJSONSchema() throws Exception } @Test - public void testAddSchemaVersion_NoSchemaProp() throws Exception { + void testAddSchemaVersion_NoSchemaProp() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -844,7 +843,7 @@ public void testAddSchemaVersion_NoSchemaProp() throws Exception { } @Test - public void testSetSubscriptionApprovalRequired_positive() throws Exception { + void testSetSubscriptionApprovalRequired_positive() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -875,7 +874,7 @@ public void testSetSubscriptionApprovalRequired_positive() throws Exception { } @Test - public void testSetSubscriptionApprovalRequired_internalTopic() throws Exception { + void testSetSubscriptionApprovalRequired_internalTopic() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -898,7 +897,7 @@ public void testSetSubscriptionApprovalRequired_internalTopic() throws Exception } @Test - public void testSetSubscriptionApprovalRequired_noop() throws Exception { + void testSetSubscriptionApprovalRequired_noop() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -916,7 +915,7 @@ public void testSetSubscriptionApprovalRequired_noop() throws Exception { @Test @DisplayName("should stage new owner on all stages immediately") - public void testChangeOwnerStaging() throws Exception { + void testChangeOwnerStaging() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); KafkaCluster testCluster2 = mock(KafkaCluster.class); @@ -949,7 +948,7 @@ public void testChangeOwnerStaging() throws Exception { } @Test - public void testDeprecateTopic_positive() throws Exception { + void testDeprecateTopic_positive() throws Exception { KafkaCluster testCluster2 = mock(KafkaCluster.class); when(testCluster2.getId()).thenReturn("test2"); KafkaCluster testCluster3 = mock(KafkaCluster.class); @@ -985,7 +984,7 @@ public void testDeprecateTopic_positive() throws Exception { } @Test - public void testDeprecateTopic_noSuchTopic() throws Exception { + void testDeprecateTopic_noSuchTopic() throws Exception { KafkaCluster testCluster2 = mock(KafkaCluster.class); when(testCluster2.getId()).thenReturn("test2"); KafkaCluster testCluster3 = mock(KafkaCluster.class); @@ -1024,7 +1023,7 @@ public void testDeprecateTopic_noSuchTopic() throws Exception { } @Test - public void testunmarkTopicDeprecated() throws Exception { + void testunmarkTopicDeprecated() throws Exception { KafkaCluster testCluster2 = mock(KafkaCluster.class); when(testCluster2.getId()).thenReturn("test2"); KafkaCluster testCluster3 = mock(KafkaCluster.class); @@ -1055,7 +1054,7 @@ public void testunmarkTopicDeprecated() throws Exception { } @Test - public void testChangeDescOfTopic() throws Exception { + void testChangeDescOfTopic() throws Exception { TopicMetadata topic = new TopicMetadata(); topic.setName("topic-1"); @@ -1075,7 +1074,7 @@ public void testChangeDescOfTopic() throws Exception { } @Test - public void testAddSchemaVersion_DataObjectNestedAtJSONSchemaAndDataTopic() throws Exception { + void testAddSchemaVersion_DataObjectNestedAtJSONSchemaAndDataTopic() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -1095,7 +1094,7 @@ public void testAddSchemaVersion_DataObjectNestedAtJSONSchemaAndDataTopic() thro } @Test - public void testAddSchemaVersion_WithChangeDesc() throws Exception { + void testAddSchemaVersion_WithChangeDesc() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -1131,7 +1130,7 @@ public void testAddSchemaVersion_WithChangeDesc() throws Exception { } @Test - public void testAddSchemaVersion_WithChangeDesc_negative() throws Exception { + void testAddSchemaVersion_WithChangeDesc_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -1160,7 +1159,7 @@ public void testAddSchemaVersion_WithChangeDesc_negative() throws Exception { } @Test - public void testDeleteSchemaWithSub_positive() throws Exception { + void testDeleteSchemaWithSub_positive() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -1185,8 +1184,7 @@ public void testDeleteSchemaWithSub_positive() throws Exception { subscription.setClientApplicationId("2"); SubscriptionService subscriptionService = mock(SubscriptionService.class); - when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)) - .thenReturn(Collections.singletonList(subscription)); + when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)).thenReturn(List.of(subscription)); ValidatingTopicServiceImpl validatingService = new ValidatingTopicServiceImpl(service, subscriptionService, applicationsService, kafkaClusters, topicConfig, true); @@ -1197,7 +1195,7 @@ public void testDeleteSchemaWithSub_positive() throws Exception { } @Test - public void testDeleteSchemaWithSub_negative() throws Exception { + void testDeleteSchemaWithSub_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); @@ -1222,8 +1220,7 @@ public void testDeleteSchemaWithSub_negative() throws Exception { subscription.setClientApplicationId("2"); SubscriptionService subscriptionService = mock(SubscriptionService.class); - when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)) - .thenReturn(Collections.singletonList(subscription)); + when(subscriptionService.getSubscriptionsForTopic("test", "topic-1", false)).thenReturn(List.of(subscription)); ValidatingTopicServiceImpl validatingService = new ValidatingTopicServiceImpl(service, subscriptionService, applicationsService, kafkaClusters, topicConfig, false); @@ -1240,7 +1237,7 @@ public void testDeleteSchemaWithSub_negative() throws Exception { } @Test - public void testDeleteLatestSchemaVersionStagedSchemaDeleteSub_negative() throws Exception { + void testDeleteLatestSchemaVersionStagedSchemaDeleteSub_negative() throws Exception { TopicServiceImpl service = new TopicServiceImpl(kafkaClusters, applicationsService, namingService, userService, topicConfig, eventManager); SubscriptionService subscriptionService = mock(SubscriptionService.class); @@ -1271,8 +1268,7 @@ public void testDeleteLatestSchemaVersionStagedSchemaDeleteSub_negative() throws subscription.setTopicName("topic-1"); subscription.setClientApplicationId("2"); - when(subscriptionService.getSubscriptionsForTopic("prod", "topic-1", false)) - .thenReturn(Collections.singletonList(subscription)); + when(subscriptionService.getSubscriptionsForTopic("prod", "topic-1", false)).thenReturn(List.of(subscription)); prodTopicRepository.save(topic1).get(); diff --git a/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/CustomLinksConfigTest.java b/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/CustomLinksConfigTest.java index e0a85a64..7a7b83c1 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/CustomLinksConfigTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/CustomLinksConfigTest.java @@ -1,45 +1,54 @@ package com.hermesworld.ais.galapagos.uisupport.controller; -import java.util.Collections; - -import org.junit.Test; - import com.hermesworld.ais.galapagos.uisupport.controller.CustomLinkConfig; + +import static org.junit.jupiter.api.Assertions.assertThrows; import com.hermesworld.ais.galapagos.uisupport.controller.CustomLinksConfig; import com.hermesworld.ais.galapagos.uisupport.controller.LinkType; +import org.junit.jupiter.api.Test; -public class CustomLinksConfigTest { +import java.util.List; - @Test(expected = RuntimeException.class) - public void testCustomLinksConfigID() { - CustomLinkConfig customLinkConfig = generatedCustomLinkConfig(null, "www.test.de", "Test-Label", - LinkType.OTHER); - new CustomLinksConfig().setLinks(Collections.singletonList(customLinkConfig)); +class CustomLinksConfigTest { + + @Test + void testCustomLinksConfigID() { + assertThrows(RuntimeException.class, () -> { + CustomLinkConfig customLinkConfig = generatedCustomLinkConfig(null, "www.test.de", "Test-Label", + LinkType.OTHER); + new CustomLinksConfig().setLinks(List.of(customLinkConfig)); + }); } - @Test(expected = RuntimeException.class) - public void testCustomLinksConfigH_Ref() { - CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", null, "Test-Label", LinkType.OTHER); - new CustomLinksConfig().setLinks(Collections.singletonList(customLinkConfig)); + @Test + void testCustomLinksConfigH_Ref() { + assertThrows(RuntimeException.class, () -> { + CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", null, "Test-Label", LinkType.OTHER); + new CustomLinksConfig().setLinks(List.of(customLinkConfig)); + }); } - @Test(expected = RuntimeException.class) - public void testCustomLinksConfigLabel() { - CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", "www.test.de", null, LinkType.OTHER); - new CustomLinksConfig().setLinks(Collections.singletonList(customLinkConfig)); + @Test + void testCustomLinksConfigLabel() { + assertThrows(RuntimeException.class, () -> { + CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", "www.test.de", null, LinkType.OTHER); + new CustomLinksConfig().setLinks(List.of(customLinkConfig)); + }); } - @Test(expected = RuntimeException.class) - public void testCustomLinksConfigLinkType() { - CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", "www.test.de", "Test-Label", null); - new CustomLinksConfig().setLinks(Collections.singletonList(customLinkConfig)); + @Test + void testCustomLinksConfigLinkType() { + assertThrows(RuntimeException.class, () -> { + CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", "www.test.de", "Test-Label", null); + new CustomLinksConfig().setLinks(List.of(customLinkConfig)); + }); } @Test - public void testCustomLinkConfigPositive() { + void testCustomLinkConfigPositive() { CustomLinkConfig customLinkConfig = generatedCustomLinkConfig("42", "www.test.de", "Test-Label", LinkType.OTHER); - new CustomLinksConfig().setLinks(Collections.singletonList(customLinkConfig)); + new CustomLinksConfig().setLinks(List.of(customLinkConfig)); } private CustomLinkConfig generatedCustomLinkConfig(String id, String href, String label, LinkType linkType) { diff --git a/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportControllerTest.java b/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportControllerTest.java index 3ca05d53..91955786 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportControllerTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/uisupport/controller/UISupportControllerTest.java @@ -1,20 +1,17 @@ package com.hermesworld.ais.galapagos.uisupport.controller; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -@RunWith(SpringRunner.class) @SpringBootTest -public class UISupportControllerTest { +class UISupportControllerTest { @MockBean private KafkaClusters kafkaClusters; @@ -23,7 +20,7 @@ public class UISupportControllerTest { private UISupportController testController; @Test - public void testCustomLinks() { + void testCustomLinks() { List links = testController.getCustomLinks(); assertNotNull(links); @@ -42,7 +39,7 @@ public void testCustomLinks() { } @Test - public void testKafkaDoc() { + void testKafkaDoc() { List result = new UISupportController(null, null, null, null, null, null, null) .getSupportedKafkaConfigs(); assertNotNull(result); diff --git a/src/test/java/com/hermesworld/ais/galapagos/util/CnUtilTest.java b/src/test/java/com/hermesworld/ais/galapagos/util/CnUtilTest.java index ab98abda..385faab5 100644 --- a/src/test/java/com/hermesworld/ais/galapagos/util/CnUtilTest.java +++ b/src/test/java/com/hermesworld/ais/galapagos/util/CnUtilTest.java @@ -1,13 +1,13 @@ package com.hermesworld.ais.galapagos.util; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CnUtilTest { +class CnUtilTest { @Test - public void testToAppCn() { + void testToAppCn() { assertEquals("alpha", CertificateUtil.toAppCn("ALPHA")); assertEquals("track_trace", CertificateUtil.toAppCn("Track & Trace")); assertEquals("elisa", CertificateUtil.toAppCn(" Elisa "));