From 5dc9e85c2dcc49d73f5ff95886e358ed7134cf00 Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr Date: Fri, 4 Aug 2023 06:02:16 +0200 Subject: [PATCH 01/26] BAEL-6415: Add simple Kafka client example (with BootStrap Servers setting) --- apache-kafka-3/pom.xml | 27 +++++++++++++ .../java/com/baeldung/kafka/KafkaJava.java | 39 +++++++++++++++++++ pom.xml | 2 + 3 files changed, 68 insertions(+) create mode 100644 apache-kafka-3/pom.xml create mode 100644 apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java diff --git a/apache-kafka-3/pom.xml b/apache-kafka-3/pom.xml new file mode 100644 index 0000000000..6c4b5284dd --- /dev/null +++ b/apache-kafka-3/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + apache-kafka-3 + apache-kafka-3 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.kafka + kafka-clients + ${kafka.version} + + + + + 3.5.1 + + + \ No newline at end of file diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java new file mode 100644 index 0000000000..bc2eeadb78 --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java @@ -0,0 +1,39 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.consumer.*; +import org.apache.kafka.common.serialization.LongDeserializer; +import org.apache.kafka.common.serialization.StringDeserializer; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Properties; + +public class KafkaJava { + + public static void main(String[] args) { + try(final Consumer consumer = createConsumer()) { + ConsumerRecords records = consumer.poll(Duration.ofMinutes(1)); + for(ConsumerRecord record : records) { + System.out.println(record.value()); + } + } + } + + private static Consumer createConsumer() { + final Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + "localhost:9092,another-host.com:29092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, + "MySampleConsumer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, + LongDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, + StringDeserializer.class.getName()); + // Create the consumer using props. + final Consumer consumer = new KafkaConsumer(props); + // Subscribe to the topic. + consumer.subscribe(Arrays.asList("samples")); + return consumer; + } + +} diff --git a/pom.xml b/pom.xml index 8fb2234a23..e11395c709 100644 --- a/pom.xml +++ b/pom.xml @@ -820,6 +820,7 @@ antlr apache-kafka apache-kafka-2 + apache-kafka-3 apache-olingo apache-poi-2 @@ -1089,6 +1090,7 @@ antlr apache-kafka apache-kafka-2 + apache-kafka-3 apache-olingo apache-poi-2 From 416c85ccabad1e5c28fe9d717b3792de7983151a Mon Sep 17 00:00:00 2001 From: Thibault Faure Date: Sat, 5 Aug 2023 20:24:56 +0200 Subject: [PATCH 02/26] BAEL-6613 Code for the Speed Up Maven Build article --- .../.mvn/jvm.config.txt | 1 + .../profiler-report-2023-08-05-19-34-46.html | 2542 +++++++++++++++++ .../maven-build-optimization/pom.xml | 62 + maven-modules/pom.xml | 1 + 4 files changed, 2606 insertions(+) create mode 100644 maven-modules/maven-build-optimization/.mvn/jvm.config.txt create mode 100644 maven-modules/maven-build-optimization/.profiler/profiler-report-2023-08-05-19-34-46.html create mode 100644 maven-modules/maven-build-optimization/pom.xml diff --git a/maven-modules/maven-build-optimization/.mvn/jvm.config.txt b/maven-modules/maven-build-optimization/.mvn/jvm.config.txt new file mode 100644 index 0000000000..37dd0076c2 --- /dev/null +++ b/maven-modules/maven-build-optimization/.mvn/jvm.config.txt @@ -0,0 +1 @@ +-XX:-TieredCompilation -XX:TieredStopAtLevel=1 \ No newline at end of file diff --git a/maven-modules/maven-build-optimization/.profiler/profiler-report-2023-08-05-19-34-46.html b/maven-modules/maven-build-optimization/.profiler/profiler-report-2023-08-05-19-34-46.html new file mode 100644 index 0000000000..807679bbf6 --- /dev/null +++ b/maven-modules/maven-build-optimization/.profiler/profiler-report-2023-08-05-19-34-46.html @@ -0,0 +1,2542 @@ + + + + + Maven Profiler Report + + + +
+

maven-build-optimization (21,91 s)

+

Run clean install on 2023/08/05 19:34:46 with parameters: {}

+ + +
+

maven-build-optimization (18,81 s)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Plugin executionDuration
org.apache.maven.plugins:maven-pmd-plugin:3.19.0:pmd {execution: pmd}10,45 s
org.commonjava.maven.plugins:directory-maven-plugin:0.3.1:directory-of {execution: directories}2,108 s
org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file {execution: install-jar-lib}1,982 s
org.apache.maven.plugins:maven-clean-plugin:3.2.0:clean {execution: default-clean}541,7 ms
org.apache.maven.plugins:maven-install-plugin:2.5.2:install {execution: default-install}22,76 ms
org.apache.maven.plugins:maven-pmd-plugin:3.19.0:check {execution: default}9,651 ms
+
+ + + +
+

Artifact Downloading (168,3 s)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArtifactDuration
org.codehaus.plexus:plexus-utils:jar:3.3.01,649 s
javax.inject:javax.inject:jar:11,646 s
org.codehaus.plexus:plexus-resources:jar:1.2.01,643 s
org.apache.maven.doxia:doxia-integration-tools:jar:1.11.11,640 s
org.eclipse.sisu:org.eclipse.sisu.inject:jar:0.3.51,636 s
javax.enterprise:cdi-api:jar:1.21,634 s
javax.annotation:javax.annotation-api:jar:1.21,632 s
org.eclipse.sisu:org.eclipse.sisu.plexus:jar:0.3.51,630 s
org.apache.maven:maven-plugin-api:jar:3.1.01,627 s
org.apache.maven.reporting:maven-reporting-impl:jar:3.2.01,623 s
org.apache.maven.reporting:maven-reporting-api:jar:3.1.11,620 s
commons-collections:commons-collections:jar:3.2.21,618 s
oro:oro:jar:2.0.81,616 s
dom4j:dom4j:jar:1.11,613 s
commons-logging:commons-logging:jar:1.11,611 s
commons-chain:commons-chain:jar:1.11,607 s
commons-digester:commons-digester:jar:1.81,604 s
commons-beanutils:commons-beanutils:jar:1.7.01,602 s
org.apache.velocity:velocity-tools:jar:2.01,600 s
commons-lang:commons-lang:jar:2.41,597 s
org.apache.velocity:velocity:jar:1.71,595 s
org.codehaus.plexus:plexus-velocity:jar:1.21,592 s
org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-301,589 s
org.codehaus.plexus:plexus-i18n:jar:1.0-beta-101,586 s
org.apache.maven.doxia:doxia-module-xhtml5:jar:1.11.11,583 s
org.apache.maven.doxia:doxia-module-xhtml:jar:1.11.11,578 s
org.apache.maven.doxia:doxia-skin-model:jar:1.11.11,572 s
org.apache.httpcomponents:httpcore:jar:4.4.141,569 s
org.apache.commons:commons-text:jar:1.31,566 s
org.apache.maven.doxia:doxia-core:jar:1.11.11,563 s
org.apache.maven.doxia:doxia-site-renderer:jar:1.11.11,560 s
org.apache.maven.doxia:doxia-decoration-model:jar:1.11.11,556 s
org.apache.maven.doxia:doxia-logging-api:jar:1.11.11,553 s
org.apache.maven.doxia:doxia-sink-api:jar:1.11.11,551 s
org.slf4j:jul-to-slf4j:jar:1.7.361,549 s
org.slf4j:slf4j-api:jar:1.7.361,546 s
net.sourceforge.pmd:pmd-jsp:jar:6.49.01,543 s
org.mozilla:rhino:jar:1.7.141,540 s
net.sourceforge.pmd:pmd-javascript:jar:6.49.01,537 s
net.sourceforge.pmd:pmd-java:jar:6.49.01,535 s
net.sourceforge.saxon:saxon:jar:dom:9.1.0.81,533 s
com.google.code.gson:gson:jar:2.8.91,530 s
org.ow2.asm:asm:jar:9.31,528 s
net.sourceforge.saxon:saxon:jar:9.1.0.81,524 s
com.beust:jcommander:jar:1.481,521 s
org.antlr:antlr4-runtime:jar:4.7.21,519 s
net.sourceforge.pmd:pmd-core:jar:6.49.01,516 s
org.apache.commons:commons-lang3:jar:3.12.01,513 s
commons-io:commons-io:jar:2.11.01,511 s
org.apache.maven.shared:maven-common-artifact-filters:jar:3.3.11,508 s
org.codehaus.plexus:plexus-component-annotations:jar:2.1.11,504 s
org.apache.maven:maven-artifact:jar:3.01,501 s
org.codehaus.plexus:plexus-classworlds:jar:2.2.31,498 s
org.sonatype.sisu:sisu-guice:jar:noaop:2.1.71,495 s
org.sonatype.sisu:sisu-inject-bean:jar:1.4.21,481 s
org.sonatype.sisu:sisu-inject-plexus:jar:1.4.21,472 s
org.sonatype.aether:aether-util:jar:1.71,468 s
org.sonatype.aether:aether-api:jar:1.71,465 s
org.sonatype.aether:aether-spi:jar:1.71,462 s
org.sonatype.aether:aether-impl:jar:1.71,459 s
org.apache.maven:maven-aether-provider:jar:3.01,455 s
org.apache.maven:maven-model-builder:jar:3.01,453 s
org.apache.maven:maven-repository-metadata:jar:3.01,450 s
org.apache.maven:maven-settings-builder:jar:3.01,447 s
org.apache.maven:maven-settings:jar:3.01,444 s
org.apache.maven:maven-model:jar:3.01,441 s
org.apache.maven:maven-core:jar:3.01,437 s
org.apache.maven.shared:maven-artifact-transfer:jar:0.13.11,434 s
org.apache.maven.surefire:surefire-logger-api:jar:2.22.21,110 s
org.objenesis:objenesis:jar:3.21,107 s
net.bytebuddy:byte-buddy-agent:jar:1.12.81,104 s
net.bytebuddy:byte-buddy:jar:1.12.81,102 s
org.mockito:mockito-core:jar:4.4.01,097 s
org.hamcrest:hamcrest-all:jar:1.31,094 s
org.hamcrest:hamcrest:jar:2.21,092 s
org.assertj:assertj-core:jar:3.21.01,090 s
org.hamcrest:hamcrest-core:jar:1.31,087 s
junit:junit:jar:4.13.21,081 s
org.junit.vintage:junit-vintage-engine:jar:5.9.21,072 s
org.junit.platform:junit-platform-commons:jar:1.9.21,053 s
org.opentest4j:opentest4j:jar:1.2.01,046 s
org.junit.jupiter:junit-jupiter-api:jar:5.9.21,043 s
org.junit.jupiter:junit-jupiter-params:jar:5.9.21,041 s
org.apiguardian:apiguardian-api:jar:1.1.21,037 s
org.junit.platform:junit-platform-engine:jar:1.9.21,034 s
org.junit.jupiter:junit-jupiter-engine:jar:5.9.21,030 s
org.slf4j:jcl-over-slf4j:jar:1.7.321,027 s
ch.qos.logback:logback-core:jar:1.2.71,025 s
ch.qos.logback:logback-classic:jar:1.2.71,021 s
org.slf4j:slf4j-api:jar:1.7.321,018 s
com.vackosar.gitflowincrementalbuilder:gitflow-incremental-builder:pom:3.12.2912,3 ms
com.jcraft:jsch.agentproxy.sshagent:jar:0.0.9714,0 ms
net.java.dev.jna:jna-platform:jar:4.1.0709,2 ms
net.java.dev.jna:jna:jar:4.1.0700,3 ms
com.jcraft:jsch.agentproxy.pageant:jar:0.0.9696,9 ms
com.jcraft:jsch.agentproxy.jsch:jar:0.0.9691,3 ms
com.jcraft:jsch.agentproxy.usocket-nc:jar:0.0.9687,5 ms
com.jcraft:jsch.agentproxy.usocket-jna:jar:0.0.9681,7 ms
com.jcraft:jsch.agentproxy.core:jar:0.0.9677,3 ms
com.jcraft:jsch.agentproxy.connector-factory:jar:0.0.9673,1 ms
com.jcraft:jzlib:jar:1.1.1669,0 ms
com.jcraft:jsch:jar:0.1.55665,4 ms
org.eclipse.jgit:org.eclipse.jgit.ssh.jsch:jar:5.10.0.202012080955-r662,5 ms
com.googlecode.javaewah:JavaEWAH:jar:1.1.7659,3 ms
org.eclipse.jgit:org.eclipse.jgit:jar:5.10.0.202012080955-r656,1 ms
com.vackosar.gitflowincrementalbuilder:gitflow-incremental-builder:jar:3.12.2653,0 ms
org.apache.maven:maven-model:jar:3.0.3435,3 ms
org.apache.maven:maven-plugin-api:jar:3.0.3430,5 ms
org.sonatype.plexus:plexus-cipher:jar:1.4427,8 ms
org.sonatype.plexus:plexus-sec-dispatcher:jar:1.3424,9 ms
org.codehaus.plexus:plexus-component-annotations:jar:1.5.5421,3 ms
org.codehaus.plexus:plexus-classworlds:jar:2.4418,1 ms
org.codehaus.plexus:plexus-utils:jar:2.0.6414,4 ms
org.codehaus.plexus:plexus-interpolation:jar:1.14411,1 ms
org.sonatype.sisu:sisu-guice:jar:no_aop:2.9.4403,0 ms
org.sonatype.sisu:sisu-inject-bean:jar:2.1.1396,1 ms
org.sonatype.sisu:sisu-inject-plexus:jar:2.1.1392,9 ms
org.sonatype.aether:aether-util:jar:1.11388,1 ms
org.sonatype.aether:aether-api:jar:1.11385,0 ms
org.sonatype.aether:aether-impl:jar:1.11381,0 ms
org.sonatype.aether:aether-spi:jar:1.11377,5 ms
org.apache.maven:maven-aether-provider:jar:3.0.3374,7 ms
org.apache.maven:maven-model-builder:jar:3.0.3371,9 ms
org.apache.maven:maven-artifact:jar:3.0.3369,1 ms
org.apache.maven:maven-repository-metadata:jar:3.0.3365,9 ms
org.apache.maven:maven-settings-builder:jar:3.0.3361,7 ms
org.apache.maven:maven-settings:jar:3.0.3358,7 ms
org.apache.maven:maven-core:jar:3.0.3355,7 ms
org.codehaus.plexus:plexus-utils:jar:3.0.15320,8 ms
com.google.code.findbugs:jsr305:jar:2.0.1312,4 ms
org.apache.maven.shared:maven-shared-utils:jar:0.4309,8 ms
commons-codec:commons-codec:jar:1.6307,2 ms
org.apache.maven:maven-artifact:jar:2.2.1304,6 ms
backport-util-concurrent:backport-util-concurrent:jar:3.1302,0 ms
org.apache.maven:maven-repository-metadata:jar:2.2.1298,3 ms
org.apache.maven:maven-artifact-manager:jar:2.2.1294,0 ms
org.apache.maven:maven-model:jar:2.2.1291,5 ms
classworlds:classworlds:jar:1.1-alpha-2288,9 ms
junit:junit:jar:3.8.1286,4 ms
org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9-stable-1282,9 ms
org.codehaus.plexus:plexus-interpolation:jar:1.11278,9 ms
org.apache.maven:maven-plugin-registry:jar:2.2.1276,5 ms
org.apache.maven:maven-profile:jar:2.2.1273,8 ms
org.apache.maven:maven-settings:jar:2.2.1271,4 ms
org.apache.maven:maven-project:jar:2.2.1268,8 ms
org.apache.maven:maven-plugin-api:jar:2.2.1265,4 ms
commons-io:commons-io:jar:2.6111,6 ms
org.apache.maven.shared:maven-shared-utils:jar:3.3.4109,0 ms
org.apache.velocity:velocity:pom:1.6.297,59 ms
commons-collections:commons-collections:pom:3.2.284,54 ms
org.apache:apache:pom:576,39 ms
org.eclipse.aether:aether-impl:pom:0.9.0.M277,00 ms
org.eclipse.sisu:org.eclipse.sisu.inject:pom:0.3.572,70 ms
org.eclipse.aether:aether-util:pom:0.9.0.M271,60 ms
org.codehaus.plexus:plexus-container-default:pom:1.0-alpha-3070,94 ms
org.codehaus.plexus:plexus-utils:pom:2.0.669,83 ms
org.mozilla:rhino:pom:1.7.1468,12 ms
org.eclipse.jgit:org.eclipse.jgit-parent:pom:5.10.0.202012080955-r67,22 ms
org.codehaus.plexus:plexus:pom:2.0.767,22 ms
oro:oro:pom:2.0.866,76 ms
org.slf4j:slf4j-api:pom:1.7.3262,58 ms
commons-collections:commons-collections:pom:2.062,45 ms
org.eclipse.jgit:org.eclipse.jgit.ssh.jsch:pom:5.10.0.202012080955-r61,11 ms
org.sonatype.aether:aether-impl:pom:1.1161,37 ms
org.codehaus.plexus:plexus-container-default:pom:1.0-alpha-9-stable-161,22 ms
com.google.code.findbugs:jsr305:pom:2.0.160,24 ms
com.jcraft:jsch:pom:0.1.4959,02 ms
org.codehaus.plexus:plexus-classworlds:pom:1.2-alpha-958,04 ms
ch.qos.logback:logback-classic:pom:1.2.757,91 ms
org.sonatype.sisu:sisu-guice:pom:2.1.757,63 ms
commons-io:commons-io:pom:2.557,02 ms
commons-beanutils:commons-beanutils:pom:1.657,12 ms
javax.inject:javax.inject:pom:157,82 ms
com.jcraft:jzlib:pom:1.1.156,09 ms
org.jboss.weld:weld-parent:pom:2656,42 ms
org.apache.maven:maven:pom:2.2.155,59 ms
org.apache.maven:maven-project:pom:2.2.155,15 ms
org.slf4j:slf4j-parent:pom:1.7.3255,55 ms
ch.qos.logback:logback-core:pom:1.2.755,62 ms
org.junit.jupiter:junit-jupiter-params:pom:5.9.255,39 ms
org.apache.maven:maven-plugin-api:pom:3.055,91 ms
org.sonatype.oss:oss-parent:pom:355,16 ms
org.apache.maven:maven:pom:3.1.055,12 ms
org.apache:apache:pom:1453,84 ms
org.assertj:assertj-core:pom:3.21.053,16 ms
org.apache.maven.doxia:doxia-logging-api:pom:1.11.153,83 ms
commons-codec:commons-codec:pom:1.652,94 ms
org.apache:apache:pom:1352,42 ms
ch.qos.logback:logback-parent:pom:1.2.752,44 ms
net.sourceforge.pmd:pmd-javascript:pom:6.49.052,50 ms
org.apache.maven:maven-model:pom:3.1.052,30 ms
org.apache.maven:maven-settings:pom:3.1.052,33 ms
com.jcraft:jsch.agentproxy.core:pom:0.0.951,97 ms
org.apache.maven:maven-parent:pom:3551,64 ms
org.apache:apache:pom:651,83 ms
org.codehaus.plexus:plexus-utils:pom:3.3.051,78 ms
org.sonatype.aether:aether-api:pom:1.751,32 ms
org.apache.velocity:velocity:pom:1.751,33 ms
org.apache.maven.shared:maven-artifact-transfer:pom:0.13.150,31 ms
org.junit:junit-bom:pom:5.7.150,17 ms
org.apache.httpcomponents:httpcore:pom:4.4.1450,00 ms
xml-apis:xml-apis:pom:1.0.b250,17 ms
org.apache.maven.reporting:maven-reporting-impl:pom:3.2.050,00 ms
org.apache.maven:maven-core:pom:3.1.050,88 ms
org.apache.maven:maven-core:pom:3.0.348,45 ms
org.apache.maven:maven-parent:pom:3648,84 ms
org.apache.commons:commons-parent:pom:4748,48 ms
net.sourceforge.pmd:pmd-java:pom:6.49.048,23 ms
org.apache.maven.doxia:doxia-core:pom:1.11.148,46 ms
commons-chain:commons-chain:pom:1.148,33 ms
org.eclipse.jgit:org.eclipse.jgit:pom:5.10.0.202012080955-r47,77 ms
com.googlecode.javaewah:JavaEWAH:pom:1.1.747,41 ms
com.jcraft:jsch:pom:0.1.5547,14 ms
org.apache.maven.plugins:maven-clean-plugin:pom:3.2.047,30 ms
org.apache:apache:pom:2547,29 ms
org.apache.maven:maven-profile:pom:2.2.147,30 ms
org.apache.maven:maven-artifact:pom:3.047,23 ms
org.commonjava.maven.plugins:directory-maven-plugin:pom:0.3.146,74 ms
org.apache.maven.plugins:maven-pmd-plugin:jar:3.19.046,85 ms
org.sonatype.sisu:sisu-parent:pom:2.1.146,14 ms
org.apache.maven.doxia:doxia-site-renderer:pom:1.11.146,37 ms
org.apache.httpcomponents:httpcomponents-parent:pom:1146,78 ms
log4j:log4j:pom:1.2.1246,66 ms
commons-digester:commons-digester:pom:1.646,89 ms
org.sonatype.oss:oss-parent:pom:645,87 ms
org.apache.maven:maven-parent:pom:1545,51 ms
org.apache.maven.plugins:maven-install-plugin:pom:2.5.245,87 ms
org.apache.maven:maven-settings-builder:pom:3.0.345,01 ms
org.sonatype.sisu:sisu-inject-bean:pom:2.1.145,81 ms
org.hamcrest:hamcrest-core:pom:1.345,43 ms
org.hamcrest:hamcrest:pom:2.245,94 ms
net.bytebuddy:byte-buddy-agent:pom:1.12.845,38 ms
org.codehaus.plexus:plexus-classworlds:pom:2.2.345,57 ms
net.sourceforge.pmd:pmd:pom:6.49.045,12 ms
org.sonatype.oss:oss-parent:pom:945,17 ms
com.beust:jcommander:pom:1.4845,36 ms
org.apache.maven.doxia:doxia-skin-model:pom:1.11.145,26 ms
avalon-framework:avalon-framework:pom:4.1.345,37 ms
org.apache.commons:commons-parent:pom:4244,20 ms
org.apache.maven:maven-settings:pom:3.0.344,16 ms
org.apache.maven:maven-model:pom:2.2.144,03 ms
org.codehaus.plexus:plexus:pom:6.544,63 ms
org.apache.commons:commons-parent:pom:3944,23 ms
org.slf4j:slf4j-parent:pom:1.7.3644,75 ms
org.ow2.asm:asm:pom:9.344,39 ms
logkit:logkit:pom:1.0.144,09 ms
org.apache.maven.reporting:maven-reporting-api:pom:3.1.144,16 ms
org.apache.maven.shared:maven-shared-components:pom:1544,84 ms
com.jcraft:jsch.agentproxy:pom:0.0.943,31 ms
net.java.dev.jna:jna-platform:pom:4.1.043,11 ms
org.commonjava.maven.plugins:directory-maven-plugin:jar:0.3.143,95 ms
org.apache.maven.plugins:maven-install-plugin:jar:2.5.243,19 ms
org.apache.maven.shared:maven-shared-components:pom:3443,48 ms
org.sonatype.forge:forge-parent:pom:743,50 ms
org.apache.maven:maven-model-builder:pom:3.0.343,32 ms
org.codehaus.plexus:plexus-containers:pom:1.0.343,70 ms
org.junit.jupiter:junit-jupiter-engine:pom:5.9.243,63 ms
net.bytebuddy:byte-buddy-parent:pom:1.12.843,82 ms
org.apache:apache:pom:2143,91 ms
org.apache.httpcomponents:httpcomponents-core:pom:4.4.1443,69 ms
org.apache.maven.doxia:doxia-modules:pom:1.11.143,31 ms
org.codehaus.plexus:plexus-components:pom:1.1.1243,70 ms
commons-collections:commons-collections:pom:3.143,62 ms
org.apache.velocity:velocity-tools:pom:2.043,88 ms
commons-collections:commons-collections:pom:3.243,92 ms
org.eclipse.sisu:sisu-inject:pom:0.3.543,24 ms
org.apache.maven:maven-model-builder:pom:3.1.043,18 ms
org.apache.httpcomponents:httpclient:pom:4.5.1343,56 ms
org.apache.maven.doxia:doxia-integration-tools:pom:1.11.143,28 ms
org.sonatype.oss:oss-parent:pom:542,01 ms
org.apache.maven.plugins:maven-plugins:pom:3542,47 ms
org.apache.maven.plugins:maven-clean-plugin:jar:3.2.042,26 ms
org.apache.maven.plugins:maven-plugins:pom:3742,31 ms
commons-io:commons-io:pom:2.642,61 ms
org.sonatype.sisu.inject:guice-plexus:pom:2.1.142,22 ms
org.sonatype.aether:aether-util:pom:1.1142,96 ms
org.codehaus.plexus:plexus:pom:2.0.242,03 ms
org.apache.maven:maven-parent:pom:2342,40 ms
org.junit:junit-bom:pom:5.8.042,55 ms
org.objenesis:objenesis-parent:pom:3.242,08 ms
org.sonatype.sisu:sisu-inject-bean:pom:1.4.242,36 ms
org.apache.maven:maven-model-builder:pom:3.042,71 ms
org.codehaus.plexus:plexus-container-default:pom:2.1.042,77 ms
org.apache.commons:commons-text:pom:1.342,56 ms
org.apache.commons:commons-parent:pom:4542,72 ms
org.codehaus.plexus:plexus-interpolation:pom:1.1642,98 ms
org.codehaus.plexus:plexus:pom:3.342,67 ms
com.jcraft:jsch.agentproxy.pageant:pom:0.0.941,70 ms
org.apache.maven.plugins:maven-plugins:pom:2541,58 ms
org.apache.maven.shared:maven-shared-utils:pom:3.3.441,60 ms
org.apache.maven:maven-model:pom:3.0.341,28 ms
org.sonatype.plexus:plexus-sec-dispatcher:pom:1.341,49 ms
org.sonatype.forge:forge-parent:pom:441,12 ms
org.codehaus.plexus:plexus:pom:3.3.141,32 ms
org.junit:junit-bom:pom:5.9.241,89 ms
org.hamcrest:hamcrest-all:pom:1.341,23 ms
org.apache.maven:maven-repository-metadata:pom:3.041,58 ms
org.ow2:ow2:pom:1.541,73 ms
org.apache.geronimo.genesis:genesis-default-flava:pom:2.041,83 ms
org.codehaus.plexus:plexus-i18n:pom:1.0-beta-1041,30 ms
org.apache.commons:commons-parent:pom:941,92 ms
commons-logging:commons-logging:pom:1.041,40 ms
dom4j:dom4j:pom:1.141,17 ms
javax.annotation:javax.annotation-api:pom:1.241,69 ms
org.codehaus.plexus:plexus:pom:3.0.141,86 ms
com.jcraft:jsch.agentproxy.connector-factory:pom:0.0.940,94 ms
com.jcraft:jsch.agentproxy.jsch:pom:0.0.940,90 ms
org.sonatype.sisu:sisu-inject-plexus:pom:2.1.140,48 ms
org.sonatype.aether:aether-parent:pom:1.1140,15 ms
classworlds:classworlds:pom:1.1-alpha-240,71 ms
org.apache.maven:maven-aether-provider:pom:3.040,45 ms
org.sonatype.aether:aether-spi:pom:1.740,35 ms
org.apache:apache:pom:1640,00 ms
org.junit:junit-bom:pom:5.7.240,99 ms
org.antlr:antlr4-master:pom:4.7.240,97 ms
org.apache.commons:commons-lang3:pom:3.8.140,64 ms
com.google.code.gson:gson-parent:pom:2.8.940,24 ms
org.apache.xbean:xbean-reflect:pom:3.740,35 ms
org.apache.geronimo.genesis:genesis-java5-flava:pom:2.040,09 ms
org.apache.maven.doxia:doxia-module-xhtml5:pom:1.11.140,48 ms
com.jcraft:jsch.agentproxy.sshagent:pom:0.0.939,63 ms
org.apache.maven:maven-parent:pom:2439,98 ms
org.apache.maven.plugins:maven-pmd-plugin:pom:3.19.039,32 ms
org.apache.maven:maven-parent:pom:3739,06 ms
org.apache:apache:pom:2339,62 ms
org.codehaus.plexus:plexus-interpolation:pom:1.1439,03 ms
org.sonatype.sisu.inject:guice-bean:pom:2.1.139,53 ms
org.sonatype.sisu:sisu-inject:pom:2.1.139,26 ms
org.sonatype.sisu:sisu-guice:pom:2.9.439,61 ms
org.apache.maven:maven-settings:pom:2.2.139,79 ms
org.junit.platform:junit-platform-commons:pom:1.9.239,25 ms
org.apache.maven:maven:pom:3.039,95 ms
org.sonatype.sisu:sisu-parent:pom:1.4.239,06 ms
org.slf4j:slf4j-api:pom:1.7.3639,61 ms
commons-collections:commons-collections:pom:3.2.139,98 ms
org.apache.maven:maven-plugin-api:pom:3.1.039,75 ms
org.eclipse.sisu:org.eclipse.sisu.plexus:pom:0.3.539,14 ms
org.apache.httpcomponents:httpcore:pom:4.4.1339,01 ms
org.apache.maven.reporting:maven-reporting-api:pom:3.039,80 ms
org.apache.maven.doxia:doxia:pom:1.039,41 ms
org.codehaus.plexus:plexus-resources:pom:1.2.039,79 ms
net.java.dev.jna:jna:pom:4.1.038,09 ms
org.apache.maven:maven:pom:3.0.338,51 ms
org.apache:apache:pom:2738,99 ms
org.sonatype.plexus:plexus-cipher:pom:1.438,91 ms
org.apache.maven:maven-artifact:pom:3.0.338,26 ms
org.apache:apache:pom:938,99 ms
org.junit.jupiter:junit-jupiter-api:pom:5.9.238,90 ms
junit:junit:pom:4.13.238,54 ms
org.assertj:assertj-parent-pom:pom:2.2.1338,07 ms
org.apache.maven:maven-parent:pom:3338,50 ms
org.apache.maven:maven-model:pom:3.038,40 ms
org.codehaus.plexus:plexus-containers:pom:2.1.138,59 ms
org.codehaus.plexus:plexus:pom:2.0.638,25 ms
org.apache.maven.shared:maven-common-artifact-filters:pom:3.1.038,98 ms
org.apache.maven:maven-parent:pom:3038,45 ms
org.apache.commons:commons-parent:pom:5238,74 ms
org.apache.geronimo.genesis:genesis:pom:2.038,35 ms
org.codehaus.plexus:plexus:pom:1.0.1038,11 ms
commons-logging:commons-logging:pom:1.138,41 ms
javax.enterprise:cdi-api:pom:1.238,86 ms
org.eclipse.aether:aether-spi:pom:0.9.0.M238,01 ms
org.apache.httpcomponents:httpcomponents-client:pom:4.5.1338,87 ms
org.apache.commons:commons-parent:pom:3438,24 ms
org.apache.maven:maven-parent:pom:1038,57 ms
com.jcraft:jsch.agentproxy.usocket-jna:pom:0.0.937,73 ms
com.jcraft:jsch.agentproxy.usocket-nc:pom:0.0.937,70 ms
org.apache.maven:maven-parent:pom:3437,84 ms
org.apache.maven:maven-aether-provider:pom:3.0.337,14 ms
org.codehaus.plexus:plexus-utils:pom:1.5.1537,16 ms
org.apache.maven:maven-repository-metadata:pom:2.2.137,94 ms
org.apache.maven:maven-plugin-registry:pom:2.2.137,76 ms
org.hamcrest:hamcrest-parent:pom:1.337,16 ms
org.apache.maven.surefire:surefire:pom:2.22.237,51 ms
org.codehaus.plexus:plexus:pom:5.137,75 ms
org.codehaus.plexus:plexus-component-annotations:pom:2.1.137,62 ms
org.slf4j:slf4j-api:pom:1.7.537,15 ms
net.sourceforge.pmd:pmd-core:pom:6.49.037,11 ms
com.google.code.gson:gson:pom:2.8.937,75 ms
org.apache.maven.doxia:doxia-sink-api:pom:1.11.137,14 ms
org.codehaus.plexus:plexus-containers:pom:2.1.037,25 ms
org.apache.xbean:xbean:pom:3.737,25 ms
com.google:google:pom:137,52 ms
org.apache.maven.doxia:doxia-module-xhtml:pom:1.11.137,70 ms
org.codehaus.plexus:plexus-containers:pom:1.0-alpha-3037,07 ms
org.codehaus.plexus:plexus-components:pom:4.037,10 ms
org.eclipse.aether:aether:pom:0.9.0.M237,23 ms
org.apache:apache:pom:1836,22 ms
org.codehaus.plexus:plexus-components:pom:1.1.1836,26 ms
org.codehaus.plexus:plexus-component-annotations:pom:1.5.536,67 ms
org.apache.maven:maven-repository-metadata:pom:3.0.336,72 ms
org.codehaus.plexus:plexus-classworlds:pom:2.436,29 ms
org.sonatype.sisu.inject:guice-parent:pom:2.9.436,18 ms
org.sonatype.aether:aether-api:pom:1.1136,69 ms
org.sonatype.aether:aether-spi:pom:1.1136,84 ms
org.apache.maven:maven-plugin-api:pom:2.2.136,35 ms
org.apache.maven:maven-artifact-manager:pom:2.2.136,45 ms
org.apache.commons:commons-parent:pom:2236,60 ms
org.codehaus.plexus:plexus-utils:pom:3.0.1536,29 ms
org.junit.platform:junit-platform-engine:pom:1.9.236,04 ms
org.mockito:mockito-core:pom:4.4.036,15 ms
org.objenesis:objenesis:pom:3.236,89 ms
org.apache.maven:maven-settings:pom:3.036,73 ms
org.sonatype.sisu.inject:guice-plexus:pom:1.4.236,89 ms
org.apache.maven.shared:maven-shared-utils:pom:3.1.036,08 ms
org.apache.maven.shared:maven-common-artifact-filters:pom:3.3.136,16 ms
net.sourceforge.pmd:pmd-jsp:pom:6.49.036,48 ms
org.apache.maven.doxia:doxia:pom:1.11.136,98 ms
com.google.collections:google-collections:pom:1.036,84 ms
org.apache.maven:maven-repository-metadata:pom:3.1.036,82 ms
org.eclipse.sisu:sisu-plexus:pom:0.3.536,74 ms
net.java:jvnet-parent:pom:336,83 ms
org.codehaus.plexus:plexus-classworlds:pom:2.4.236,24 ms
org.apache.httpcomponents:httpcomponents-core:pom:4.4.1336,86 ms
org.apache:apache:pom:736,60 ms
org.codehaus.plexus:plexus-container-default:pom:1.0-alpha-936,51 ms
org.sonatype.forge:forge-parent:pom:635,58 ms
org.apache.maven:maven-parent:pom:1135,64 ms
org.codehaus.plexus:plexus:pom:1.0.435,29 ms
org.codehaus.plexus:plexus-utils:pom:1.0.435,69 ms
backport-util-concurrent:backport-util-concurrent:pom:3.135,38 ms
org.apache.maven.shared:maven-shared-utils:pom:0.435,84 ms
org.slf4j:jcl-over-slf4j:pom:1.7.3235,15 ms
org.opentest4j:opentest4j:pom:1.2.035,58 ms
net.bytebuddy:byte-buddy:pom:1.12.835,52 ms
org.sonatype.sisu:sisu-inject-plexus:pom:1.4.235,46 ms
org.sonatype.sisu:sisu-inject:pom:1.4.235,22 ms
org.apache.maven.shared:maven-shared-components:pom:3635,28 ms
org.apache:apache:pom:2635,25 ms
org.apache.commons:commons-lang3:pom:3.12.035,54 ms
org.antlr:antlr4-runtime:pom:4.7.235,18 ms
net.sourceforge.saxon:saxon:pom:9.1.0.835,76 ms
org.apache:apache:pom:1935,50 ms
org.codehaus.plexus:plexus-classworlds:pom:2.6.035,71 ms
org.apache.maven.doxia:doxia-sitetools:pom:1.11.135,39 ms
commons-digester:commons-digester:pom:1.835,20 ms
commons-logging:commons-logging:pom:1.235,75 ms
commons-codec:commons-codec:pom:1.1135,24 ms
org.apache.maven:maven-parent:pom:1635,28 ms
org.sonatype.oss:oss-parent:pom:734,14 ms
org.codehaus.plexus:plexus-containers:pom:1.5.534,23 ms
org.codehaus.plexus:plexus-components:pom:1.1.1434,12 ms
junit:junit:pom:3.8.134,09 ms
org.apache.maven.shared:maven-shared-components:pom:1934,01 ms
org.sonatype.forge:forge-parent:pom:1034,20 ms
org.apiguardian:apiguardian-api:pom:1.1.234,54 ms
org.junit.vintage:junit-vintage-engine:pom:5.9.234,23 ms
org.apache.maven.surefire:surefire-logger-api:pom:2.22.234,84 ms
org.apache.maven:maven-core:pom:3.034,67 ms
org.sonatype.aether:aether-parent:pom:1.734,08 ms
org.sonatype.aether:aether-util:pom:1.734,82 ms
org.sonatype.aether:aether-impl:pom:1.734,32 ms
org.slf4j:slf4j-parent:pom:1.7.534,23 ms
commons-io:commons-io:pom:2.11.034,39 ms
org.slf4j:jul-to-slf4j:pom:1.7.3634,66 ms
org.apache.maven.doxia:doxia-decoration-model:pom:1.11.134,92 ms
org.codehaus.plexus:plexus:pom:1.0.1134,91 ms
org.codehaus.plexus:plexus-velocity:pom:1.234,82 ms
org.codehaus.plexus:plexus:pom:4.034,51 ms
org.apache:apache:pom:434,13 ms
commons-beanutils:commons-beanutils:pom:1.7.034,92 ms
org.apache.maven:maven-settings-builder:pom:3.1.034,20 ms
org.apache.maven:maven-artifact:pom:3.1.034,42 ms
org.codehaus.plexus:plexus-classworlds:pom:2.5.234,87 ms
org.eclipse.aether:aether-api:pom:0.9.0.M234,42 ms
org.codehaus.plexus:plexus-components:pom:6.634,12 ms
org.codehaus.plexus:plexus:pom:834,82 ms
org.sonatype.spice:spice-parent:pom:1233,99 ms
org.apache.maven:maven-plugin-api:pom:3.0.333,53 ms
org.codehaus.plexus:plexus-interpolation:pom:1.1133,07 ms
org.apache.maven:maven-artifact:pom:2.2.133,82 ms
org.apache.maven:maven-settings-builder:pom:3.033,79 ms
org.apache.maven.shared:maven-shared-components:pom:3333,07 ms
org.apache.maven.shared:maven-shared-components:pom:3033,90 ms
org.apache.commons:commons-lang3:pom:3.733,77 ms
commons-lang:commons-lang:pom:2.433,27 ms
commons-logging:commons-logging:pom:1.0.333,41 ms
commons-collections:commons-collections:pom:2.133,89 ms
org.apache.maven:maven-aether-provider:pom:3.1.033,63 ms
org.sonatype.spice:spice-parent:pom:1732,83 ms
org.sonatype.sisu.inject:guice-bean:pom:1.4.232,52 ms
org.codehaus.plexus:plexus-components:pom:1.332,73 ms
org.apache.maven.doxia:doxia-sink-api:pom:1.032,06 ms
org.codehaus.plexus:plexus-interpolation:pom:1.2632,64 ms
+
+ +
+ + + + diff --git a/maven-modules/maven-build-optimization/pom.xml b/maven-modules/maven-build-optimization/pom.xml new file mode 100644 index 0000000000..f0da31ceda --- /dev/null +++ b/maven-modules/maven-build-optimization/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + maven-build-optimization + 0.0.1-SNAPSHOT + maven-build-optimization + pom + + + com.baeldung + maven-modules + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-profiler-plugin + ${profiler.version} + + + org.apache.maven.plugins + maven-failsafe-plugin + ${failsafe.version} + + + + integration-test + verify + + + + + + + + + + skipITs + + + + org.apache.maven.plugins + maven-failsafe-plugin + + true + + + + + + + + + 3.1.2 + 1.7 + + + \ No newline at end of file diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index f7bba3a8ff..e139a4b921 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -20,6 +20,7 @@ dependency-exclusion host-maven-repo-example maven-archetype + maven-build-optimization maven-builder-plugin maven-classifier maven-copy-files From c0eb994c4585bafc86a12b15c434e5eb89f8d991 Mon Sep 17 00:00:00 2001 From: GaetanoPiazzolla Date: Thu, 10 Aug 2023 10:59:27 +0200 Subject: [PATCH 03/26] JAVA-24009 | changed maven repo address for spring-native dependencies --- pom.xml | 2 +- spring-native/pom.xml | 22 ++++++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 97e3cf6639..1c2dd0dc06 100644 --- a/pom.xml +++ b/pom.xml @@ -909,7 +909,7 @@ spring-kafka - + spring-native spring-security-modules spring-protobuf spring-quartz diff --git a/spring-native/pom.xml b/spring-native/pom.xml index 55f17c833f..97eb33c1c7 100644 --- a/spring-native/pom.xml +++ b/spring-native/pom.xml @@ -17,17 +17,27 @@ - spring-release - Spring release - https://repo.spring.io/release + spring-milestone + Spring Milestone + https://repo.spring.io/milestone + + + spring-snapshot + Spring Snapshot + https://repo.spring.io/snapshot - spring-release - Spring release - https://repo.spring.io/release + spring-plugins-snapshot + Spring Plugins Snapshot + https://repo.spring.io/plugins-snapshot + + + spring-plugins-milestone + Spring Plugins Milestone + https://repo.spring.io/plugins-milestone From aa110827b32cef636e18966620e28db7cb33c28f Mon Sep 17 00:00:00 2001 From: kasramp Date: Sat, 12 Aug 2023 21:10:44 +0200 Subject: [PATCH 04/26] JAVA-21093 add endpoints to the readme file of the thymeleaf module --- spring-web-modules/spring-thymeleaf/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/spring-web-modules/spring-thymeleaf/README.md b/spring-web-modules/spring-thymeleaf/README.md index b49095f5b1..7121085ac0 100644 --- a/spring-web-modules/spring-thymeleaf/README.md +++ b/spring-web-modules/spring-thymeleaf/README.md @@ -23,3 +23,20 @@ mvn cargo:run ### Security The user/password required is: user1/user1Pass + +### Endpoints + +All endpoints start with `http://localhost:8082/spring-thymeleaf`: + +- `/dates` +- `/saveStudent` +- `/objects` +- `/fragments` +- `/markup` +- `/params` +- `/other` +- `/function-call` +- `/html` +- `/js` +- `/plain` +- `/layout` \ No newline at end of file From 0323955992037583c89d9a2ce45b27e3a4b84293 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sun, 13 Aug 2023 09:52:02 +0530 Subject: [PATCH 05/26] Bael 6625 new (#14476) * BAEL-6625 - spring data neo4j example * BAEL-6625 - spring data neo4j example * BAEL-6625 - optimized imports * BAEL-6625 - moving project to jdk9 and above * BAEL-6625 - changing test names --- .../com/baeldung/neo4j/Neo4jLiveTest.java | 178 ------------------ persistence-modules/spring-data-neo4j/pom.xml | 56 +++--- .../spring/data/neo4j/Neo4JApplication.java | 12 ++ .../MovieDatabaseNeo4jConfiguration.java | 26 --- .../MovieDatabaseNeo4jTestConfiguration.java | 36 ---- .../spring/data/neo4j/config/Neo4jConfig.java | 14 ++ .../spring/data/neo4j/domain/Author.java | 48 +++++ .../spring/data/neo4j/domain/Book.java | 58 ++++++ .../spring/data/neo4j/domain/Car.java | 48 ----- .../spring/data/neo4j/domain/Company.java | 42 ----- .../spring/data/neo4j/domain/Movie.java | 64 ------- .../spring/data/neo4j/domain/Person.java | 52 ----- .../spring/data/neo4j/domain/Role.java | 50 ----- .../neo4j/repository/AuthorRepository.java | 16 ++ .../data/neo4j/repository/BookRepository.java | 14 ++ .../neo4j/repository/MovieRepository.java | 23 --- .../neo4j/repository/PersonRepository.java | 9 - .../data/neo4j/services/MovieService.java | 51 ----- .../src/main/resources/application.properties | 3 + .../src/main/resources/test.png | Bin 855 -> 0 bytes .../java/com/baeldung/SpringContextTest.java | 19 -- ...ookAndAuthorRepositoryIntegrationTest.java | 69 +++++++ .../neo4j/MovieRepositoryIntegrationTest.java | 131 ------------- pom.xml | 4 +- 24 files changed, 257 insertions(+), 766 deletions(-) delete mode 100644 persistence-modules/neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/Neo4JApplication.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/Neo4jConfig.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Author.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Book.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/AuthorRepository.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/BookRepository.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java delete mode 100644 persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java create mode 100644 persistence-modules/spring-data-neo4j/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-neo4j/src/main/resources/test.png delete mode 100644 persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/BookAndAuthorRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java diff --git a/persistence-modules/neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java b/persistence-modules/neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java deleted file mode 100644 index 8591dd3a8d..0000000000 --- a/persistence-modules/neo4j/src/test/java/com/baeldung/neo4j/Neo4jLiveTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.baeldung.neo4j; - - -import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; - -import java.io.File; -import java.time.Duration; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.neo4j.configuration.GraphDatabaseSettings; -import org.neo4j.dbms.api.DatabaseManagementService; -import org.neo4j.dbms.api.DatabaseManagementServiceBuilder; -import org.neo4j.graphdb.GraphDatabaseService; -import org.neo4j.graphdb.Label; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.NotFoundException; -import org.neo4j.graphdb.RelationshipType; -import org.neo4j.graphdb.Result; -import org.neo4j.graphdb.Transaction; - -/** - * To run this test you will need to have an instance of the docker running on your machine (Docker desktop - for Windows and Docker instance for linux) - * After your docker instance is up run this test - */ -public class Neo4jLiveTest { - - private static GraphDatabaseService graphDb; - private static Transaction transaction; - private static DatabaseManagementService managementService; - - @Before - public void setUp() { - managementService = new DatabaseManagementServiceBuilder(new File("data/cars").toPath()) - .setConfig( GraphDatabaseSettings.transaction_timeout, Duration.ofSeconds( 60 ) ) - .setConfig( GraphDatabaseSettings.preallocate_logical_logs, false ).build(); - graphDb = managementService.database( DEFAULT_DATABASE_NAME ); - } - - @After - public void tearDown() { - managementService.shutdown(); - } - - @Test - public void testPersonCar() { - transaction = graphDb.beginTx(); - Node car = transaction.createNode(Label.label("Car")); - car.setProperty("make", "tesla"); - car.setProperty("model", "model3"); - - Node owner = transaction.createNode(Label.label("Person")); - owner.setProperty("firstName", "baeldung"); - owner.setProperty("lastName", "baeldung"); - - owner.createRelationshipTo(car, RelationshipType.withName("owner")); - - Result result = transaction.execute("MATCH (c:Car) <-[owner]- (p:Person) " + - "WHERE c.make = 'tesla'" + - "RETURN p.firstName, p.lastName"); - - Map firstResult = result.next(); - - Assert.assertEquals("baeldung", firstResult.get("p.firstName")); - } - - @Test - public void testCreateNode() { - transaction = graphDb.beginTx(); - Result result = transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" + - "RETURN baeldung"); - - Map firstResult = result.next(); - Node firstNode = (Node) firstResult.get("baeldung"); - - Assert.assertEquals(firstNode.getProperty("name"), "Baeldung"); - } - - @Test - public void testCreateNodeAndLink() { - transaction = graphDb.beginTx(); - Result result = transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + - "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + - "RETURN baeldung, tesla"); - - Map firstResult = result.next(); - - Assert.assertTrue(firstResult.containsKey("baeldung")); - Assert.assertTrue(firstResult.containsKey("tesla")); - } - - @Test - public void testFindAndReturn() { - transaction = graphDb.beginTx(); - transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + - "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + - "RETURN baeldung, tesla"); - - Result result = transaction.execute("MATCH (company:Company)-[:owns]-> (car:Car)" + - "WHERE car.make='tesla' and car.model='modelX'" + - "RETURN company.name"); - - Map firstResult = result.next(); - - Assert.assertEquals(firstResult.get("company.name"), "Baeldung"); - } - - @Test - public void testUpdate() { - transaction = graphDb.beginTx(); - transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + - "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + - "RETURN baeldung, tesla"); - - Result result = transaction.execute("MATCH (car:Car)" + - "WHERE car.make='tesla'" + - " SET car.milage=120" + - " SET car :Car:Electro" + - " SET car.model=NULL" + - " RETURN car"); - - Map firstResult = result.next(); - Node car = (Node) firstResult.get("car"); - - Assert.assertEquals(car.getProperty("milage"), 120L); - Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro"))); - - try { - car.getProperty("model"); - Assert.fail(); - } catch (NotFoundException e) { - // expected - } - } - - @Test - public void testDelete() { - transaction = graphDb.beginTx(); - transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + - "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + - "RETURN baeldung, tesla"); - - transaction.execute("MATCH (company:Company)" + - " WHERE company.name='Baeldung'" + - " DELETE company"); - - Result result = transaction.execute("MATCH (company:Company)" + - " WHERE company.name='Baeldung'" + - " RETURN company"); - - Assert.assertFalse(result.hasNext()); - } - - @Test - public void testBindings() { - transaction = graphDb.beginTx(); - Map params = new HashMap<>(); - params.put("name", "baeldung"); - params.put("make", "tesla"); - params.put("model", "modelS"); - - Result result = transaction.execute("CREATE (baeldung:Company {name:$name}) " + - "-[:owns]-> (tesla:Car {make: $make, model: $model})" + - "RETURN baeldung, tesla", params); - - Map firstResult = result.next(); - Assert.assertTrue(firstResult.containsKey("baeldung")); - Assert.assertTrue(firstResult.containsKey("tesla")); - - Node car = (Node) firstResult.get("tesla"); - Assert.assertEquals(car.getProperty("model"), "modelS"); - } -} diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index 33f2966db3..8a0a9ff464 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -15,53 +15,39 @@ - org.neo4j - neo4j-ogm-embedded-driver - ${neo4j-ogm.version} + org.neo4j.test + neo4j-harness + ${neo4j-harness.version} + test - org.springframework.data - spring-data-neo4j - ${spring-data-neo4j.version} - - - com.voodoodyne.jackson.jsog - jackson-jsog - ${jackson-jsog.version} - compile + org.springframework.boot + spring-boot-starter-data-neo4j + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-logging + + org.springframework.boot spring-boot-starter-test ${spring-boot.version} test - - - org.neo4j - neo4j-ogm-test - ${neo4j-ogm.version} - test - - - org.neo4j.test - neo4j-harness - ${neo4j.version} - test - - - org.springframework - spring-test - ${spring-test.version} + + + org.springframework.boot + spring-boot-starter-logging + + - 3.4.6 - 5.0.1.RELEASE - 1.1 - 2.0.1.RELEASE - 5.0.1.RELEASE - 3.1.2 + 2.7.14 + 5.10.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/Neo4JApplication.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/Neo4JApplication.java new file mode 100644 index 0000000000..8e1f104be5 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/Neo4JApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.neo4j; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Neo4JApplication { + + public static void main(String[] args) { + SpringApplication.run(Neo4JApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java deleted file mode 100644 index 4e87c24614..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.spring.data.neo4j.config; - -import org.neo4j.ogm.config.Configuration.Builder; -import org.neo4j.ogm.session.SessionFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; - -@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) -@Configuration -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") -public class MovieDatabaseNeo4jConfiguration { - - public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474"; - - @Bean - public org.neo4j.ogm.config.Configuration getConfiguration() { - return new Builder().uri(URL).build(); - } - - @Bean - public SessionFactory getSessionFactory() { - return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); - } -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java deleted file mode 100644 index a4cbe4b809..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.spring.data.neo4j.config; - -import org.neo4j.ogm.config.Configuration.Builder; -import org.neo4j.ogm.session.SessionFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; -import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") -@Profile({ "embedded", "test" }) -public class MovieDatabaseNeo4jTestConfiguration { - - @Bean - public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new Builder().build(); - return config; - } - - @Bean - public SessionFactory getSessionFactory() { - return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); - } - - @Bean - public Neo4jTransactionManager transactionManager() { - return new Neo4jTransactionManager(getSessionFactory()); - } - -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/Neo4jConfig.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/Neo4jConfig.java new file mode 100644 index 0000000000..7571d01c68 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/Neo4jConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.neo4j.config; + +import org.neo4j.cypherdsl.core.renderer.Dialect; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class Neo4jConfig { + @Bean + org.neo4j.cypherdsl.core.renderer.Configuration cypherDslConfiguration() { + return org.neo4j.cypherdsl.core.renderer.Configuration.newConfig() + .withDialect(Dialect.NEO4J_5).build(); + } +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Author.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Author.java new file mode 100644 index 0000000000..69f035dcae --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Author.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.data.neo4j.domain; + + +import org.springframework.data.neo4j.core.schema.Id; +import org.springframework.data.neo4j.core.schema.Node; +import org.springframework.data.neo4j.core.schema.Relationship; + +import java.util.List; + +@Node("Author") +public class Author { + @Id + private Long id; + + private String name; + + @Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.INCOMING) + private List books; + + public Author(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Book.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Book.java new file mode 100644 index 0000000000..4e6aff6798 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Book.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.data.neo4j.domain; + +import org.springframework.data.neo4j.core.schema.Id; +import org.springframework.data.neo4j.core.schema.Node; +import org.springframework.data.neo4j.core.schema.Property; +import org.springframework.data.neo4j.core.schema.Relationship; + +@Node("Book") +public class Book { + @Id + private String isbn; + + @Property("name") + private String title; + + private Integer year; + + @Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.OUTGOING) + private Author author; + + public Book(String isbn, String title, Integer year) { + this.isbn = isbn; + this.title = title; + this.year = year; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java deleted file mode 100644 index 455407a92b..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.spring.data.neo4j.domain; - -import org.neo4j.ogm.annotation.GeneratedValue; -import org.neo4j.ogm.annotation.Id; -import org.neo4j.ogm.annotation.NodeEntity; -import org.neo4j.ogm.annotation.Relationship; - -@NodeEntity -public class Car { - @Id @GeneratedValue - private Long id; - - private String make; - - @Relationship(direction = "INCOMING") - private Company company; - - public Car(String make, String model) { - this.make = make; - this.model = model; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - private String model; -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java deleted file mode 100644 index 4422ade44f..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Company.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.spring.data.neo4j.domain; - -import org.neo4j.ogm.annotation.NodeEntity; -import org.neo4j.ogm.annotation.Relationship; - -@NodeEntity -public class Company { - private Long id; - - private String name; - - @Relationship(type="owns") - private Car car; - - public Company(String name) { - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Car getCar() { - return car; - } - - public void setCar(Car car) { - this.car = car; - } -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java deleted file mode 100644 index 996a661b07..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.spring.data.neo4j.domain; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.voodoodyne.jackson.jsog.JSOGGenerator; - -import org.neo4j.ogm.annotation.GeneratedValue; -import org.neo4j.ogm.annotation.Id; -import org.neo4j.ogm.annotation.NodeEntity; -import org.neo4j.ogm.annotation.Relationship; - -import java.util.Collection; -import java.util.List; - -@JsonIdentityInfo(generator = JSOGGenerator.class) - -@NodeEntity -public class Movie { - @Id @GeneratedValue - Long id; - - private String title; - - private int released; - private String tagline; - - @Relationship(type = "ACTED_IN", direction = Relationship.INCOMING) - private List roles; - - public Movie() { - } - - public String getTitle() { - return title; - } - - public int getReleased() { - return released; - } - - public String getTagline() { - return tagline; - } - - public Collection getRoles() { - return roles; - } - - public void setTitle(String title) { - this.title = title; - } - - public void setReleased(int released) { - this.released = released; - } - - public void setTagline(String tagline) { - this.tagline = tagline; - } - - public void setRoles(List roles) { - this.roles = roles; - } - -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java deleted file mode 100644 index 453ca1c3f3..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.spring.data.neo4j.domain; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.voodoodyne.jackson.jsog.JSOGGenerator; - -import org.neo4j.ogm.annotation.GeneratedValue; -import org.neo4j.ogm.annotation.Id; -import org.neo4j.ogm.annotation.NodeEntity; -import org.neo4j.ogm.annotation.Relationship; - -import java.util.List; - -@JsonIdentityInfo(generator = JSOGGenerator.class) -@NodeEntity -public class Person { - @Id @GeneratedValue - Long id; - - private String name; - private int born; - - @Relationship(type = "ACTED_IN") - private List movies; - - public Person() { - } - - public String getName() { - return name; - } - - public int getBorn() { - return born; - } - - public List getMovies() { - return movies; - } - - public void setName(String name) { - this.name = name; - } - - public void setBorn(int born) { - this.born = born; - } - - public void setMovies(List movies) { - this.movies = movies; - } - -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java deleted file mode 100644 index 5a18837dae..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.spring.data.neo4j.domain; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.voodoodyne.jackson.jsog.JSOGGenerator; -import org.neo4j.ogm.annotation.EndNode; -import org.neo4j.ogm.annotation.GeneratedValue; -import org.neo4j.ogm.annotation.Id; -import org.neo4j.ogm.annotation.RelationshipEntity; -import org.neo4j.ogm.annotation.StartNode; - -import java.util.Collection; - -@JsonIdentityInfo(generator = JSOGGenerator.class) -@RelationshipEntity(type = "ACTED_IN") -public class Role { - @Id @GeneratedValue - Long id; - private Collection roles; - @StartNode - private Person person; - @EndNode - private Movie movie; - - public Role() { - } - - public Collection getRoles() { - return roles; - } - - public Person getPerson() { - return person; - } - - public Movie getMovie() { - return movie; - } - - public void setRoles(Collection roles) { - this.roles = roles; - } - - public void setPerson(Person person) { - this.person = person; - } - - public void setMovie(Movie movie) { - this.movie = movie; - } -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/AuthorRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/AuthorRepository.java new file mode 100644 index 0000000000..16949dfeef --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/AuthorRepository.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.data.neo4j.repository; + +import com.baeldung.spring.data.neo4j.domain.Author; +import com.baeldung.spring.data.neo4j.domain.Book; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import org.springframework.data.neo4j.repository.query.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface AuthorRepository extends Neo4jRepository { + @Query("MATCH (b:Book)-[:WRITTEN_BY]->(a:Author) WHERE a.name = $name AND b.year > $year RETURN b") + List findBooksAfterYear(@Param("name") String name, @Param("year") Integer year); +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/BookRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/BookRepository.java new file mode 100644 index 0000000000..0489ff3c30 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/BookRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.neo4j.repository; + + +import com.baeldung.spring.data.neo4j.domain.Book; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface BookRepository extends Neo4jRepository { + Book findOneByTitle(String title); + List findAllByYear(Integer year); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java deleted file mode 100644 index dde946ea73..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.spring.data.neo4j.repository; - -import com.baeldung.spring.data.neo4j.domain.Movie; -import org.springframework.data.neo4j.annotation.Query; -import org.springframework.data.neo4j.repository.Neo4jRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -@Repository -public interface MovieRepository extends Neo4jRepository { - - Movie findByTitle(@Param("title") String title); - - @Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m") - Collection findByTitleContaining(@Param("title") String title); - - @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}") - List> graph(@Param("limit") int limit); -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java deleted file mode 100644 index 22094d26b6..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring.data.neo4j.repository; - -import com.baeldung.spring.data.neo4j.domain.Person; -import org.springframework.data.neo4j.repository.Neo4jRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonRepository extends Neo4jRepository { -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java deleted file mode 100644 index 086bf48bfa..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.spring.data.neo4j.services; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.spring.data.neo4j.repository.MovieRepository; - -import java.util.*; - -@Service -@Transactional -public class MovieService { - - @Autowired - private MovieRepository movieRepository; - - private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList<>(); - List> rels = new ArrayList<>(); - int i = 0; - while (result.hasNext()) { - Map row = result.next(); - nodes.add(map("title", row.get("movie"), "label", "movie")); - int target = i; - i++; - for (Object name : (Collection) row.get("cast")) { - Map actor = map("title", name, "label", "actor"); - int source = nodes.indexOf(actor); - if (source == -1) { - nodes.add(actor); - source = i++; - } - rels.add(map("source", source, "target", target)); - } - } - return map("nodes", nodes, "links", rels); - } - - private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap<>(2); - result.put(key1, value1); - result.put(key2, value2); - return result; - } - - public Map graph(int limit) { - Iterator> result = movieRepository.graph(limit).iterator(); - return toD3Format(result); - } -} diff --git a/persistence-modules/spring-data-neo4j/src/main/resources/application.properties b/persistence-modules/spring-data-neo4j/src/main/resources/application.properties new file mode 100644 index 0000000000..6a0b6712fd --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.neo4j.uri=bolt://localhost:7687 +spring.neo4j.authentication.username=neo4j +spring.neo4j.authentication.password=password \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/main/resources/test.png b/persistence-modules/spring-data-neo4j/src/main/resources/test.png deleted file mode 100644 index c3b5e8027635ff4f0a0b10c0a9a6aa7a014e6086..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 855 zcmex=6kE^cmKJ|O{KK0!WiZUHd? zL17V5QBfX#aS1UI2_X?t5k_Vf7B*H^PBu0!em)*P5fKr7L0%pn0bT(feo-D?UVdI4 zpg0dNAHM*Q$HT+J$HNcg@q#%Zh5rvQ2y!sUFvu`73NkPWGBOJ?{y)MX0rV0OKpYGv zIoQ})S%5M+0t`%y%uFn-%&bsZMkb)c1=$oC*g1rh3>^~-jRG5mMVuBM1ge%|WME=O zF^8Fjk%^U!0Vt;gv=3+$3p2tNMkYaKCBqLwfr*X6ijMzpG4L=04G?4&WUyx___R78 z`bEZ3n*%y$c1p?=OzsY{vOIcDRID^@mH5k5n_VmCLN*tlQtc~BqmaI3acZm^A1dHBrChNRU-KfIG`3a9F1Z+JCT zaBkFRt*1+W!zihZ}s%F&cxn?h~EIRD%9;ni-#KyOjOZ3l7 z_6Ks(XSKVYPbdvPm!tpIJj%Ot(S2`WC0AaXj1Ds{Yc~e@JYj`ND^=I^G)#%-Q1qX7 z;Q8}@p=SNS>z3K2PrXivv`$(a:Author {id: 1, name: 'J. R. R. Tolkien'})" + + "CREATE (b2:Book {isbn: '978-0547928203', name: 'The Two Towers', year: 1956})-[:WRITTEN_BY]->(a)") + .build(); + } + + @AfterAll + static void stopNeo4j() { + newServer.close(); + } + + @DynamicPropertySource + static void neo4jProperties(DynamicPropertyRegistry registry) { + registry.add("spring.neo4j.uri", newServer::boltURI); + registry.add("spring.neo4j.authentication.username", () -> "neo4j"); + registry.add("spring.neo4j.authentication.password", () -> "null"); + } + + @Autowired + private BookRepository bookRepository; + + @Autowired + private AuthorRepository authorRepository; + + @Test + void givenBookExists_whenFindOneByTitle_thenBookIsReturned() { + Book book = bookRepository.findOneByTitle("The Two Towers"); + Assertions.assertEquals("978-0547928203", book.getIsbn()); + } + + @Test + void givenOneBookExistsForYear_whenFindAllByYear_thenOneBookIsReturned() { + List books = bookRepository.findAllByYear(1954); + Assertions.assertEquals(1, books.size()); + } + + @Test + void givenOneBookExistsAfterYear_whenFindBooksAfterYear_thenOneBookIsReturned() { + List books = authorRepository.findBooksAfterYear("J. R. R. Tolkien", 1955); + Assertions.assertEquals(1, books.size()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java deleted file mode 100644 index 3d9215f32f..0000000000 --- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.baeldung.spring.data.neo4j; - -import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; -import com.baeldung.spring.data.neo4j.domain.Movie; -import com.baeldung.spring.data.neo4j.domain.Person; -import com.baeldung.spring.data.neo4j.domain.Role; -import com.baeldung.spring.data.neo4j.repository.MovieRepository; -import com.baeldung.spring.data.neo4j.repository.PersonRepository; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.*; - -import static junit.framework.TestCase.assertNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) -@ActiveProfiles(profiles = "test") -public class MovieRepositoryIntegrationTest { - - @Autowired - private MovieRepository movieRepository; - - @Autowired - private PersonRepository personRepository; - - public MovieRepositoryIntegrationTest() { - } - - @Before - public void initializeDatabase() { - System.out.println("seeding embedded database"); - Movie italianJob = new Movie(); - italianJob.setTitle("The Italian Job"); - italianJob.setReleased(1999); - movieRepository.save(italianJob); - - Person mark = new Person(); - mark.setName("Mark Wahlberg"); - personRepository.save(mark); - - Role charlie = new Role(); - charlie.setMovie(italianJob); - charlie.setPerson(mark); - Collection roleNames = new HashSet<>(); - roleNames.add("Charlie Croker"); - charlie.setRoles(roleNames); - List roles = new ArrayList<>(); - roles.add(charlie); - italianJob.setRoles(roles); - movieRepository.save(italianJob); - } - - @Test - @DirtiesContext - public void testFindByTitle() { - System.out.println("findByTitle"); - String title = "The Italian Job"; - Movie result = movieRepository.findByTitle(title); - assertNotNull(result); - assertEquals(1999, result.getReleased()); - } - - @Test - @DirtiesContext - public void testCount() { - System.out.println("count"); - long movieCount = movieRepository.count(); - assertNotNull(movieCount); - assertEquals(1, movieCount); - } - - @Test - @DirtiesContext - public void testFindAll() { - System.out.println("findAll"); - Collection result = (Collection) movieRepository.findAll(); - assertNotNull(result); - assertEquals(1, result.size()); - } - - @Test - @DirtiesContext - public void testFindByTitleContaining() { - System.out.println("findByTitleContaining"); - String title = "Italian"; - Collection result = movieRepository.findByTitleContaining(title); - assertNotNull(result); - assertEquals(1, result.size()); - } - - @Test - @DirtiesContext - public void testGraph() { - System.out.println("graph"); - List> graph = movieRepository.graph(5); - assertEquals(1, graph.size()); - Map map = graph.get(0); - assertEquals(2, map.size()); - String[] cast = (String[]) map.get("cast"); - String movie = (String) map.get("movie"); - assertEquals("The Italian Job", movie); - assertEquals("Mark Wahlberg", cast[0]); - } - - @Test - @DirtiesContext - public void testDeleteMovie() { - System.out.println("deleteMovie"); - movieRepository.delete(movieRepository.findByTitle("The Italian Job")); - assertNull(movieRepository.findByTitle("The Italian Job")); - } - - @Test - @DirtiesContext - public void testDeleteAll() { - System.out.println("deleteAll"); - movieRepository.deleteAll(); - Collection result = (Collection) movieRepository.findAll(); - assertEquals(0, result.size()); - } -} diff --git a/pom.xml b/pom.xml index cd3c6bfa33..17daf26278 100644 --- a/pom.xml +++ b/pom.xml @@ -368,7 +368,6 @@ persistence-modules/hibernate-ogm persistence-modules/java-cassandra persistence-modules/spring-data-cassandra-reactive - persistence-modules/spring-data-neo4j java-nashorn jeromq @@ -545,7 +544,6 @@ persistence-modules/hibernate-ogm persistence-modules/java-cassandra persistence-modules/spring-data-cassandra-reactive - persistence-modules/spring-data-neo4j java-nashorn @@ -940,6 +938,7 @@ image-processing language-interop gradle-modules/gradle/maven-to-gradle + persistence-modules/spring-data-neo4j @@ -1211,6 +1210,7 @@ image-processing language-interop gradle-modules/gradle/maven-to-gradle + persistence-modules/spring-data-neo4j From cb111b0d8be5383d5693b60073ef07c7a5b01ea6 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Mon, 14 Aug 2023 18:03:59 +0100 Subject: [PATCH 06/26] Conversion From 12 Hours Time to 24 Hours Time in Java (#14580) --- .../TimeConversionUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java diff --git a/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java new file mode 100644 index 0000000000..e82af6dd19 --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/twelvehourstotwentyhours/TimeConversionUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.twelvehourstotwentyhours; + +import static org.junit.jupiter.api.Assertions.*; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Locale; +import org.junit.jupiter.api.Test; + +public class TimeConversionUnitTest { + + @Test + public void givenTimeInTwelveHours_whenConvertingToTwentyHours_thenConverted() throws ParseException { + SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm"); + SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); + Date date = parseFormat.parse("06:00 PM"); + assertEquals("18:00", displayFormat.format(date)); + } + + @Test + public void givenTimeInTwelveHours_whenConvertingToTwentyHoursWithDateTimeFormatter_thenConverted() throws ParseException { + String time = LocalTime.parse("06:00 PM", DateTimeFormatter.ofPattern("hh:mm a", Locale.US)) + .format(DateTimeFormatter.ofPattern("HH:mm")); + assertEquals("18:00", time); + } + +} From 1df07e6696576d363890d67384e9dffb8767338d Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr Date: Tue, 15 Aug 2023 07:47:27 +0200 Subject: [PATCH 07/26] BAEL-6415: Merged Kafka-3 project into Kafka-2 project --- .../SimpleConsumerWithBootStrapServers.java | 4 +-- apache-kafka-3/pom.xml | 27 ------------------- pom.xml | 2 -- 3 files changed, 2 insertions(+), 31 deletions(-) rename apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java => apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/SimpleConsumerWithBootStrapServers.java (94%) delete mode 100644 apache-kafka-3/pom.xml diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/SimpleConsumerWithBootStrapServers.java similarity index 94% rename from apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java rename to apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/SimpleConsumerWithBootStrapServers.java index bc2eeadb78..7501b40056 100644 --- a/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaJava.java +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/SimpleConsumerWithBootStrapServers.java @@ -1,4 +1,4 @@ -package com.baeldung.kafka; +package com.baeldung.kafka.consumer; import org.apache.kafka.clients.consumer.*; import org.apache.kafka.common.serialization.LongDeserializer; @@ -8,7 +8,7 @@ import java.time.Duration; import java.util.Arrays; import java.util.Properties; -public class KafkaJava { +public class SimpleConsumerWithBootStrapServers { public static void main(String[] args) { try(final Consumer consumer = createConsumer()) { diff --git a/apache-kafka-3/pom.xml b/apache-kafka-3/pom.xml deleted file mode 100644 index 6c4b5284dd..0000000000 --- a/apache-kafka-3/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - apache-kafka-3 - apache-kafka-3 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.apache.kafka - kafka-clients - ${kafka.version} - - - - - 3.5.1 - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index e11395c709..8fb2234a23 100644 --- a/pom.xml +++ b/pom.xml @@ -820,7 +820,6 @@ antlr apache-kafka apache-kafka-2 - apache-kafka-3 apache-olingo apache-poi-2 @@ -1090,7 +1089,6 @@ antlr apache-kafka apache-kafka-2 - apache-kafka-3 apache-olingo apache-poi-2 From ef865442eae4024dc3837b53a9fe53957a5a85b2 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 15 Aug 2023 10:40:32 +0300 Subject: [PATCH 08/26] upgrade core-java-collections-conversions-2 module to jdk 11 --- core-java-modules/core-java-collections-conversions-2/pom.xml | 2 ++ pom.xml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml index 8cd0a6932b..0a30cbeae6 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/pom.xml @@ -43,6 +43,8 @@ 0.10.3 + 11 + 3.1.1 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 17daf26278..0c86a686c5 100644 --- a/pom.xml +++ b/pom.xml @@ -346,7 +346,7 @@ core-java-modules/core-java-serialization core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 - core-java-modules/core-java-collections-conversions-2 + core-java-modules/core-java-streams-2 @@ -524,7 +524,7 @@ core-java-modules/core-java-serialization core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 - core-java-modules/core-java-collections-conversions-2 + core-java-modules/core-java-streams-2 From 7b074ab5c2819163b7be0b3e33b6cd2f87837dd3 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Tue, 15 Aug 2023 11:20:27 +0300 Subject: [PATCH 09/26] JAVA-23695 Article's employee class doesn't exist in module (#14568) Co-authored-by: timis1 --- .../src/main/java/com/baeldung/hibernate/joincolumn/Email.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java index 096faf7984..c25820300e 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -18,7 +18,7 @@ public class Email { private String address; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "employee_id") + @JoinColumn(name = "employee_id", referencedColumnName = "id") private OfficialEmployee employee; public Long getId() { From 1f5590b7b50a1f68da03b8de4a3cb66a298d36d6 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Tue, 15 Aug 2023 11:40:13 +0300 Subject: [PATCH 10/26] JAVA-24054 Upgrade java-enum-values article (#14590) --- core-java-modules/core-java-lang-oop-types/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-types/pom.xml b/core-java-modules/core-java-lang-oop-types/pom.xml index a5b492f5ca..a9909598eb 100644 --- a/core-java-modules/core-java-lang-oop-types/pom.xml +++ b/core-java-modules/core-java-lang-oop-types/pom.xml @@ -27,7 +27,7 @@ - 1.15 + 1.16.0 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 17daf26278..2265114cff 100644 --- a/pom.xml +++ b/pom.xml @@ -1280,7 +1280,7 @@ 4.4 2.11.0 2.6 - 3.12.0 + 3.13.0 1.5.0 3.3.2 4.0.1 From 379992c84e345dbf8505e274046c24193c1f5b37 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Tue, 15 Aug 2023 11:56:05 +0100 Subject: [PATCH 11/26] BAEL-6813: Moved Magic Square code to core-java-lang-math-3 (#14587) * BAEL-6813: Moved Magic Square code to core-java-lang-math-3 * Fix code to work below Java 11 * Fix unrelated broken test --- .../java/com/baeldung/jar/JarAppUnitTest.java | 6 ++- .../magicsquare/GenerationUnitTest.java | 2 +- .../baeldung}/magicsquare/MagicSquare.java | 6 ++- .../magicsquare/ValidationUnitTest.java | 2 +- core-java-modules/core-java-leetcode/pom.xml | 39 ------------------- core-java-modules/pom.xml | 1 - 6 files changed, 11 insertions(+), 45 deletions(-) rename core-java-modules/{core-java-leetcode/src/test/java/com/baeldung/leetcode => core-java-lang-math-3/src/test/java/com/baeldung}/magicsquare/GenerationUnitTest.java (95%) rename core-java-modules/{core-java-leetcode/src/test/java/com/baeldung/leetcode => core-java-lang-math-3/src/test/java/com/baeldung}/magicsquare/MagicSquare.java (96%) rename core-java-modules/{core-java-leetcode/src/test/java/com/baeldung/leetcode => core-java-lang-math-3/src/test/java/com/baeldung}/magicsquare/ValidationUnitTest.java (92%) delete mode 100644 core-java-modules/core-java-leetcode/pom.xml diff --git a/core-java-modules/core-java-jar/src/test/java/com/baeldung/jar/JarAppUnitTest.java b/core-java-modules/core-java-jar/src/test/java/com/baeldung/jar/JarAppUnitTest.java index 707ce79624..fc40aa01c5 100644 --- a/core-java-modules/core-java-jar/src/test/java/com/baeldung/jar/JarAppUnitTest.java +++ b/core-java-modules/core-java-jar/src/test/java/com/baeldung/jar/JarAppUnitTest.java @@ -3,10 +3,14 @@ package com.baeldung.jar; import org.junit.Assert; import org.junit.jupiter.api.Test; +import java.util.regex.Pattern; + public class JarAppUnitTest { @Test public void findClassTest(){ - Assert.assertTrue(JarApp.findObjectMapperClass().endsWith("jackson-databind-2.13.3.jar")); + Pattern databindPattern = Pattern.compile(".*jackson-databind-(\\d)+\\.(\\d)+\\.(\\d)\\.jar$"); + + Assert.assertTrue(databindPattern.matcher(JarApp.findObjectMapperClass()).matches()); } } diff --git a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/GenerationUnitTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/GenerationUnitTest.java similarity index 95% rename from core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/GenerationUnitTest.java rename to core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/GenerationUnitTest.java index 308c655bd1..f02200462e 100644 --- a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/GenerationUnitTest.java +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/GenerationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.leetcode.magicsquare; +package com.baeldung.magicsquare; import org.junit.jupiter.api.Test; diff --git a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/MagicSquare.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java similarity index 96% rename from core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/MagicSquare.java rename to core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java index 5e16f2e0db..b6e7ac24f5 100644 --- a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/MagicSquare.java +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/MagicSquare.java @@ -1,4 +1,4 @@ -package com.baeldung.leetcode.magicsquare; +package com.baeldung.magicsquare; import org.junit.platform.commons.util.StringUtils; @@ -172,7 +172,9 @@ public class MagicSquare { int value = getCell(x, y); if (value == 0) { sb.append(" "); - sb.append(".".repeat(largestNumberLength)); + for (int i = 0; i < largestNumberLength; ++i) { + sb.append("."); + } sb.append(" "); } else { sb.append(String.format(formatString, value)); diff --git a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/ValidationUnitTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/ValidationUnitTest.java similarity index 92% rename from core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/ValidationUnitTest.java rename to core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/ValidationUnitTest.java index 93f36931e6..6b0ec600bb 100644 --- a/core-java-modules/core-java-leetcode/src/test/java/com/baeldung/leetcode/magicsquare/ValidationUnitTest.java +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/magicsquare/ValidationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.leetcode.magicsquare; +package com.baeldung.magicsquare; import org.junit.jupiter.api.Test; diff --git a/core-java-modules/core-java-leetcode/pom.xml b/core-java-modules/core-java-leetcode/pom.xml deleted file mode 100644 index eb91308c64..0000000000 --- a/core-java-modules/core-java-leetcode/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - core-java-leetcode - core-java-leetcode - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../pom.xml - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - - - - - - - 11 - 11 - - - diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index a6f0382186..e9bb86e500 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -108,7 +108,6 @@ core-java-lang-operators-2 core-java-lang-syntax core-java-lang-syntax-2 - core-java-leetcode core-java-locale core-java-networking core-java-networking-2 From 06f473f5e6d815459190650077e26c805541c56d Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 15 Aug 2023 16:27:23 +0530 Subject: [PATCH 12/26] =?UTF-8?q?JAVA-15019:=20changes=20made=20for=20upda?= =?UTF-8?q?grading=20Advanced=20Apache=20HttpClient=20C=E2=80=A6=20(#14499?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...tAdvancedConfigurationIntegrationTest.java | 65 ++++--- ...tAdvancedConfigurationIntegrationTest.java | 161 ++++++++++++++++++ 2 files changed, 193 insertions(+), 33 deletions(-) create mode 100644 apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index 2235d0e9d0..3f2c1328e8 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -1,29 +1,5 @@ package com.baeldung.httpclient.advancedconfig; - -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.junit.Rule; -import org.junit.Test; - -import java.io.IOException; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; @@ -34,6 +10,30 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; +import java.io.IOException; + +import org.apache.hc.client5.http.auth.AuthCache; +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.CredentialsProvider; +import org.apache.hc.client5.http.auth.StandardAuthScheme; +import org.apache.hc.client5.http.classic.HttpClient; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.impl.auth.BasicAuthCache; +import org.apache.hc.client5.http.impl.auth.BasicScheme; +import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.junit.Rule; +import org.junit.Test; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + public class HttpClientAdvancedConfigurationIntegrationTest { @Rule @@ -59,7 +59,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpGet); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(response.getCode(), 200); } @Test @@ -82,7 +82,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpPost); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(response.getCode(), 200); } @@ -107,7 +107,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpclient.execute(httpGet); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(response.getCode(), 200); proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } @@ -125,14 +125,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest { DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); // Client credentials - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope(proxy), - new UsernamePasswordCredentials("username_admin", "secret_password")); - + CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create() + .add(new AuthScope(proxy), "username_admin", "secret_password".toCharArray()) + .build(); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); - // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(proxy, basicAuth); @@ -149,10 +147,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //when final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + httpGet.setHeader("Authorization", StandardAuthScheme.BASIC); HttpResponse response = httpclient.execute(httpGet, context); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(response.getCode(), 200); proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java new file mode 100644 index 0000000000..2235d0e9d0 --- /dev/null +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -0,0 +1,161 @@ +package com.baeldung.httpclient.advancedconfig; + + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.DefaultProxyRoutePlanner; +import org.junit.Rule; +import org.junit.Test; + +import java.io.IOException; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.junit.Assert.assertEquals; + +public class HttpClientAdvancedConfigurationIntegrationTest { + + @Rule + public WireMockRule serviceMock = new WireMockRule(8089); + + @Rule + public WireMockRule proxyMock = new WireMockRule(8090); + + @Test + public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { + //given + String userAgent = "BaeldungAgent/1.0"; + serviceMock.stubFor(get(urlEqualTo("/detail")) + .withHeader("User-Agent", equalTo(userAgent)) + .willReturn(aResponse() + .withStatus(200))); + + HttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); + httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent); + + //when + HttpResponse response = httpClient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + } + + @Test + public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { + //given + String xmlBody = "1"; + serviceMock.stubFor(post(urlEqualTo("/person")) + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo(xmlBody)) + .willReturn(aResponse() + .withStatus(200))); + + HttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost("http://localhost:8089/person"); + httpPost.setHeader("Content-Type", "application/xml"); + StringEntity xmlEntity = new StringEntity(xmlBody); + httpPost.setEntity(xmlEntity); + + //when + HttpResponse response = httpClient.execute(httpPost); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + + } + + @Test + public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { + //given + proxyMock.stubFor(get(urlMatching(".*")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + + serviceMock.stubFor(get(urlEqualTo("/private")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .build(); + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); + } + + @Test + public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { + //given + proxyMock.stubFor(get(urlMatching("/private")) + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + serviceMock.stubFor(get(urlEqualTo("/private")) + .willReturn(aResponse().withStatus(200))); + + + HttpHost proxy = new HttpHost("localhost", 8090); + DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + + // Client credentials + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope(proxy), + new UsernamePasswordCredentials("username_admin", "secret_password")); + + + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + + // Generate BASIC scheme object and add it to the local auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(proxy, basicAuth); + HttpClientContext context = HttpClientContext.create(); + context.setCredentialsProvider(credentialsProvider); + context.setAuthCache(authCache); + + + HttpClient httpclient = HttpClients.custom() + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); + + + //when + final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); + HttpResponse response = httpclient.execute(httpGet, context); + + //then + assertEquals(response.getStatusLine().getStatusCode(), 200); + proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); + serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); + } + + +} From 674b3d34535725d1fc7b18a1a1ca7a8585f89448 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Tue, 15 Aug 2023 22:47:51 +0530 Subject: [PATCH 13/26] BAEL-6801, Applied review comments (#14567) * BAEL-6801 Validate string length with Java validation annotations * Bael-6801, applied Review comments * Bael-6801, applied Review comments, deleting the springboot implementation --- .../javaxval/listvalidation/AllLevels.java | 4 + .../javaxval/listvalidation}/JobAspirant.java | 44 +-- .../javaxval/listvalidation/Junior.java | 4 + .../javaxval/listvalidation/MidSenior.java | 4 + .../javaxval/listvalidation/Senior.java | 4 + .../listvalidation/JobAspirantUnitTest.java | 209 +++++++++++++ .../SpringJobApplicationDemoApp.java | 12 - .../controller/ApplyJobController.java | 49 --- .../listvalidation/groups/AllLevels.java | 4 - .../listvalidation/groups/Junior.java | 4 - .../listvalidation/groups/MidSenior.java | 4 - .../listvalidation/groups/Senior.java | 4 - .../ApplyJobControllerIntegrationTest.java | 289 ------------------ 13 files changed, 241 insertions(+), 394 deletions(-) create mode 100644 javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/AllLevels.java rename {spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/domain => javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation}/JobAspirant.java (79%) create mode 100644 javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Junior.java create mode 100644 javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/MidSenior.java create mode 100644 javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Senior.java create mode 100644 javaxval-2/src/test/java/com/baeldung/javaxval/listvalidation/JobAspirantUnitTest.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/SpringJobApplicationDemoApp.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/controller/ApplyJobController.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/AllLevels.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Junior.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/MidSenior.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Senior.java delete mode 100644 spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/listvalidation/application/ApplyJobControllerIntegrationTest.java diff --git a/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/AllLevels.java b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/AllLevels.java new file mode 100644 index 0000000000..b6660c225a --- /dev/null +++ b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/AllLevels.java @@ -0,0 +1,4 @@ +package com.baeldung.javaxval.listvalidation; + +public interface AllLevels { +} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/domain/JobAspirant.java b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/JobAspirant.java similarity index 79% rename from spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/domain/JobAspirant.java rename to javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/JobAspirant.java index 4191625b4f..31c8d69639 100644 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/domain/JobAspirant.java +++ b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/JobAspirant.java @@ -1,12 +1,7 @@ -package com.baeldung.listvalidation.domain; +package com.baeldung.javaxval.listvalidation; -import com.baeldung.listvalidation.groups.AllLevels; -import com.baeldung.listvalidation.groups.Junior; -import com.baeldung.listvalidation.groups.MidSenior; -import com.baeldung.listvalidation.groups.Senior; -import org.springframework.lang.Nullable; +import jakarta.validation.constraints.*; -import javax.validation.constraints.*; import java.util.Date; public class JobAspirant { @@ -14,7 +9,6 @@ public class JobAspirant { @Size(min = 5, message = "Name should have at least 5 characters", groups = AllLevels.class), @Size(max = 20, message = "Name should have at most 20 characters", groups = AllLevels.class) }) - @Pattern.List({ @Pattern(regexp = "^[\\p{Alpha} ]*$", message = "Name should contain only alphabets and space", groups = AllLevels.class), @Pattern(regexp = "^[^\\s].*$", message = "Name should not start with space", groups = AllLevels.class), @@ -22,18 +16,8 @@ public class JobAspirant { @Pattern(regexp = "^((?! ).)*$", message = "Name should not contain consecutive spaces", groups = AllLevels.class), @Pattern(regexp = "^[^a-z].*$", message = "Name should not start with a lower case character", groups = AllLevels.class) }) - - private String name; - public Integer getExperience() { - return experience; - } - - public void setExperience(Integer experience) { - this.experience = experience; - } - @Min.List({ @Min(value = 15, message = "Years of experience cannot be less than 15 Years", groups = Senior.class), @Min(value = 10, message = "Years of experience cannot be less than 10 Years", groups = MidSenior.class), @@ -47,18 +31,16 @@ public class JobAspirant { private Integer experience; @AssertTrue.List({ - @AssertTrue(message = "Terms and Conditions consent missing for Senior Level Job Application", groups = Senior.class), - @AssertTrue(message = "Terms and Conditions consent missing for Mid-Senior Level Job Application", groups = MidSenior.class), - @AssertTrue(message = "Terms and Conditions consent missing for Junior Level Job Application", groups = Junior.class) + @AssertTrue(message = "Terms and Conditions consent missing for Senior Level Job", groups = Senior.class), + @AssertTrue(message = "Terms and Conditions consent missing for Mid-Senior Level Job", groups = MidSenior.class), + @AssertTrue(message = "Terms and Conditions consent missing for Junior Level Job", groups = Junior.class) }) - @Nullable private Boolean agreement; - @Nullable @Future.List({ - @Future(message = "Active passport is mandatory for Senior Level Job Application", groups = Senior.class), - @Future(message = "Active passport is mandatory for Mid-Senior Level Job Application", groups = MidSenior.class), - @Future(message = "Active passport is mandatory for Junior Level Job Application", groups = Junior.class) + @Future(message = "Active passport is mandatory for Senior Level Job", groups = Senior.class), + @Future(message = "Active passport is mandatory for Mid-Senior Level Job", groups = MidSenior.class), + @Future(message = "Active passport is mandatory for Junior Level Job", groups = Junior.class) }) private Date passportExpiryDate; @@ -70,8 +52,6 @@ public class JobAspirant { @Pattern(regexp = "^(Junior)$", message = "Job level should be Junior" ,flags = Pattern.Flag.CASE_INSENSITIVE, groups = Junior.class) }) -// @Pattern(regexp = "^(Senior|MidSenior|Junior)$", message = "Job level should be Senior, MidSenior or Junior" -// ,flags = Pattern.Flag.CASE_INSENSITIVE, groups = AllLevels.class) private String jobLevel; public String getJobLevel() { @@ -104,4 +84,12 @@ public class JobAspirant { public void setPassportExpiryDate(Date passportExpiryDate) { this.passportExpiryDate = passportExpiryDate; } + + public Integer getExperience() { + return experience; + } + + public void setExperience(Integer experience) { + this.experience = experience; + } } diff --git a/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Junior.java b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Junior.java new file mode 100644 index 0000000000..e881f4d6cd --- /dev/null +++ b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Junior.java @@ -0,0 +1,4 @@ +package com.baeldung.javaxval.listvalidation; + +public interface Junior { +} diff --git a/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/MidSenior.java b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/MidSenior.java new file mode 100644 index 0000000000..f3a6bb67f8 --- /dev/null +++ b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/MidSenior.java @@ -0,0 +1,4 @@ +package com.baeldung.javaxval.listvalidation; + +public interface MidSenior { +} diff --git a/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Senior.java b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Senior.java new file mode 100644 index 0000000000..be3cf00d9c --- /dev/null +++ b/javaxval-2/src/main/java/com/baeldung/javaxval/listvalidation/Senior.java @@ -0,0 +1,4 @@ +package com.baeldung.javaxval.listvalidation; + +public interface Senior { +} diff --git a/javaxval-2/src/test/java/com/baeldung/javaxval/listvalidation/JobAspirantUnitTest.java b/javaxval-2/src/test/java/com/baeldung/javaxval/listvalidation/JobAspirantUnitTest.java new file mode 100644 index 0000000000..cee020c69f --- /dev/null +++ b/javaxval-2/src/test/java/com/baeldung/javaxval/listvalidation/JobAspirantUnitTest.java @@ -0,0 +1,209 @@ +package com.baeldung.javaxval.listvalidation; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JobAspirantUnitTest { + private static Validator validator; + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + @Test + public void givenJobLevelJunior_whenInValidMinExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 3, true); + Set> violations = validator.validate(jobAspirant, Junior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 5 Years"); + }); + } + @Test + public void givenJobLevelMidSenior_whenInvalidMinExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 8, true); + Set> violations = validator.validate(jobAspirant, MidSenior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 10 Years"); + }); + } + @Test + public void givenJobLevelSenior_whenInvalidMinExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 13, true); + Set> violations = validator.validate(jobAspirant, Senior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 15 Years"); + }); + } + @Test + public void givenJobLevelJunior_whenInValidMaxExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 11, true); + Set> violations = validator.validate(jobAspirant, Junior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 10 Years"); + }); + } + @Test + public void givenJobLevelMidSenior_whenInvalidMaxExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 16, true); + Set> violations = validator.validate(jobAspirant, MidSenior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 15 Years"); + }); + } + @Test + public void givenJobLevelSenior_whenInvalidMaxExperience_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 23, true); + Set> violations = validator.validate(jobAspirant, Senior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("experience"); + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 20 Years"); + }); + } + @Test + public void whenInvalidName_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, true); + Set> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("name"); + assertThat(action.getMessage()).isEqualTo("Name should not contain consecutive spaces"); + }); + } + @Test + public void givenJuniorLevel_whenInvalidAgreement_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 7, false); + Set> violations = validator.validate(jobAspirant, Junior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("agreement"); + assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Junior Level Job"); + }); + } + @Test + public void givenSeniorLevel_whenInvalidAgreement_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, false); + Set> violations = validator.validate(jobAspirant, Senior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("agreement"); + assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Senior Level Job"); + }); + } + @Test + public void givenJobLevelMidSenior_whenInvalidPassport_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2021-12-31", 12, true); + Set> violations = validator.validate(jobAspirant, MidSenior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("passportExpiryDate"); + assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Mid-Senior Level Job"); + }); + } + @Test + public void givenJobLevelSenior_whenInvalidPassport_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2021-12-31", 18, true); + Set> violations = validator.validate(jobAspirant, Senior.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getPropertyPath().toString()).isEqualTo("passportExpiryDate"); + assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Senior Level Job"); + }); + } + @Test + public void givenJobLevelSenior_whenAllFieldsValid_thenNoErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, true); + Set> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(0); + } + @Test + public void givenJobLevelMidSenior_whenAllFieldsValid_thenNoErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 12, true); + Set> violations = validator.validate(jobAspirant, MidSenior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(0); + } + @Test + public void givenJobLevelJunior_whenAllFieldsValid_thenNoErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 7, true); + Set> violations = validator.validate(jobAspirant, Junior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(0); + } + @Test + public void givenJobLevelJunior_whenAllFieldsInValid_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Junior", " John Adam", "2022-12-31", 3, false); + Set> violations = validator.validate(jobAspirant, Junior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(4); + violations.forEach(action -> { + String fieldName = action.getPropertyPath().toString(); + switch(fieldName) { + case "name": + assertThat(action.getMessage()).isEqualTo("Name should not start with space"); + break; + case "passportExpiryDate": + assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Junior Level Job"); + break; + case "experience": + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 5 Years"); + break; + case "agreement": + assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Junior Level Job"); + break; + } + }); + } + @Test + public void givenJobLevelSenior_whenAllFieldsInValid_thenExpectErrors() throws ParseException { + JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam ", "2022-12-31", 12, false); + Set> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class); + assertThat(violations.size()).isEqualTo(4); + violations.forEach(action -> { + String fieldName = action.getPropertyPath().toString(); + switch(fieldName) { + case "name": + assertThat(action.getMessage()).isEqualTo("Name should not end with space"); + break; + case "passportExpiryDate": + assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Senior Level Job"); + break; + case "experience": + assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 15 Years"); + break; + case "agreement": + assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Senior Level Job"); + break; + } + }); + } + private JobAspirant getJobAspirant(String jobLevel, String name, String passportExpDate, int exp, boolean agmt) throws ParseException { + JobAspirant jobAspirant = new JobAspirant(); + jobAspirant.setName(name); + jobAspirant.setPassportExpiryDate(convertStringToDate(passportExpDate)); + jobAspirant.setJobLevel(jobLevel); + jobAspirant.setExperience(exp); + jobAspirant.setAgreement(agmt); + return jobAspirant; + } + private Date convertStringToDate(String date) throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + return formatter.parse(date); + } +} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/SpringJobApplicationDemoApp.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/SpringJobApplicationDemoApp.java deleted file mode 100644 index a7967c73cb..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/SpringJobApplicationDemoApp.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.listvalidation; - - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringJobApplicationDemoApp { - public static void main(String[] args) { - SpringApplication.run(SpringJobApplicationDemoApp.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/controller/ApplyJobController.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/controller/ApplyJobController.java deleted file mode 100644 index e3877f09b0..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/controller/ApplyJobController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.listvalidation.controller; - -import com.baeldung.listvalidation.domain.JobAspirant; -import com.baeldung.listvalidation.groups.AllLevels; -import com.baeldung.listvalidation.groups.Junior; -import com.baeldung.listvalidation.groups.MidSenior; -import com.baeldung.listvalidation.groups.Senior; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.validation.FieldError; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.*; - -import java.util.HashMap; -import java.util.Map; - -@RestController -public class ApplyJobController { - @PostMapping("/applyLevelJunior") - public ResponseEntity applyLevelJunior(@Validated({Junior.class, AllLevels.class}) @RequestBody JobAspirant user) { - - return ResponseEntity.ok("Application submitted successfully"); - } - - @PostMapping("/applyLevelMidSenior") - public ResponseEntity applyLevelMidSenior(@Validated({MidSenior.class, AllLevels.class}) @RequestBody JobAspirant user) { - - return ResponseEntity.ok("Application submitted successfully"); - } - - @PostMapping("/applyLevelSenior") - public ResponseEntity applyLevelSenior(@Validated({Senior.class, AllLevels.class}) @RequestBody JobAspirant user) { - - return ResponseEntity.ok("Application submitted successfully"); - } - - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(MethodArgumentNotValidException.class) - public Map handleValidationExceptions(MethodArgumentNotValidException ex) { - Map errors = new HashMap<>(); - ex.getBindingResult().getAllErrors().forEach((error) -> { - String fieldName = ((FieldError) error).getField(); - String errorMessage = error.getDefaultMessage(); - errors.put(fieldName, errorMessage); - }); - return errors; - } -} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/AllLevels.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/AllLevels.java deleted file mode 100644 index 8e3f8cc7ef..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/AllLevels.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.listvalidation.groups; - -public interface AllLevels { -} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Junior.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Junior.java deleted file mode 100644 index 8aca819f18..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Junior.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.listvalidation.groups; - -public interface Junior { -} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/MidSenior.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/MidSenior.java deleted file mode 100644 index ddea95f5e2..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/MidSenior.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.listvalidation.groups; - -public interface MidSenior { -} diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Senior.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Senior.java deleted file mode 100644 index d09d3ea5d5..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/listvalidation/groups/Senior.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.listvalidation.groups; - -public interface Senior { -} diff --git a/spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/listvalidation/application/ApplyJobControllerIntegrationTest.java b/spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/listvalidation/application/ApplyJobControllerIntegrationTest.java deleted file mode 100644 index 978110633c..0000000000 --- a/spring-boot-modules/spring-boot-validation/src/test/java/com/baeldung/listvalidation/application/ApplyJobControllerIntegrationTest.java +++ /dev/null @@ -1,289 +0,0 @@ -package com.baeldung.listvalidation.application; - - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -import java.nio.charset.StandardCharsets; -import java.util.Map; - -@RunWith(SpringRunner.class) -@WebMvcTest -@AutoConfigureMockMvc -public class ApplyJobControllerIntegrationTest { - - @Autowired - private MockMvc mockMvc; - private static final String[] CORRECT_PASSPORT_EXPIRY_DATES = {"2025-01-01", "2026-02-29", "2024-03-31"}; - private static final String[] INCORRECT_PASSPORT_EXPIRY_DATES = {"2020-01-01", "2021-02-29", "2022-03-31"}; - - private static final Map MAP_OF_JOB_LEVEL_TO_PASSPORT_ERRMSG = Map.of( - "Junior", "Active passport is mandatory for Junior Level Job Application" - , "MidSenior", "Active passport is mandatory for Mid-Senior Level Job Application" - , "Senior", "Active passport is mandatory for Senior Level Job Application" - ); - private static final Map MAP_OF_JOB_LEVEL_TO_AGREEMENT_ERRMSG = Map.of( - "Junior", "Terms and Conditions consent missing for Junior Level Job Application" - , "MidSenior", "Terms and Conditions consent missing for Mid-Senior Level Job Application" - , "Senior", "Terms and Conditions consent missing for Senior Level Job Application" - ); - private static final String[] USERS_INCORRECT_NAMES = {"Bob", "bob Marley", "Bob John Federik Marley", "Bob M@rley" - , " Bob Marley", "Bob Marley ", "Bob Marley"}; - - private static final String[] USERS_CORRECT_NAMES = {"Bob Marley", "Bob John Marley", "Bobby"}; - - private static final Map MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES = Map.of( - "Junior", new String[]{"1", "2", "3", "4"} - , "MidSenior", new String[]{"6", "7", "8", "9"} - , "Senior", new String[]{"11", "12", "13", "14"} - ); - private static final Map MAP_OF_JOBLEVEL_TO_MIN_ERRMSG = Map.of( - "Junior", "Years of experience cannot be less than 5 Years" - , "MidSenior", "Years of experience cannot be less than 10 Years" - , "Senior", "Years of experience cannot be less than 15 Years" - ); - private static final Map MAP_OF_JOBLEVEL_TO_MAX_ERRMSG = Map.of( - "Junior", "Years of experience cannot be more than 10 Years" - , "MidSenior", "Years of experience cannot be more than 15 Years" - , "Senior", "Years of experience cannot be more than 20 Years" - ); - private static final Map MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES = Map.of( - "Junior", new String[]{"11", "14", "20", "30"} - , "MidSenior", new String[]{"16", "20", "25", "40"} - , "Senior", new String[]{"21", "25", "30", "35"} - ); - private static final Map MAP_OF_INCORRECT_NAMES_TO_ERRMSG = Map.of( - "Bob", "Name should have at least 5 characters" - , "bob Marley", "Name should not start with a lower case character" - , "Bob John Federik Marley", "Name should have at most 20 characters" - , "Bob M@rley", "Name should contain only alphabets and space" - , " Bob Marley", "Name should not start with space" - , "Bob Marley ", "Name should not end with space" - , "Bob Marley", "Name should not contain consecutive spaces" - ); - - private static final Map MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES = Map.of( - "Junior", new String[]{"6", "7", "8", "9", "10"} - , "MidSenior", new String[]{"11", "12", "13", "14", "15"} - , "Senior", new String[]{"16", "17", "18", "19", "20"} - ); - - - private static String[] USERS_VALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS = null; - private static String[] USERS_VALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS = null; - private static String[] USERS_INVALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS = null; - private static String[] USERS_INVALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS = null; - private static String[] USERS_ALL_FIELDS_VALID_EXCEPT_FOR_PSPT_AND_AGMT_JSONS = null; - private static String[] USERS_ALL_FIELDS_VALID_JSONS = null; - - @Before - public void prepareAllValidFieldsExceptForPsptAndAgmt() { - USERS_ALL_FIELDS_VALID_EXCEPT_FOR_PSPT_AND_AGMT_JSONS = new String[USERS_CORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.size() * 5 * INCORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_CORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : INCORRECT_PASSPORT_EXPIRY_DATES) { - USERS_ALL_FIELDS_VALID_EXCEPT_FOR_PSPT_AND_AGMT_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + false + "\"}"; - } - } - } - } - - } - @Before - public void prepareUserWithAllFieldsValid() { - USERS_ALL_FIELDS_VALID_JSONS = new String[USERS_CORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.size() * 5 * CORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_CORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_CORRECT_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : CORRECT_PASSPORT_EXPIRY_DATES) { - USERS_ALL_FIELDS_VALID_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + true + "\"}"; - } - } - } - } - } - @Before - public void prepareUsersInvalidNamesInValidMaxExpValidPassportValidAgreementJsons() { - USERS_INVALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS = new String[USERS_INCORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.size() * 4 * CORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_INCORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : CORRECT_PASSPORT_EXPIRY_DATES) { - USERS_INVALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + true + "\"}"; - } - } - } - } - } - @Before - public void prepareUsersCorrectNamesIncorrectMinExpJsons() { - USERS_VALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS = new String[USERS_CORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.size() * 4 * CORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_CORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : CORRECT_PASSPORT_EXPIRY_DATES) { - USERS_VALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + true + "\"}"; - } - } - } - } - } - @Before - public void prepareUsersIncorrectNamesIncorrectMinExpJsons() { - USERS_INVALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS = new String[USERS_INCORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.size() * 4 * CORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_INCORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_INCORRECT_MIN_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : CORRECT_PASSPORT_EXPIRY_DATES) { - USERS_INVALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + true + "\"}"; - } - } - } - } - } - @Before - public void prepareUsersCorrectNamesIncorrectMaxExpJsons() { - USERS_VALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS = new String[USERS_CORRECT_NAMES.length - * MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.size() * 4 * CORRECT_PASSPORT_EXPIRY_DATES.length]; - int i = 0; - for (String user : USERS_CORRECT_NAMES) { - for (String jobLevel : MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.keySet()) { - for (String experience : MAP_OF_JOBLEVEL_TO_INCORRECT_MAX_EXPERIENCES.get(jobLevel)) { - for (String passportExpiryDate : CORRECT_PASSPORT_EXPIRY_DATES) { - USERS_VALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS[i++] = "{\"name\": \"" + user - + "\", \"experience\": \"" + experience + "\", \"jobLevel\": \"" + jobLevel - + "\", \"passportExpiryDate\": \"" + passportExpiryDate - + "\", \"agreement\": \"" + true + "\"}"; - } - } - } - } - } - @Test - public void whenAllFieldsValidExceptForPsptAndAgmt_thenBadRequestResponse() throws Exception { - String[] users = USERS_ALL_FIELDS_VALID_EXCEPT_FOR_PSPT_AND_AGMT_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.content() - .json("{\"agreement\":\"" + MAP_OF_JOB_LEVEL_TO_AGREEMENT_ERRMSG.get(jobLevel) - + "\",\"passportExpiryDate\":\"" + MAP_OF_JOB_LEVEL_TO_PASSPORT_ERRMSG.get(jobLevel) + "\"}")); - } - } - @Test - public void whenUserWithAllFieldsValid_thenCorrectResponse() throws Exception { - MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8); - String[] users = USERS_ALL_FIELDS_VALID_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8)) - .andExpect(MockMvcResultMatchers.content().string("Application submitted successfully")); - } - } - @Test - public void whenValidUserNamesInValidMaxExpValidPsptValidAgmt_thenBadRequestResponse() throws Exception { - String[] users = USERS_VALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.content() - .json("{\"experience\":\"" + MAP_OF_JOBLEVEL_TO_MAX_ERRMSG.get(jobLevel) - + "\"}")); - } - } - @Test - public void whenInvalidUserNamesInValidMaxExpValidPsptValidAgmt_thenBadRequestResponse() throws Exception { - String[] users = USERS_INVALID_NAMES_INVALID_MAXEXP_VALIDPSPT_VALIDAGMT_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - String name = jsonObject.getString("name"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.content() - .json("{\"name\":\"" + MAP_OF_INCORRECT_NAMES_TO_ERRMSG.get(name) - + "\",\"experience\":\"" + MAP_OF_JOBLEVEL_TO_MAX_ERRMSG.get(jobLevel) + "\"}")); - } - } - @Test - public void whenValidUserNamesInValidMinExpValidPsptValidAgmt_thenBadRequestResponse() throws Exception { - String[] users = USERS_VALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.content() - .json("{\"experience\":\"" + MAP_OF_JOBLEVEL_TO_MIN_ERRMSG.get(jobLevel) + "\"}")); - } - } - @Test - public void whenInValidUserNamesInValidMinExpValidPsptValidAgmt_thenBadRequestResponse() throws Exception { - String[] users = USERS_INVALID_NAMES_INVALID_MINEXP_VALIDPSPT_VALIDAGMT_JSONS; - for (String user : users) { - JSONObject jsonObject = new JSONObject(user); - String jobLevel = jsonObject.getString("jobLevel"); - String name = jsonObject.getString("name"); - mockMvc.perform(MockMvcRequestBuilders.post("/applyLevel" + jobLevel) - .content(user) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isBadRequest()) - .andExpect(MockMvcResultMatchers.content() - .json("{\"name\":\"" + MAP_OF_INCORRECT_NAMES_TO_ERRMSG.get(name) - + "\",\"experience\":\"" + MAP_OF_JOBLEVEL_TO_MIN_ERRMSG.get(jobLevel) + "\"}")); - } - } -} From 1d0afe4f07c1e823166102379b0ff4cf3c2f0227 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 16 Aug 2023 02:40:47 +0200 Subject: [PATCH 14/26] Convert an ArrayList of String to a String Array in Java (#14583) * Convert an ArrayList of String to a String Array in Java * fixing typo * module moving --- .../core-java-arrays-convert/pom.xml | 1 - .../pom.xml | 3 +- .../ArrayListToArrayUnitTest.java | 46 +++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayListToArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml index c90b60e09a..480e1b3f07 100644 --- a/core-java-modules/core-java-arrays-convert/pom.xml +++ b/core-java-modules/core-java-arrays-convert/pom.xml @@ -20,5 +20,4 @@ ${commons-lang3.version} - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml index 0a30cbeae6..7b7533fc39 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/pom.xml @@ -44,7 +44,6 @@ 0.10.3 11 - 3.1.1 + 3.1.1 - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayListToArrayUnitTest.java b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayListToArrayUnitTest.java new file mode 100644 index 0000000000..63cdf22f3a --- /dev/null +++ b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayListToArrayUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.arrayconversion; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class ArrayListToArrayUnitTest { + private static final List INPUT_LIST = Lists.newArrayList("Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply"); + private static final String[] EXPECTED_ARRAY = new String[] { "Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply" }; + + @Test + void whenUsingForLoop_thenGetExpectedResult() { + String[] result = new String[INPUT_LIST.size()]; + for (int i = 0; i < INPUT_LIST.size(); i++) { + result[i] = INPUT_LIST.get(i); + } + assertArrayEquals(EXPECTED_ARRAY, result); + } + + @Test + void whenUsingListToArray_thenGetExpectedResult() { + String[] result = new String[INPUT_LIST.size()]; + INPUT_LIST.toArray(result); + assertArrayEquals(EXPECTED_ARRAY, result); + + String[] result2 = INPUT_LIST.toArray(new String[0]); + assertArrayEquals(EXPECTED_ARRAY, result2); + } + + @Test + void whenUsingStreamApi_thenGetExpectedResult() { + String[] result = INPUT_LIST.stream() + .toArray(String[]::new); + assertArrayEquals(EXPECTED_ARRAY, result); + } + + @Test + void whenUsingListToArrayInJava11_thenGetExpectedResult() { + String[] result = INPUT_LIST.toArray(String[]::new); + assertArrayEquals(EXPECTED_ARRAY, result); + } +} \ No newline at end of file From dc524b75e7b246731dfc99dd2e78349bc44cf609 Mon Sep 17 00:00:00 2001 From: GaetanoPiazzolla Date: Wed, 16 Aug 2023 13:22:04 +0200 Subject: [PATCH 15/26] JAVA-24009 | re-added spring-native to list of modules --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1c2dd0dc06..e37a11f0d9 100644 --- a/pom.xml +++ b/pom.xml @@ -1180,7 +1180,7 @@ spring-kafka - + spring-native spring-security-modules spring-protobuf spring-quartz From c11dc3a6ac32e70bc91fdff316a3189f20cfeda8 Mon Sep 17 00:00:00 2001 From: kasramp Date: Wed, 16 Aug 2023 18:05:37 +0200 Subject: [PATCH 16/26] JAVA-23441 fix small typo --- parent-boot-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-3/README.md b/parent-boot-3/README.md index 738d97bdfd..d0b11d44d8 100644 --- a/parent-boot-3/README.md +++ b/parent-boot-3/README.md @@ -1,3 +1,3 @@ -## Parent Boot 2 +## Parent Boot 3 This is a parent module for all projects using Spring Boot 3. From 4551a5413e7588bb0462be76fc0c79f9e7d45df6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kingsley=E2=9C=A8?= <64941442+KingsleyAmankwah@users.noreply.github.com> Date: Wed, 16 Aug 2023 16:38:36 +0000 Subject: [PATCH 17/26] XSLT Processing In Java (#14507) * Jaxb vs Jaxp * apache libraries added to profile * XSLT processing in Java * XSLT Processing In Java * XSLT Processing modified * XSLT Processing modified * XSLT Processing * pom clean up * ReadMe clean up * pom clean up * Clean up --- apache-libraries-2/README.md | 0 apache-libraries-2/pom.xml | 29 ++++++++++++ .../java/com/baeldung/xslt/XSLTProcessor.java | 18 +++++++ .../resources/avroHttpRequest-schema.avsc | 47 +++++++++++++++++++ .../src/main/resources/log4j2.xml | 18 +++++++ .../src/main/resources/logback.xml | 13 +++++ .../baeldung/xslt/XSLTProcessorUnitTest.java | 29 ++++++++++++ .../src/test/resources/input.xml | 11 +++++ .../src/test/resources/output.html | 3 ++ .../src/test/resources/stylesheet.xslt | 22 +++++++++ pom.xml | 2 + 11 files changed, 192 insertions(+) create mode 100644 apache-libraries-2/README.md create mode 100644 apache-libraries-2/pom.xml create mode 100644 apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java create mode 100644 apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc create mode 100644 apache-libraries-2/src/main/resources/log4j2.xml create mode 100644 apache-libraries-2/src/main/resources/logback.xml create mode 100644 apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java create mode 100644 apache-libraries-2/src/test/resources/input.xml create mode 100644 apache-libraries-2/src/test/resources/output.html create mode 100644 apache-libraries-2/src/test/resources/stylesheet.xslt diff --git a/apache-libraries-2/README.md b/apache-libraries-2/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apache-libraries-2/pom.xml b/apache-libraries-2/pom.xml new file mode 100644 index 0000000000..618ff4a188 --- /dev/null +++ b/apache-libraries-2/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + apache-libraries-2 + 0.0.1-SNAPSHOT + apache-libraries-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax.validation + validation-api + ${javax.validation.validation-api.version} + + + + + + 2.0.1.Final + + + \ No newline at end of file diff --git a/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java b/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java new file mode 100644 index 0000000000..6bc0023485 --- /dev/null +++ b/apache-libraries-2/src/main/java/com/baeldung/xslt/XSLTProcessor.java @@ -0,0 +1,18 @@ +package com.baeldung.xslt; + +import javax.xml.transform.*; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import java.io.File; + +public class XSLTProcessor { + public static void transformXMLUsingXSLT(String inputXMLPath, String xsltPath, String outputHTMLPath) throws TransformerException { + Source xmlSource = new StreamSource(new File(inputXMLPath)); + Source xsltSource = new StreamSource(new File(xsltPath)); + Result output = new StreamResult(new File(outputHTMLPath)); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(xsltSource); + transformer.transform(xmlSource, output); + } +} diff --git a/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc b/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc new file mode 100644 index 0000000000..18179a9cde --- /dev/null +++ b/apache-libraries-2/src/main/resources/avroHttpRequest-schema.avsc @@ -0,0 +1,47 @@ +{ + "type":"record", + "name":"AvroHttpRequest", + "namespace":"com.baeldung.avro.model", + "fields":[ + { + "name":"requestTime", + "type":"long" + }, + { + "name":"clientIdentifier", + "type":{ + "type":"record", + "name":"ClientIdentifier", + "fields":[ + { + "name":"hostName", + "type":"string" + }, + { + "name":"ipAddress", + "type":"string" + } + ] + } + }, + { + "name":"employeeNames", + "type":{ + "type":"array", + "items":"string" + }, + "default":null + }, + { + "name":"active", + "type":{ + "type":"enum", + "name":"Active", + "symbols":[ + "YES", + "NO" + ] + } + } + ] +} \ No newline at end of file diff --git a/apache-libraries-2/src/main/resources/log4j2.xml b/apache-libraries-2/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..d1ea5173fa --- /dev/null +++ b/apache-libraries-2/src/main/resources/log4j2.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/apache-libraries-2/src/main/resources/logback.xml b/apache-libraries-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-libraries-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java b/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java new file mode 100644 index 0000000000..cbfbf78c87 --- /dev/null +++ b/apache-libraries-2/src/test/java/com/baeldung/xslt/XSLTProcessorUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.xslt; + +import org.junit.jupiter.api.Test; + +import javax.xml.transform.TransformerException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class XSLTProcessorUnitTest { + + @Test + public void givenValidInputAndStylesheet_whenTransformingXML_thenOutputHTMLCreated() throws TransformerException, IOException { + // Given + String inputXMLPath = "src/test/resources/input.xml"; + String xsltPath = "src/test/resources/stylesheet.xslt"; + String outputHTMLPath = "src/test/resources/output.html"; + + + XSLTProcessor.transformXMLUsingXSLT(inputXMLPath, xsltPath, outputHTMLPath); + + + Path outputFile = Paths.get(outputHTMLPath); + assertTrue(Files.exists(outputFile)); + } +} diff --git a/apache-libraries-2/src/test/resources/input.xml b/apache-libraries-2/src/test/resources/input.xml new file mode 100644 index 0000000000..e283680337 --- /dev/null +++ b/apache-libraries-2/src/test/resources/input.xml @@ -0,0 +1,11 @@ + + + + John Doe + 30 + + + Jane Smith + 25 + + diff --git a/apache-libraries-2/src/test/resources/output.html b/apache-libraries-2/src/test/resources/output.html new file mode 100644 index 0000000000..b75e73ca15 --- /dev/null +++ b/apache-libraries-2/src/test/resources/output.html @@ -0,0 +1,3 @@ + +

Male person: John Doe, Age: 30

+

Female person: Jane Smith, Age: 25

diff --git a/apache-libraries-2/src/test/resources/stylesheet.xslt b/apache-libraries-2/src/test/resources/stylesheet.xslt new file mode 100644 index 0000000000..9f07852a2a --- /dev/null +++ b/apache-libraries-2/src/test/resources/stylesheet.xslt @@ -0,0 +1,22 @@ + + + + + + Male person: + + , Age: + + + + + + + Female person: + + , Age: + + + + + diff --git a/pom.xml b/pom.xml index de95855f49..fd5257877a 100644 --- a/pom.xml +++ b/pom.xml @@ -758,6 +758,7 @@ algorithms-modules apache-libraries + apache-libraries-2 apache-poi apache-velocity di-modules @@ -1025,6 +1026,7 @@ algorithms-modules apache-libraries + apache-libraries-2 apache-poi apache-velocity di-modules From 65159d313a803b59d0ed5d9f661b34fb5ea9b0cc Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 17 Aug 2023 17:58:22 +0530 Subject: [PATCH 18/26] JAVA-19354 Potential issue in A Quick Guide to Using Keycloak With Spring Boot article (#14537) --- .../com/baeldung/keycloak/SecurityConfig.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 1ad22d9397..3423f8eb2b 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.keycloak; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -27,18 +28,30 @@ class SecurityConfig { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } + @Order(1) @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/customers*") - .hasRole("USER") + .antMatchers("/") + .permitAll() .anyRequest() - .permitAll(); + .authenticated(); http.oauth2Login() .and() .logout() .addLogoutHandler(keycloakLogoutHandler) .logoutSuccessUrl("/"); + return http.build(); + } + + @Order(2) + @Bean + public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/customers*") + .hasRole("USER") + .anyRequest() + .authenticated(); http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); return http.build(); } From 7f13b86f3b4d37f0154427184fbf53002581422a Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Thu, 17 Aug 2023 18:14:53 +0530 Subject: [PATCH 19/26] JAVA-23450: changes made for Update spring-boot-documentation module (#14533) --- pom.xml | 2 - spring-boot-documentation/pom.xml | 46 -------- spring-boot-documentation/springwolf/pom.xml | 82 -------------- spring-boot-modules/pom.xml | 1 + .../spring-boot-documentation}/README.md | 0 .../docker-compose.yml | 0 .../spring-boot-documentation/pom.xml | 102 ++++++++++++++++++ .../springwolf/SpringwolfApplication.java | 0 .../adapter/incoming/IncomingConsumer.java | 0 .../adapter/outgoing/OutgoingProducer.java | 0 .../springwolf/dto/IncomingPayloadDto.java | 0 .../springwolf/dto/OutgoingPayloadDto.java | 0 .../springwolf/service/ProcessorService.java | 0 .../src/main/resources/application.properties | 0 .../springwolf/ApiIntegrationTest.java | 0 .../src/test/resources/asyncapi.json | 0 16 files changed, 103 insertions(+), 130 deletions(-) delete mode 100644 spring-boot-documentation/pom.xml delete mode 100644 spring-boot-documentation/springwolf/pom.xml rename {spring-boot-documentation => spring-boot-modules/spring-boot-documentation}/README.md (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/docker-compose.yml (100%) create mode 100644 spring-boot-modules/spring-boot-documentation/pom.xml rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/main/resources/application.properties (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java (100%) rename {spring-boot-documentation/springwolf => spring-boot-modules/spring-boot-documentation}/src/test/resources/asyncapi.json (100%) diff --git a/pom.xml b/pom.xml index fd5257877a..8484e788bd 100644 --- a/pom.xml +++ b/pom.xml @@ -703,7 +703,6 @@ osgi spring-katharsis logging-modules - spring-boot-documentation spring-boot-modules apache-httpclient apache-httpclient4 @@ -977,7 +976,6 @@ osgi spring-katharsis logging-modules - spring-boot-documentation spring-boot-modules apache-httpclient apache-httpclient4 diff --git a/spring-boot-documentation/pom.xml b/spring-boot-documentation/pom.xml deleted file mode 100644 index d718f33a99..0000000000 --- a/spring-boot-documentation/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - com.baeldung.spring-boot-documentation - spring-boot-documentation - 1.0.0-SNAPSHOT - spring-boot-documentation - pom - - - com.baeldung - parent-boot-3 - 0.0.1-SNAPSHOT - ../parent-boot-3 - - - - springwolf - - - - - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - 3.3.2 - - - diff --git a/spring-boot-documentation/springwolf/pom.xml b/spring-boot-documentation/springwolf/pom.xml deleted file mode 100644 index 4bd9f24065..0000000000 --- a/spring-boot-documentation/springwolf/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - springwolf - 0.0.1-SNAPSHOT - springwolf - Documentation Spring Event Driven API Using AsyncAPI and Springwolf - - - com.baeldung.spring-boot-documentation - spring-boot-documentation - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.kafka - spring-kafka - - - io.swagger.core.v3 - swagger-core-jakarta - ${swagger-core.version} - - - io.github.springwolf - springwolf-kafka - ${springwolf-kafka.version} - - - io.github.springwolf - springwolf-ui - ${springwolf-ui.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.kafka - spring-kafka-test - test - - - org.testcontainers - junit-jupiter - ${testcontainers-kafka.version} - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.boot.documentation.springwolf.SpringwolfApplication - - - - - - - 2.2.11 - 0.12.1 - 0.8.0 - 1.18.3 - - - diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index de14e26027..a2febc8156 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -97,6 +97,7 @@ spring-boot-properties-3 spring-boot-properties-4 spring-boot-properties-migrator-demo + spring-boot-documentation diff --git a/spring-boot-documentation/README.md b/spring-boot-modules/spring-boot-documentation/README.md similarity index 100% rename from spring-boot-documentation/README.md rename to spring-boot-modules/spring-boot-documentation/README.md diff --git a/spring-boot-documentation/springwolf/docker-compose.yml b/spring-boot-modules/spring-boot-documentation/docker-compose.yml similarity index 100% rename from spring-boot-documentation/springwolf/docker-compose.yml rename to spring-boot-modules/spring-boot-documentation/docker-compose.yml diff --git a/spring-boot-modules/spring-boot-documentation/pom.xml b/spring-boot-modules/spring-boot-documentation/pom.xml new file mode 100644 index 0000000000..587ad8473b --- /dev/null +++ b/spring-boot-modules/spring-boot-documentation/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + com.baeldung.spring-boot-documentation + spring-boot-documentation + 1.0.0-SNAPSHOT + spring-boot-documentation + Documentation Spring Event Driven API Using AsyncAPI and Springwolf + pom + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3/pom.xml + + + + + + org.junit + junit-bom + ${junit-jupiter.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.kafka + spring-kafka + + + io.swagger.core.v3 + swagger-core-jakarta + ${swagger-core.version} + + + io.github.springwolf + springwolf-kafka + ${springwolf-kafka.version} + + + io.github.springwolf + springwolf-ui + ${springwolf-ui.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.kafka + spring-kafka-test + test + + + org.testcontainers + junit-jupiter + ${testcontainers-kafka.version} + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.boot.documentation.springwolf.SpringwolfApplication + + + + + + + 3.3.2 + 2.2.11 + 0.12.1 + 0.8.0 + 1.18.3 + + + diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/SpringwolfApplication.java diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/incoming/IncomingConsumer.java diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/adapter/outgoing/OutgoingProducer.java diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/dto/IncomingPayloadDto.java diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/dto/OutgoingPayloadDto.java diff --git a/spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java b/spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java similarity index 100% rename from spring-boot-documentation/springwolf/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java rename to spring-boot-modules/spring-boot-documentation/src/main/java/com/baeldung/boot/documentation/springwolf/service/ProcessorService.java diff --git a/spring-boot-documentation/springwolf/src/main/resources/application.properties b/spring-boot-modules/spring-boot-documentation/src/main/resources/application.properties similarity index 100% rename from spring-boot-documentation/springwolf/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-documentation/src/main/resources/application.properties diff --git a/spring-boot-documentation/springwolf/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java b/spring-boot-modules/spring-boot-documentation/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java similarity index 100% rename from spring-boot-documentation/springwolf/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java rename to spring-boot-modules/spring-boot-documentation/src/test/java/com/baeldung/boot/documentation/springwolf/ApiIntegrationTest.java diff --git a/spring-boot-documentation/springwolf/src/test/resources/asyncapi.json b/spring-boot-modules/spring-boot-documentation/src/test/resources/asyncapi.json similarity index 100% rename from spring-boot-documentation/springwolf/src/test/resources/asyncapi.json rename to spring-boot-modules/spring-boot-documentation/src/test/resources/asyncapi.json From fed88e6609b29d05ea166cd01529d64c303dc224 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 17 Aug 2023 16:38:05 -0400 Subject: [PATCH 20/26] BAEL-6827 - Update an Existing Amazon S3 Object using Java (#14585) * Deep and Shallow copy - code snippets * removed maven files * Ignore mvn files * Removed application test file * Removed .gitIgnore, additional review comments incorporated. * Incorporate review comments * incorporated review comments * https://jira.baeldung.com/browse/BAEL-6827 - Initial Commit * BAEL-6827 - Unit tests * BAEL-6827 - Tests * BAEL-6827 - Minor issue fixes * Removed deep shalow copy project * BAEL-6827 - BDD naming convention * BAEL-6827 - Test classes end with *UnitTest,.java --- .gitignore | 5 +- aws-modules/aws-s3-update-object/pom.xml | 46 +++++++++ .../AwsS3UpdateObjectApplication.java | 13 +++ .../controller/FileController.java | 24 +++++ .../service/FileService.java | 80 +++++++++++++++ .../src/main/resources/application.properties | 1 + .../controller/FileControllerUnitTest.java | 61 ++++++++++++ .../service/FileServiceUnitTest.java | 97 +++++++++++++++++++ 8 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 aws-modules/aws-s3-update-object/pom.xml create mode 100644 aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java create mode 100644 aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java create mode 100644 aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java create mode 100644 aws-modules/aws-s3-update-object/src/main/resources/application.properties create mode 100644 aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java create mode 100644 aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java diff --git a/.gitignore b/.gitignore index d22c792f43..0b6bd24070 100644 --- a/.gitignore +++ b/.gitignore @@ -124,4 +124,7 @@ devDb*.db *.xjb #neo4j -persistence-modules/neo4j/data/** \ No newline at end of file +persistence-modules/neo4j/data/** +/deep-shallow-copy/.mvn/wrapper +/deep-shallow-copy/mvnw +/deep-shallow-copy/mvnw.cmd diff --git a/aws-modules/aws-s3-update-object/pom.xml b/aws-modules/aws-s3-update-object/pom.xml new file mode 100644 index 0000000000..b44cdb8c6a --- /dev/null +++ b/aws-modules/aws-s3-update-object/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.2 + + + com.baeldung + aws-s3-update-object + 0.0.1-SNAPSHOT + aws-s3-update-object + Project demonstrating overwriting of S3 objects + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.amazonaws + aws-java-sdk + 1.12.523 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java new file mode 100644 index 0000000000..24866c287b --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/AwsS3UpdateObjectApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.awss3updateobject; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AwsS3UpdateObjectApplication { + + public static void main(String[] args) { + SpringApplication.run(AwsS3UpdateObjectApplication.class, args); + } + +} diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java new file mode 100644 index 0000000000..e87358ef56 --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/controller/FileController.java @@ -0,0 +1,24 @@ +package com.baeldung.awss3updateobject.controller; + +import com.baeldung.awss3updateobject.service.FileService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping("api/v1/file") +public class FileController { + + @Autowired + FileService fileService; + + @PostMapping("/upload") + public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception { + return this.fileService.uploadFile(multipartFile); + } + + @PostMapping("/update") + public String updateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("filePath") String exitingFilePath) throws Exception { + return this.fileService.updateFile(multipartFile, exitingFilePath); + } +} diff --git a/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java new file mode 100644 index 0000000000..8f3458d060 --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/main/java/com/baeldung/awss3updateobject/service/FileService.java @@ -0,0 +1,80 @@ +package com.baeldung.awss3updateobject.service; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.s3.model.*; +import jakarta.annotation.PostConstruct; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +@Service +public class FileService { + + private static final Logger logger = LoggerFactory.getLogger(FileService.class); + + public AmazonS3 amazonS3; + + @Value("${aws.s3bucket}") + public String awsS3Bucket; + + @PostConstruct + private void init(){ + AWSCredentials credentials = new BasicAWSCredentials( + "AWS AccessKey", + "AWS secretKey" + ); + this.amazonS3 = AmazonS3ClientBuilder.standard() + .withRegion(Regions.fromName("us-east-1")) + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .build(); + } + + public String uploadFile(MultipartFile multipartFile) throws Exception { + String key = "/documents/" + multipartFile.getOriginalFilename(); + return this.uploadDocument(this.awsS3Bucket, key, multipartFile); + } + + public String updateFile(MultipartFile multipartFile, String key) throws Exception { + return this.uploadDocument(this.awsS3Bucket, key, multipartFile); + } + + private String uploadDocument(String s3bucket, String key, MultipartFile multipartFile) throws Exception { + try { + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentType(multipartFile.getContentType()); + Map attributes = new HashMap<>(); + attributes.put("document-content-size", String.valueOf(multipartFile.getSize())); + metadata.setUserMetadata(attributes); + InputStream documentStream = multipartFile.getInputStream(); + PutObjectResult putObjectResult = this.amazonS3.putObject(new PutObjectRequest(s3bucket, key, documentStream, metadata)); + + S3Object s3Object = this.amazonS3.getObject(s3bucket, key); + logger.info("Last Modified: " + s3Object.getObjectMetadata().getLastModified()); + return key; + } catch (AmazonS3Exception ex) { + if (ex.getErrorCode().equalsIgnoreCase("NoSuchBucket")) { + String msg = String.format("No bucket found with name %s", s3bucket); + throw new Exception(msg); + } else if (ex.getErrorCode().equalsIgnoreCase("AccessDenied")) { + String msg = String.format("Access denied to S3 bucket %s", s3bucket); + throw new Exception(msg); + } + throw ex; + } catch (IOException ex) { + String msg = String.format("Error saving file %s to AWS S3 bucket %s", key, s3bucket); + throw new Exception(msg); + } + } +} diff --git a/aws-modules/aws-s3-update-object/src/main/resources/application.properties b/aws-modules/aws-s3-update-object/src/main/resources/application.properties new file mode 100644 index 0000000000..c840d970a8 --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/main/resources/application.properties @@ -0,0 +1 @@ +aws.s3bucket=baeldung-documents; diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java new file mode 100644 index 0000000000..ec2385f62b --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/controller/FileControllerUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.awss3updateobject.controller; + +import com.baeldung.awss3updateobject.service.FileService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.multipart.MultipartFile; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +public class FileControllerUnitTest { + + private MockMvc mockMvc; + + @Mock + private FileService fileService; + + @InjectMocks + private FileController fileController; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(fileController).build(); + } + + @Test + public void givenValidMultipartFile_whenUploadedViaEndpoint_thenCorrectPathIsReturned() throws Exception { + MockMultipartFile multipartFile = new MockMultipartFile("multipartFile", "test.txt", + "text/plain", "test data".getBytes()); + + when(fileService.uploadFile(any(MultipartFile.class))).thenReturn("/documents/test.txt"); + + mockMvc.perform(multipart("/file/upload").file(multipartFile)) + .andExpect(status().isOk()) + .andExpect(content().string("/documents/test.txt")); + } + + @Test + public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception { + MockMultipartFile multipartFile = new MockMultipartFile("multipartFile", "test.txt", + "text/plain", "test update data".getBytes()); + String existingFilePath = "/documents/existingFile.txt"; + + when(fileService.updateFile(any(MultipartFile.class), eq(existingFilePath))).thenReturn(existingFilePath); + + mockMvc.perform(multipart("/file/update") + .file(multipartFile) + .param("exitingFilePath", existingFilePath)) + .andExpect(status().isOk()) + .andExpect(content().string(existingFilePath)); + } +} \ No newline at end of file diff --git a/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java new file mode 100644 index 0000000000..3ccd41820e --- /dev/null +++ b/aws-modules/aws-s3-update-object/src/test/java/com/baeldung/awss3updateobject/service/FileServiceUnitTest.java @@ -0,0 +1,97 @@ +package com.baeldung.awss3updateobject.service; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.model.AmazonS3Exception; +import com.amazonaws.services.s3.model.PutObjectRequest; +import com.amazonaws.services.s3.model.S3Object; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class FileServiceUnitTest { + + @Mock + private AmazonS3 amazonS3; + + @Mock + private MultipartFile multipartFile; + + @InjectMocks + private FileService fileService; + + @BeforeEach + public void setup() { + MockitoAnnotations.openMocks(this); + fileService = new FileService(); + fileService.awsS3Bucket = "test-bucket"; + fileService.amazonS3 = amazonS3; + } + + @Test + public void givenValidFile_whenUploaded_thenKeyMatchesDocumentPath() throws Exception { + when(multipartFile.getName()).thenReturn("testFile"); + when(multipartFile.getContentType()).thenReturn("application/pdf"); + when(multipartFile.getSize()).thenReturn(1024L); + when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); + + S3Object s3Object = new S3Object(); + when(amazonS3.putObject(any())).thenReturn(null); + when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object); + + String key = fileService.uploadFile(multipartFile); + + assertEquals("/documents/testFile", key); + } + + @Test + public void givenValidFile_whenUploadFailsDueToNoBucket_thenExceptionIsThrown() throws Exception { + when(multipartFile.getName()).thenReturn("testFile"); + when(multipartFile.getContentType()).thenReturn("application/pdf"); + when(multipartFile.getSize()).thenReturn(1024L); + when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); + + AmazonS3Exception exception = new AmazonS3Exception("Test exception"); + exception.setErrorCode("NoSuchBucket"); + when(amazonS3.putObject(any(PutObjectRequest.class))).thenThrow(exception); + + assertThrows(Exception.class, () -> fileService.uploadFile(multipartFile)); + } + + @Test + public void givenExistingFile_whenUpdated_thenSameKeyIsReturned() throws Exception { + when(multipartFile.getName()).thenReturn("testFile"); + when(multipartFile.getContentType()).thenReturn("application/pdf"); + when(multipartFile.getSize()).thenReturn(1024L); + when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class)); + + S3Object s3Object = new S3Object(); + when(amazonS3.putObject(any(PutObjectRequest.class))).thenReturn(null); + when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object); + + String key = "/documents/existingFile"; + String resultKey = fileService.updateFile(multipartFile, key); + + assertEquals(key, resultKey); + } + + @Test + public void givenFileWithIOException_whenUpdated_thenExceptionIsThrown() throws Exception { + when(multipartFile.getName()).thenReturn("testFile"); + when(multipartFile.getContentType()).thenReturn("application/pdf"); + when(multipartFile.getSize()).thenReturn(1024L); + when(multipartFile.getInputStream()).thenThrow(new IOException("Test IO Exception")); + + assertThrows(Exception.class, () -> fileService.updateFile(multipartFile, "/documents/existingFile")); + } +} \ No newline at end of file From 04caad5f8058152b08f911959dcf7eb6e3ec97d8 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Fri, 18 Aug 2023 12:14:17 +0300 Subject: [PATCH 21/26] JAVA-24057 Upgrade java-aes-encryption-decription article (#14593) --- .../core-java-security-algorithms/pom.xml | 24 ------------------- 1 file changed, 24 deletions(-) diff --git a/core-java-modules/core-java-security-algorithms/pom.xml b/core-java-modules/core-java-security-algorithms/pom.xml index 0dde9f861a..0204203fd7 100644 --- a/core-java-modules/core-java-security-algorithms/pom.xml +++ b/core-java-modules/core-java-security-algorithms/pom.xml @@ -13,28 +13,4 @@ 0.0.1-SNAPSHOT - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - - - - - 1.60 - 1.11 - 2.3.1 - - \ No newline at end of file From 395d0f9d22f8d0931d0a026e09cffcc69ec9a99e Mon Sep 17 00:00:00 2001 From: gaepi Date: Fri, 18 Aug 2023 12:58:17 +0200 Subject: [PATCH 22/26] JAVA-24249 | Renamed test in LiveTest since it's using TestContainers. --- ...derServiceIntegrationTest.java => OrderServiceLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/{OrderServiceIntegrationTest.java => OrderServiceLiveTest.java} (98%) diff --git a/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceIntegrationTest.java b/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceLiveTest.java similarity index 98% rename from persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceIntegrationTest.java rename to persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceLiveTest.java index 938d250058..139081182f 100644 --- a/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceIntegrationTest.java +++ b/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceLiveTest.java @@ -21,7 +21,7 @@ import java.util.List; @Testcontainers @SpringBootTest -class OrderServiceIntegrationTest { +class OrderServiceLiveTest { @Container static MySQLContainer mySQLContainer1 = new MySQLContainer<>("mysql:8.0.23") From b25e32479036dd3e0a2d88974598bab5bd7b6867 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Sat, 19 Aug 2023 01:06:51 +0530 Subject: [PATCH 23/26] [BAEL-6859] Inner Classes vs. Subclasses in Java (#14608) * [BAEL-6859] inner and sub classes * [BAEL-6859] unit test cases added --------- Co-authored-by: Bhaskar --- .../subclassinnerclass/EmailNotifier.java | 17 +++++++++++++++++ .../baeldung/subclassinnerclass/Message.java | 6 ++++++ .../NotificationService.java | 17 +++++++++++++++++ .../baeldung/subclassinnerclass/Notifier.java | 5 +++++ .../TextMessageNotifier.java | 14 ++++++++++++++ .../subclassinnerclass/InnerClassUnitTest.java | 16 ++++++++++++++++ .../subclassinnerclass/SubClassUnitTest.java | 18 ++++++++++++++++++ 7 files changed, 93 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/EmailNotifier.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Message.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/NotificationService.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Notifier.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/TextMessageNotifier.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/InnerClassUnitTest.java create mode 100644 core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/SubClassUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/EmailNotifier.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/EmailNotifier.java new file mode 100644 index 0000000000..1ade675e87 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/EmailNotifier.java @@ -0,0 +1,17 @@ +package com.baeldung.subclassinnerclass; + +import java.util.HashMap; + +public class EmailNotifier extends Notifier { + @Override + void notify(Message e) { + // Provide email specific implementation here + } + + // Inner class for email connection + static class EmailConnector { + private String emailHost; + private int emailPort; + // Getter Setters + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Message.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Message.java new file mode 100644 index 0000000000..35d751b288 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Message.java @@ -0,0 +1,6 @@ +package com.baeldung.subclassinnerclass; + +public class Message { + private int message; + // getter setter and other atteibutes +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/NotificationService.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/NotificationService.java new file mode 100644 index 0000000000..2ebbbde961 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/NotificationService.java @@ -0,0 +1,17 @@ +package com.baeldung.subclassinnerclass; + +public class NotificationService { + void notifyMessages() { + // Sending a Text Message + Message textMessage = new Message(); + Notifier textNotifier = new TextMessageNotifier(); + + textNotifier.notify(textMessage); + + // Sending an Email Message + Message emailMessage = new Message(); + Notifier emailNotifier = new EmailNotifier(); + + emailNotifier.notify(emailMessage); + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Notifier.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Notifier.java new file mode 100644 index 0000000000..aff0372af3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/Notifier.java @@ -0,0 +1,5 @@ +package com.baeldung.subclassinnerclass; + +public abstract class Notifier { + abstract void notify(Message e); +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/TextMessageNotifier.java b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/TextMessageNotifier.java new file mode 100644 index 0000000000..8b64b4331d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/main/java/com/baeldung/subclassinnerclass/TextMessageNotifier.java @@ -0,0 +1,14 @@ +package com.baeldung.subclassinnerclass; + +public class TextMessageNotifier extends Notifier { + @Override + void notify(Message e) { + // Provide text message specific implementation here + } + + // Inner class for text message connection + private static class SMSConnector { + private String smsHost; + // Getter Setters + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/InnerClassUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/InnerClassUnitTest.java new file mode 100644 index 0000000000..27577a546f --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/InnerClassUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.subclassinnerclass; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import org.junit.Test; + +public class InnerClassUnitTest { + @Test + public void givenInnerStaticClassWhenInstantiatedThenOuterClassIsInstantiated() { + Notifier emailNotifier = new EmailNotifier(); + EmailNotifier.EmailConnector emailConnector = new EmailNotifier.EmailConnector(); + + assertThat(emailNotifier).hasSameClassAs(new EmailNotifier()); + assertThat(emailConnector).isInstanceOf(EmailNotifier.EmailConnector.class); + } +} diff --git a/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/SubClassUnitTest.java b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/SubClassUnitTest.java new file mode 100644 index 0000000000..25e6f5b8a4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-inheritance/src/test/java/com/baeldung/subclassinnerclass/SubClassUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.subclassinnerclass; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import org.junit.Test; + +public class SubClassUnitTest { + @Test + public void givenSubclassWhenInstantiatedThenSubclassObjectIsPossible() { + Notifier emailNotifier = new EmailNotifier(); + assertThat(emailNotifier).hasSameClassAs(new EmailNotifier()); + assertThat(emailNotifier).isExactlyInstanceOf(EmailNotifier.class); + + Notifier textMessageNotifier = new TextMessageNotifier(); + assertThat(textMessageNotifier).isInstanceOf(Notifier.class); + assertThat(textMessageNotifier).isExactlyInstanceOf(TextMessageNotifier.class); + } +} From 85026701400be0c267a18ecc23d4a48a7c791308 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Fri, 18 Aug 2023 20:43:41 +0100 Subject: [PATCH 24/26] Calculating the Sum of Two Arrays Element by Element in Java (#14579) * Create SumArraysUsingForLoop.java * Update SumArraysUsingForLoop.java * add sum arrays using for each loop and streams * Create SumArraysUsingForLoopTest.java * Add files via upload * Update SumArraysUsingStreams.java * Update and rename SumArraysUsingForEachTest.java to SumArraysUsingForEachUnitTest.java * Rename SumArraysUsingForLoopTest.java to SumArraysUsingForLoopUnitTest.java * Update and rename SumArraysUsingStreamsTest.java to SumArraysUsingStreamsUnitTest.java * Update SumArraysUsingForEachUnitTest.java * Update SumArraysUsingForLoopUnitTest.java * Update SumArraysUsingForEachUnitTest.java * Update SumArraysUsingStreamsUnitTest.java --- .../arraysums/SumArraysUsingForEach.java | 14 ++++++++++++++ .../arraysums/SumArraysUsingForLoop.java | 12 ++++++++++++ .../arraysums/SumArraysUsingStreams.java | 14 ++++++++++++++ .../arraysums/SumArraysUsingForEachUnitTest.java | 16 ++++++++++++++++ .../arraysums/SumArraysUsingForLoopUnitTest.java | 16 ++++++++++++++++ .../arraysums/SumArraysUsingStreamsUnitTest.java | 16 ++++++++++++++++ 6 files changed, 88 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForEach.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForLoop.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingStreams.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForEachUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForLoopUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingStreamsUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForEach.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForEach.java new file mode 100644 index 0000000000..3c2a75a409 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForEach.java @@ -0,0 +1,14 @@ +package com.baeldung.arraysums; + +public class SumArraysUsingForEach { + + public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) { + int[] arr3 = new int[arr1.length]; + int counter = 0; + for (int num1 : arr1) { + arr3[counter] = num1 + arr2[counter]; + counter++; + } + return arr3; + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForLoop.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForLoop.java new file mode 100644 index 0000000000..32e2e939d4 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingForLoop.java @@ -0,0 +1,12 @@ +package com.baeldung.arraysums; + +public class SumArraysUsingForLoop { + + public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) { + int[] arr3 = new int[arr1.length]; + for (int i = 0; i < arr1.length; i++) { + arr3[i] = arr1[i] + arr2[i]; + } + return arr3; + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingStreams.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingStreams.java new file mode 100644 index 0000000000..40bfda4b74 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraysums/SumArraysUsingStreams.java @@ -0,0 +1,14 @@ +package com.baeldung.arraysums; + +import java.util.Arrays; +import java.util.stream.IntStream; + +public class SumArraysUsingStreams { + + public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) { + IntStream range = IntStream.range(0, Math.min(arr1.length, arr2.length)); + IntStream stream3 = range.map(i -> arr1[i] + arr2[i]); + int[] arr3 = stream3.toArray(); + return arr3; + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForEachUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForEachUnitTest.java new file mode 100644 index 0000000000..883b35b223 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForEachUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.arraysums; + +import com.baeldung.arraysums.SumArraysUsingForEach; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SumArraysUsingForEachUnitTest { + + @Test + public void sumOfTwoArraysUsingForEach_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() { + int[] arr1 = { 4, 5, 1, 6, 4, 15 }; + int[] arr2 = { 3, 5, 6, 1, 9, 6 }; + int[] expected = { 7, 10, 7, 7, 13, 21 }; + assertArrayEquals(expected, SumArraysUsingForEach.sumOfTwoArrays(arr1, arr2)); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForLoopUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForLoopUnitTest.java new file mode 100644 index 0000000000..7cffd5f4ff --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingForLoopUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.arraysums; + +import com.baeldung.arraysums.SumArraysUsingForLoop; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SumArraysUsingForLoopUnitTest { + + @Test + public void sumOfTwoArrays_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() { + int[] arr1 = {4, 5, 1, 6, 4, 15}; + int[] arr2 = {3, 5, 6, 1, 9, 6}; + int[] expected = {7, 10, 7, 7, 13, 21}; + assertArrayEquals(expected, SumArraysUsingForLoop.sumOfTwoArrays(arr1, arr2)); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingStreamsUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingStreamsUnitTest.java new file mode 100644 index 0000000000..62ea465ab0 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraysums/SumArraysUsingStreamsUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.arraysums; + +import com.baeldung.arraysums.SumArraysUsingStreams; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SumArraysUsingStreamsUnitTest { + + @Test + public void sumOfTwoArraysUsingStreams_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() { + int[] arr1 = {4, 5, 1, 6, 4, 15}; + int[] arr2 = {3, 5, 6, 1, 9, 6}; + int[] expected = {7, 10, 7, 7, 13, 21}; + assertArrayEquals(expected, SumArraysUsingStreams.sumOfTwoArrays(arr1, arr2)); + } +} From 16080930fa4ec37827015762cf38b41ca951d4e3 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 18 Aug 2023 21:48:48 +0200 Subject: [PATCH 25/26] [map-KV-to-list] Get Values and Keys as ArralyLists From a HashMap (#14615) --- .../kvtolist/MapKeysValuesToListUnitTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/hashmap/kvtolist/MapKeysValuesToListUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/hashmap/kvtolist/MapKeysValuesToListUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/hashmap/kvtolist/MapKeysValuesToListUnitTest.java new file mode 100644 index 0000000000..39c537bac2 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/hashmap/kvtolist/MapKeysValuesToListUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.map.hashmap.kvtolist; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +public class MapKeysValuesToListUnitTest { + private static final HashMap DEV_MAP; + + static { + DEV_MAP = new HashMap<>(); + DEV_MAP.put("Kent", "Linux"); + DEV_MAP.put("Eric", "MacOS"); + DEV_MAP.put("Kevin", "Windows"); + DEV_MAP.put("Michal", "MacOS"); + DEV_MAP.put("Saajan", "Linux"); + } + + @Test + void whenUsingKeySet_thenGetExpectedResult() { + List keyList = new ArrayList<>(DEV_MAP.keySet()); + // this assertion may fail, since hashMap doesn't preserve the insertion order + // assertEquals(Lists.newArrayList("Kent", "Eric", "Kevin", "Michal", "Saajan"), keyList); + + assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan"); + + } + + @Test + void whenUsingValues_thenGetExpectedResult() { + List valueList = new ArrayList<>(DEV_MAP.values()); + assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux"); + } + + @Test + void whenLoopingEntries_thenGetExpectedResult() { + List keyList = new ArrayList<>(); + List valueList = new ArrayList<>(); + for (Map.Entry entry : DEV_MAP.entrySet()) { + keyList.add(entry.getKey()); + valueList.add(entry.getValue()); + } + + assertKeyAndValueList(keyList, valueList); + + } + + @Test + void whenUsingForEach_thenGetExpectedResult() { + List keyList = new ArrayList<>(); + List valueList = new ArrayList<>(); + DEV_MAP.forEach((k, v) -> { + keyList.add(k); + valueList.add(v); + }); + + assertKeyAndValueList(keyList, valueList); + } + + private void assertKeyAndValueList(List keyList, List valueList) { + assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan"); + assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux"); + for (int i = 0; i < keyList.size(); i++) { + assertThat(DEV_MAP).containsEntry(keyList.get(i), valueList.get(i)); + } + } +} \ No newline at end of file From 98d959f33a63c909187d6358e111071cefb553e1 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 19 Aug 2023 03:30:24 +0200 Subject: [PATCH 26/26] Get the first n elements of a List into an Array (#14599) * Get the first n elements of a List into an Array * [first-n-to-array] rename N -> n --- .../ListToArrayFirstNElementsUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ListToArrayFirstNElementsUnitTest.java diff --git a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ListToArrayFirstNElementsUnitTest.java b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ListToArrayFirstNElementsUnitTest.java new file mode 100644 index 0000000000..c9818613fe --- /dev/null +++ b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ListToArrayFirstNElementsUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.arrayconversion; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import java.util.Iterator; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class ListToArrayFirstNElementsUnitTest { + private static final List INPUT_LIST = Lists.newArrayList("one", "two", "three", "four", "five", "six", "seven"); + private static final int n = 5; + + @Test + void whenUsingForLoop_thenGetExpectedArray() { + String[] result = new String[n]; + for (int i = 0; i < n; i++) { + result[i] = INPUT_LIST.get(i); + } + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result); + + String[] result2 = new String[n]; + Iterator iterator = INPUT_LIST.iterator(); + for (int i = 0; i < n && iterator.hasNext(); i++) { + result2[i] = iterator.next(); + } + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2); + } + + @Test + void whenUsingSubList_thenGetExpectedArray() { + String[] result = new String[n]; + INPUT_LIST.subList(0, n) + .toArray(result); + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result); + + String[] result2 = INPUT_LIST.subList(0, n) + .toArray(new String[0]); + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2); + + // available only for java 11+ + String[] result3 = INPUT_LIST.subList(0, n) + .toArray(String[]::new); + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result3); + } + + @Test + void whenUsingStream_thenGetExpectedArray() { + String[] result = INPUT_LIST.stream() + .limit(n) + .toArray(String[]::new); + assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result); + } +} \ No newline at end of file