From 79bf0d99762ec36185c5eb4930512ac1ac139ade Mon Sep 17 00:00:00 2001
From: Sachin kumar
Date: Thu, 16 Dec 2021 17:43:43 +0530
Subject: [PATCH 001/235] BAEL-5271 set custom thread name
---
.../threads/name/CustomThreadName.java | 70 +++++++++++++++++++
1 file changed, 70 insertions(+)
create mode 100644 core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/threads/name/CustomThreadName.java
diff --git a/core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/threads/name/CustomThreadName.java b/core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/threads/name/CustomThreadName.java
new file mode 100644
index 0000000000..9ce35d1137
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/threads/name/CustomThreadName.java
@@ -0,0 +1,70 @@
+package com.baeldung.concurrent.threads.name;
+
+public class CustomThreadName {
+
+ public int currentNumber = 1;
+
+ public int N = 5;
+
+ public static void main(String[] args) {
+
+ CustomThreadName test = new CustomThreadName();
+
+ Thread oddThread = new Thread(() -> {
+ test.printOddNumber();
+ // Uncomment below to set thread name using setName() Method
+ // Thread.currentThread().setName("ODD");
+ }, "ODD");
+ // or Uncomment below to set thread name using setName() Method
+ // oddThread.setName("ODD");
+
+ Thread evenThread = new Thread(() -> {
+ test.printEvenNumber();
+ // Uncomment below to set thread name using setName() Method
+ // Thread.currentThread().setName("EVEN");
+ }, "EVEN");
+
+ // evenThread.setName("EVEN");
+
+ evenThread.start();
+ oddThread.start();
+
+ }
+
+ public void printEvenNumber() {
+ synchronized (this) {
+ while (currentNumber < N) {
+ while (currentNumber % 2 == 1) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ System.out.println(Thread.currentThread()
+ .getName() + " --> " + currentNumber);
+ currentNumber++;
+ notify();
+ }
+ }
+ }
+
+ public void printOddNumber() {
+ synchronized (this) {
+ while (currentNumber < N) {
+ while (currentNumber % 2 == 0) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ System.out.println(Thread.currentThread()
+ .getName() + " --> " + currentNumber);
+ currentNumber++;
+ notify();
+ }
+ }
+ }
+
+}
From a95db4fe73200e9722df00dc49e23503a64ac1ab Mon Sep 17 00:00:00 2001
From: mdabrowski-eu
Date: Sat, 15 Jan 2022 03:27:58 +0100
Subject: [PATCH 002/235] BAEL-5301 Retrying Feign Calls
---
.../feign/retry/Custom5xxErrorDecoder.java | 27 ++++++++++
.../baeldung/feign/retry/NaiveRetryer.java | 21 ++++++++
.../retry/ResilientFeignClientBuilder.java | 28 ++++++++++
.../retry/Custom5xxErrorDecoderUnitTest.java | 51 +++++++++++++++++++
4 files changed, 127 insertions(+)
create mode 100644 feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
create mode 100644 feign/src/main/java/com/baeldung/feign/retry/NaiveRetryer.java
create mode 100644 feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
create mode 100644 feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
diff --git a/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java b/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
new file mode 100644
index 0000000000..c4edfe219f
--- /dev/null
+++ b/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
@@ -0,0 +1,27 @@
+package com.baeldung.feign.retry;
+
+
+import feign.FeignException;
+import feign.Response;
+import feign.RetryableException;
+import feign.codec.ErrorDecoder;
+
+import static feign.FeignException.errorStatus;
+
+public class Custom5xxErrorDecoder implements ErrorDecoder {
+ @Override
+ public Exception decode(String methodKey, Response response) {
+ FeignException exception = errorStatus(methodKey, response);
+ int status = response.status();
+ if (status >= 500) {
+ return new RetryableException(
+ response.status(),
+ exception.getMessage(),
+ response.request().httpMethod(),
+ exception,
+ null,
+ response.request());
+ }
+ return exception;
+ }
+}
diff --git a/feign/src/main/java/com/baeldung/feign/retry/NaiveRetryer.java b/feign/src/main/java/com/baeldung/feign/retry/NaiveRetryer.java
new file mode 100644
index 0000000000..5a3c13fadd
--- /dev/null
+++ b/feign/src/main/java/com/baeldung/feign/retry/NaiveRetryer.java
@@ -0,0 +1,21 @@
+package com.baeldung.feign.retry;
+
+import feign.RetryableException;
+import feign.Retryer;
+
+public class NaiveRetryer implements feign.Retryer {
+ @Override
+ public void continueOrPropagate(RetryableException e) {
+ try {
+ Thread.sleep(1000L);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw e;
+ }
+ }
+
+ @Override
+ public Retryer clone() {
+ return new NaiveRetryer();
+ }
+}
diff --git a/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
new file mode 100644
index 0000000000..edcaf13242
--- /dev/null
+++ b/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
@@ -0,0 +1,28 @@
+package com.baeldung.feign.retry;
+
+import com.baeldung.feign.clients.BookClient;
+import feign.Feign;
+import feign.Logger;
+import feign.Retryer;
+import feign.gson.GsonDecoder;
+import feign.gson.GsonEncoder;
+import feign.okhttp.OkHttpClient;
+import feign.slf4j.Slf4jLogger;
+import lombok.Getter;
+
+import java.util.concurrent.TimeUnit;
+
+@Getter
+public class ResilientFeignClientBuilder {
+ public BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
+
+ public static T createClient(Class type, String uri) {
+ return Feign.builder()
+ .client(new OkHttpClient())
+ .encoder(new GsonEncoder())
+ .decoder(new GsonDecoder())
+ .retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(3L), 5))
+ .errorDecoder(new Custom5xxErrorDecoder())
+ .target(type, uri);
+ }
+}
diff --git a/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
new file mode 100644
index 0000000000..0b67090268
--- /dev/null
+++ b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.feign.retry;
+
+import feign.*;
+import feign.codec.ErrorDecoder;
+import org.jetbrains.annotations.NotNull;
+import org.junit.Test;
+
+import java.nio.charset.Charset;
+import java.util.Collection;
+import java.util.HashMap;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class Custom5xxErrorDecoderUnitTest {
+ @Test
+ public void given5xxResponse_whenDecode_thenReturnRetryableException() {
+ // given
+ ErrorDecoder decoder = new Custom5xxErrorDecoder();
+ Response response = responseStub(500);
+
+ // when
+ Exception exception = decoder.decode("GET", response);
+
+ // then
+ assertTrue(exception instanceof RetryableException);
+ }
+
+ @Test
+ public void given4xxResponse_whenDecode_thenReturnFeignException() {
+ // given
+ ErrorDecoder decoder = new Custom5xxErrorDecoder();
+ Response response = responseStub(400);
+
+ // when
+ Exception exception = decoder.decode("GET", response);
+
+ // then
+ assertTrue(exception instanceof FeignException);
+ assertFalse(exception instanceof RetryableException);
+ }
+
+ @NotNull
+ private Response responseStub(int status) {
+ return Response.builder()
+ .request(Request.create(
+ Request.HttpMethod.GET, "url", new HashMap>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
+ .status(status)
+ .build();
+ }
+}
From 31ddc6a45dc01d066b0000fd616084ba4a33a374 Mon Sep 17 00:00:00 2001
From: mobin
Date: Sat, 15 Jan 2022 16:37:28 +0530
Subject: [PATCH 003/235] Move arrive and wait after thread sleep and detailed
logging
---
.../baeldung/concurrent/phaser/LongRunningAction.java | 9 +++++++--
.../com/baeldung/concurrent/phaser/PhaserUnitTest.java | 7 +++++++
2 files changed, 14 insertions(+), 2 deletions(-)
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
index dd1487b5cb..c022c02085 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
@@ -16,12 +16,17 @@ class LongRunningAction implements Runnable {
public void run() {
System.out.println("This is phase " + ph.getPhase());
System.out.println("Thread " + threadName + " before long running action");
- ph.arriveAndAwaitAdvance();
+
try {
- Thread.sleep(20);
+ Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
+
+ System.out.println("Thread " + threadName + " action completed and waiting for others");
+ ph.arriveAndAwaitAdvance();
+ System.out.println("Thread " + threadName + " proceeding in phase " + ph.getPhase());
+
ph.arriveAndDeregister();
}
}
\ No newline at end of file
diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
index a7b56e1151..88c18b5149 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
@@ -26,13 +26,20 @@ public class PhaserUnitTest {
executorService.submit(new LongRunningAction("thread-3", ph));
//then
+ System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
ph.arriveAndAwaitAdvance();
+ System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
+
+ System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
ph.arriveAndAwaitAdvance();
+ System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+
assertEquals(2, ph.getPhase());
From d0735facef7bba13d317b021a91ec22b89231895 Mon Sep 17 00:00:00 2001
From: Mladen Savic
Date: Sun, 16 Jan 2022 21:31:59 +0100
Subject: [PATCH 004/235] Difference between NIO and NIO.2?
---
.../baeldung/niovsnio2/NioVsNio2UnitTest.java | 70 +++++++++++++++++++
.../src/test/resources/nio-vs-nio2.txt | 1 +
2 files changed, 71 insertions(+)
create mode 100644 core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java
create mode 100644 core-java-modules/core-java-nio-2/src/test/resources/nio-vs-nio2.txt
diff --git a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java
new file mode 100644
index 0000000000..7413ebda13
--- /dev/null
+++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/niovsnio2/NioVsNio2UnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.niovsnio2;
+
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class NioVsNio2UnitTest {
+
+ @Test
+ public void readFromFileUsingFileIO() throws Exception {
+ File file = new File("src/test/resources/nio-vs-nio2.txt");
+ FileInputStream in = new FileInputStream(file);
+ StringBuilder content = new StringBuilder();
+ int data = in.read();
+ while (data != -1) {
+ content.append((char) data);
+ data = in.read();
+ }
+ in.close();
+ assertThat(content.toString()).isEqualTo("Hello from file!");
+ }
+
+ @Test
+ public void readFromFileUsingFileChannel() throws Exception {
+ RandomAccessFile file = new RandomAccessFile("src/test/resources/nio-vs-nio2.txt", "r");
+ FileChannel channel = file.getChannel();
+ StringBuilder content = new StringBuilder();
+
+ ByteBuffer buffer = ByteBuffer.allocate(256);
+ int bytesRead = channel.read(buffer);
+ while (bytesRead != -1) {
+ buffer.flip();
+
+ while (buffer.hasRemaining()) {
+ content.append((char) buffer.get());
+ }
+
+ buffer.clear();
+ bytesRead = channel.read(buffer);
+ }
+ file.close();
+
+ assertThat(content.toString()).isEqualTo("Hello from file!");
+ }
+
+ @Test
+ public void readFromFileUsingNIO2() throws Exception {
+ List strings = Files.readAllLines(Paths.get("src/test/resources/nio-vs-nio2.txt"));
+
+ assertThat(strings.get(0)).isEqualTo("Hello from file!");
+ }
+
+ @Test
+ public void listFilesUsingWalk() throws Exception {
+ Path path = Paths.get("src/test");
+ Stream walk = Files.walk(path);
+ walk.forEach(System.out::println);
+ }
+}
diff --git a/core-java-modules/core-java-nio-2/src/test/resources/nio-vs-nio2.txt b/core-java-modules/core-java-nio-2/src/test/resources/nio-vs-nio2.txt
new file mode 100644
index 0000000000..c12b07297d
--- /dev/null
+++ b/core-java-modules/core-java-nio-2/src/test/resources/nio-vs-nio2.txt
@@ -0,0 +1 @@
+Hello from file!
\ No newline at end of file
From 7ad433dcb6990c01ecc3af70a26f61e16ac63e46 Mon Sep 17 00:00:00 2001
From: Ulisses Lima
Date: Sat, 22 Jan 2022 15:59:45 -0300
Subject: [PATCH 005/235] [BAEL-4806] - How to test an LDAP connection from a
client: code (#11664)
* working code
* added unit test
* [BAEL-4806] - How to test an LDAP connection from a client
Ticket: http://jira.baeldung.com/browse/BAEL-4806
Draft: https://drafts.baeldung.com/wp-admin/post.php?post=125004&action=edit
* removing draft project
* applying requested changes
* 1. renaming package to comply with java conventions;
* 2. breaking class into methods to enhance readability;
* 3. creating an 'execute' method so it's not necessary to call 'main';
* requested changes
* 1. adding final keyword to constants;
* 2. using diamond operator;
* Update LdapConnectionToolManualTest.java
---
.../connection/tool/LdapConnectionTool.java | 116 ++++++++++++++++++
.../tool/LdapConnectionToolManualTest.java | 87 +++++++++++++
.../test/resources/ldap-connection-tool.ldif | 34 +++++
3 files changed, 237 insertions(+)
create mode 100644 core-java-modules/core-java-jndi/src/main/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionTool.java
create mode 100644 core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionToolManualTest.java
create mode 100644 core-java-modules/core-java-jndi/src/test/resources/ldap-connection-tool.ldif
diff --git a/core-java-modules/core-java-jndi/src/main/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionTool.java b/core-java-modules/core-java-jndi/src/main/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionTool.java
new file mode 100644
index 0000000000..bf605cb160
--- /dev/null
+++ b/core-java-modules/core-java-jndi/src/main/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionTool.java
@@ -0,0 +1,116 @@
+package com.baeldung.jndi.ldap.connection.tool;
+
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+
+public class LdapConnectionTool {
+ private static final boolean DEBUG_MODE = Boolean.parseBoolean(System.getProperty("debug.mode", "false"));
+ private static final String QUERY = "query";
+
+ public static void main(String[] args) throws NamingException {
+ execute();
+ }
+
+ public static void execute() throws NamingException {
+ Hashtable env = createEnvironmentFromProperties();
+
+ DirContext context = null;
+ try {
+ context = connectToServer(env);
+
+ String query = env.get(LdapConnectionTool.QUERY);
+ if (query != null) {
+ executeQuery(context, query);
+ }
+ } catch (NamingException e) {
+ showErrorMessage(e);
+ } finally {
+ close(context);
+ }
+ }
+
+ private static void close(DirContext context) throws NamingException {
+ if (context != null) {
+ try {
+ context.close();
+ } catch (NamingException e) {
+ System.out.println(e.getMessage());
+
+ if (DEBUG_MODE)
+ throw e;
+ }
+ }
+ }
+
+ private static void showErrorMessage(NamingException e) throws NamingException {
+ System.out.println(e.getClass() + ": " + e.getMessage());
+ Throwable cause = e.getRootCause();
+ if (cause != null) {
+ System.out.println(cause.getClass() + ": " + cause.getMessage());
+ }
+
+ if (DEBUG_MODE)
+ throw e;
+ }
+
+ private static DirContext connectToServer(Hashtable env) throws NamingException {
+ String url = env.get(Context.PROVIDER_URL);
+
+ System.out.println("connecting to " + url + "...");
+ DirContext context = new InitialDirContext(env);
+ System.out.println("successfully connected to " + url);
+ return context;
+ }
+
+ private static void executeQuery(DirContext context, String query) throws NamingException {
+ Attributes attributes = context.getAttributes(query);
+ NamingEnumeration extends Attribute> all = attributes.getAll();
+ while (all.hasMoreElements()) {
+ Attribute next = all.next();
+
+ String key = next.getID();
+ Object value = next.get();
+
+ System.out.println(key + "=" + value);
+ }
+ }
+
+ private static Hashtable createEnvironmentFromProperties() {
+ String factory = System.getProperty("factory", "com.sun.jndi.ldap.LdapCtxFactory");
+ String authType = System.getProperty("authType", "none");
+ String url = System.getProperty("url");
+ String user = System.getProperty("user");
+ String password = System.getProperty("password");
+ String query = System.getProperty(QUERY, user);
+
+ if (url == null) {
+ throw new IllegalArgumentException("please provide 'url' system property");
+ }
+
+ Hashtable env = new Hashtable<>();
+ env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
+ env.put("com.sun.jndi.ldap.read.timeout", "5000");
+ env.put("com.sun.jndi.ldap.connect.timeout", "5000");
+ env.put(Context.SECURITY_AUTHENTICATION, authType);
+ env.put(Context.PROVIDER_URL, url);
+ if (query != null) {
+ env.put(LdapConnectionTool.QUERY, query);
+ }
+
+ if (user != null) {
+ if (password == null) {
+ throw new IllegalArgumentException("please provide 'password' system property");
+ }
+ env.put(Context.SECURITY_PRINCIPAL, user);
+ env.put(Context.SECURITY_CREDENTIALS, password);
+ }
+ return env;
+ }
+}
diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionToolManualTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionToolManualTest.java
new file mode 100644
index 0000000000..21898ddaf7
--- /dev/null
+++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/ldap/connection/tool/LdapConnectionToolManualTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.jndi.ldap.connection.tool;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+
+import javax.naming.NamingException;
+
+import org.apache.directory.server.annotations.CreateLdapServer;
+import org.apache.directory.server.annotations.CreateTransport;
+import org.apache.directory.server.core.annotations.ApplyLdifFiles;
+import org.apache.directory.server.core.annotations.CreateDS;
+import org.apache.directory.server.core.annotations.CreatePartition;
+import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
+import org.apache.directory.server.core.integ.FrameworkRunner;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(FrameworkRunner.class)
+@CreateLdapServer(allowAnonymousAccess = true, transports = { @CreateTransport(protocol = "LDAP", address = "localhost", port = 10389) })
+@CreateDS(allowAnonAccess = true, partitions = { @CreatePartition(name = "ldap-connection-tool", suffix = "dc=baeldung,dc=com") })
+@ApplyLdifFiles({ "ldap-connection-tool.ldif" })
+// class marked as manual test, as it has to run independently of other unit tests in the module
+public class LdapConnectionToolManualTest extends AbstractLdapTestUnit {
+ @Before
+ public void init() {
+ System.setProperty("debug.mode", "true");
+ System.clearProperty("url");
+ System.clearProperty("user");
+ System.clearProperty("password");
+ System.clearProperty("query");
+ }
+
+ @Test
+ public void whenNoUrlProvided_thenConnectionFails() throws Exception {
+ assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> LdapConnectionTool.execute());
+ }
+
+ @Test
+ public void givenUrlProvided_whenValidUrl_thenConnectionSucceeds() throws Exception {
+ System.setProperty("url", "ldap://localhost:10389");
+
+ assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void givenUrlProvided_whenInvalidUrl_thenConnectionFails() throws Exception {
+ System.setProperty("url", "ldap://unkownhost:10389");
+
+ assertThatExceptionOfType(NamingException.class).isThrownBy(() -> LdapConnectionTool.execute());
+ }
+
+ @Test
+ public void givenUserProvided_whenCorrectPassword_thenConnectionSucceeds() throws Exception {
+ System.setProperty("url", "ldap://localhost:10389");
+ System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
+ System.setProperty("password", "password");
+
+ assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void givenUserProvided_whenPasswordIsNull_thenConnectionFails() throws Exception {
+ System.setProperty("url", "ldap://localhost:10389");
+ System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
+
+ assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> LdapConnectionTool.execute());
+ }
+
+ @Test
+ public void whenOnlyValidQueryProvided_thenConnectionSucceeds() throws Exception {
+ System.setProperty("url", "ldap://localhost:10389");
+ System.setProperty("query", "uid=gauss,dc=baeldung,dc=com");
+
+ assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void givenUserProvided_whenQueryProvided_thenConnectionSucceeds() throws Exception {
+ System.setProperty("url", "ldap://localhost:10389");
+ System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
+ System.setProperty("password", "password");
+ System.setProperty("query", "uid=newton,dc=baeldung,dc=com");
+
+ assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
+ }
+}
diff --git a/core-java-modules/core-java-jndi/src/test/resources/ldap-connection-tool.ldif b/core-java-modules/core-java-jndi/src/test/resources/ldap-connection-tool.ldif
new file mode 100644
index 0000000000..9b68cb8a1d
--- /dev/null
+++ b/core-java-modules/core-java-jndi/src/test/resources/ldap-connection-tool.ldif
@@ -0,0 +1,34 @@
+version: 1
+dn: dc=baeldung,dc=com
+objectClass: top
+objectClass: dcObject
+objectClass: organization
+dc: baeldung
+o: baeldung.com
+
+dn: cn=admin,dc=baeldung,dc=com
+objectClass: simpleSecurityObject
+objectClass: organizationalRole
+cn: admin
+description: LDAP administrator
+userPassword: password
+
+dn: uid=newton,dc=baeldung,dc=com
+objectClass: inetOrgPerson
+objectClass: organizationalPerson
+objectClass: person
+objectClass: top
+cn: Isaac Newton
+sn: Newton
+uid: newton
+userPassword: password
+
+dn: uid=gauss,dc=baeldung,dc=com
+objectClass: inetOrgPerson
+objectClass: organizationalPerson
+objectClass: person
+objectClass: top
+cn: Carl Friedrich Gauss
+sn: Gauss
+uid: gauss
+userPassword: password
\ No newline at end of file
From db396b39a9916c70b2362eee2e83aae9769aaf10 Mon Sep 17 00:00:00 2001
From: Arash Ariani
Date: Sun, 23 Jan 2022 01:25:53 +0330
Subject: [PATCH 006/235] BAEL-5131: constructor specification is added c
(#11586)
* BAEL-5131: constructor specification is added c
* BAEL-5131: codes have been reformatted
* BAEL-5131: I've added a few minor changes over on this package.
* BAEL-5131: I've added a few minor changes over on this package.
---
.../rules/Employee.java | 24 +++++++++++++++++++
.../rules/Person.java | 14 +++++++++++
.../rules/RecursiveConstructorInvocation.java | 12 ++++++++++
.../simple/Person.java | 14 +++++++++++
.../superclass/Employee.java | 15 ++++++++++++
.../superclass/Person.java | 10 ++++++++
6 files changed, 89 insertions(+)
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Employee.java
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Person.java
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/RecursiveConstructorInvocation.java
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/simple/Person.java
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Employee.java
create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Person.java
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Employee.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Employee.java
new file mode 100644
index 0000000000..cb90aa3253
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Employee.java
@@ -0,0 +1,24 @@
+package com.baeldung.constructorspecification.rules;
+
+class Employee extends Person {
+
+ int id;
+
+ public Employee() {
+ super();
+ }
+
+ public Employee(String name) {
+ super(name);
+ }
+
+ public Employee(int id) {
+ this();
+ //super("John"); // syntax error
+ this.id = id;
+ }
+
+ public static void main(String[] args) {
+ new Employee(100);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Person.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Person.java
new file mode 100644
index 0000000000..9d96afdb01
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/Person.java
@@ -0,0 +1,14 @@
+package com.baeldung.constructorspecification.rules;
+
+class Person {
+
+ String name;
+
+ public Person() {
+ this("Arash");
+ }
+
+ public Person(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/RecursiveConstructorInvocation.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/RecursiveConstructorInvocation.java
new file mode 100644
index 0000000000..85ab2b6872
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/rules/RecursiveConstructorInvocation.java
@@ -0,0 +1,12 @@
+package com.baeldung.constructorspecification.rules;
+
+class RecursiveConstructorInvocation {
+
+ public RecursiveConstructorInvocation() {
+ RecursiveConstructorInvocation rci = new RecursiveConstructorInvocation();
+ }
+
+ public static void main(String[] args) {
+ new RecursiveConstructorInvocation(); // java.lang.StackOverflowError
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/simple/Person.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/simple/Person.java
new file mode 100644
index 0000000000..101df06150
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/simple/Person.java
@@ -0,0 +1,14 @@
+package com.baeldung.constructorspecification.simple;
+
+class Person {
+
+ String name;
+
+ public Person() {
+ this("Arash"); //ExplicitConstructorInvocation
+ }
+
+ public Person(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Employee.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Employee.java
new file mode 100644
index 0000000000..884fc4e404
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Employee.java
@@ -0,0 +1,15 @@
+package com.baeldung.constructorspecification.superclass;
+
+class Employee extends Person {
+
+ String name;
+
+ public Employee(int id) {
+ super(id); //ExplicitConstructorInvocation
+ }
+
+ public Employee(int id, String name) {
+ super(id);
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Person.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Person.java
new file mode 100644
index 0000000000..24bde9f613
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/constructorspecification/superclass/Person.java
@@ -0,0 +1,10 @@
+package com.baeldung.constructorspecification.superclass;
+
+class Person {
+
+ int id;
+
+ public Person(int id) {
+ this.id = id;
+ }
+}
\ No newline at end of file
From 7dde535340296eb1209f1daa3609f1e505756911 Mon Sep 17 00:00:00 2001
From: psevestre
Date: Sun, 23 Jan 2022 00:32:51 -0300
Subject: [PATCH 007/235] Bael 5260 (#11712)
* [BAEL-4849] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Remove extra comments
* WIP:Update to latest Boot
* WIP: Backend App
* WIP: resource server
* WIP: Change endpoint path
* WIP: Add Postman sample
* WIP: Add keycloak baeldung realm
* WIP: Change lombok scope
* WIP: Remove lombok dependency
* [BEAL-5260] README-OAuth
---
.../spring-cloud-gateway/README-OAuth.md | 40 +
.../spring-cloud-gateway/baeldung-realm.json | 2186 +++++++++++++++++
spring-cloud/spring-cloud-gateway/pom.xml | 84 +-
.../config/CustomPredicatesConfig.java | 23 +-
.../oauth/backend/QuotesApplication.java | 44 +
.../oauth/backend/domain/Quote.java | 35 +
.../oauth/backend/web/QuoteApi.java | 34 +
.../ResourceServerGatewayApplication.java | 13 +
.../KeycloakReactiveTokenInstrospector.java | 65 +
.../resources/application-oauth-client.yml | 26 +
.../resources/application-resource-server.yml | 19 +
.../resources/quotes-application.properties | 12 +
.../OAuth_Gateway.postman_collection.json | 203 ++
13 files changed, 2771 insertions(+), 13 deletions(-)
create mode 100644 spring-cloud/spring-cloud-gateway/README-OAuth.md
create mode 100644 spring-cloud/spring-cloud-gateway/baeldung-realm.json
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/QuotesApplication.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/domain/Quote.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/web/QuoteApi.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/server/ResourceServerGatewayApplication.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/shared/KeycloakReactiveTokenInstrospector.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-oauth-client.yml
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-resource-server.yml
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/quotes-application.properties
create mode 100644 spring-cloud/spring-cloud-gateway/src/test/postman/OAuth_Gateway.postman_collection.json
diff --git a/spring-cloud/spring-cloud-gateway/README-OAuth.md b/spring-cloud/spring-cloud-gateway/README-OAuth.md
new file mode 100644
index 0000000000..c186114589
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/README-OAuth.md
@@ -0,0 +1,40 @@
+# OAuth Test Setup
+
+In order to test the OAuth-secured gateway configurations, please follow the steps below
+
+## Keycloak setup
+
+1. Clone or download the https://github.com/Baeldung/spring-security-oauth project
+2. Replace the file `oauth-rest/oauth-authorization-server/src/main/resources/baeldung-realm.json`
+ with the one provider here
+3. Go to the oauth-rest/oauth-authorization-server folder and use maven to build the project
+4. Run the Keycloack service with `mvn spring-boot:run`
+5. Once Keycloak is up and running, go to `http://localhost:8083/auth/admin/master/console/#/realms/baeldung` and
+ log in with using `bael-admin/pass` as credentials
+6. Create two test users, so that one belongs to the *Golden Customers* group and the other doesn't.
+
+## Quotes backend
+
+Use the provided maven profile:
+
+```
+$ mvn spring-boot:run -Pquotes-application
+```
+
+## Gateway as Resource Server
+
+Use the provided maven profile:
+
+```
+$ mvn spring-boot:run -Pgateway-as-resource-server
+```
+
+## Gateway as OAuth 2.0 Client
+
+Use the provided maven profile:
+
+```
+$ mvn spring-boot:run -Pgateway-as-oauth-client
+```
+
+
diff --git a/spring-cloud/spring-cloud-gateway/baeldung-realm.json b/spring-cloud/spring-cloud-gateway/baeldung-realm.json
new file mode 100644
index 0000000000..4dad262568
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/baeldung-realm.json
@@ -0,0 +1,2186 @@
+{
+ "id": "baeldung",
+ "realm": "baeldung",
+ "notBefore": 0,
+ "revokeRefreshToken": false,
+ "refreshTokenMaxReuse": 0,
+ "accessTokenLifespan": 300,
+ "accessTokenLifespanForImplicitFlow": 900,
+ "ssoSessionIdleTimeout": 1800,
+ "ssoSessionMaxLifespan": 36000,
+ "ssoSessionIdleTimeoutRememberMe": 0,
+ "ssoSessionMaxLifespanRememberMe": 0,
+ "offlineSessionIdleTimeout": 2592000,
+ "offlineSessionMaxLifespanEnabled": false,
+ "offlineSessionMaxLifespan": 5184000,
+ "clientSessionIdleTimeout": 0,
+ "clientSessionMaxLifespan": 0,
+ "clientOfflineSessionIdleTimeout": 0,
+ "clientOfflineSessionMaxLifespan": 0,
+ "accessCodeLifespan": 60,
+ "accessCodeLifespanUserAction": 300,
+ "accessCodeLifespanLogin": 1800,
+ "actionTokenGeneratedByAdminLifespan": 43200,
+ "actionTokenGeneratedByUserLifespan": 300,
+ "enabled": true,
+ "sslRequired": "external",
+ "registrationAllowed": false,
+ "registrationEmailAsUsername": false,
+ "rememberMe": false,
+ "verifyEmail": false,
+ "loginWithEmailAllowed": true,
+ "duplicateEmailsAllowed": false,
+ "resetPasswordAllowed": false,
+ "editUsernameAllowed": false,
+ "bruteForceProtected": false,
+ "permanentLockout": false,
+ "maxFailureWaitSeconds": 900,
+ "minimumQuickLoginWaitSeconds": 60,
+ "waitIncrementSeconds": 60,
+ "quickLoginCheckMilliSeconds": 1000,
+ "maxDeltaTimeSeconds": 43200,
+ "failureFactor": 30,
+ "roles": {
+ "realm": [
+ {
+ "id": "2f721e46-398b-43ff-845f-3c747f1f69f5",
+ "name": "standard",
+ "description": "Standard customer",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ },
+ {
+ "id": "b8b1cb49-c953-4cb0-acea-62b24c4b6d30",
+ "name": "silver",
+ "description": "Silver customer",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ },
+ {
+ "id": "f44f5ba9-2393-4d2a-b581-81cf8dd7f245",
+ "name": "gold",
+ "description": "Gold customers",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ },
+ {
+ "id": "3b6109f5-6e5a-4578-83c3-791ec3e2bf9e",
+ "name": "offline_access",
+ "description": "${role_offline-access}",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ },
+ {
+ "id": "0dd6a8c7-d669-4941-9ea1-521980e9c53f",
+ "name": "uma_authorization",
+ "description": "${role_uma_authorization}",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ },
+ {
+ "id": "ca962095-7f9b-49e2-a190-e391a0d4b704",
+ "name": "user",
+ "composite": false,
+ "clientRole": false,
+ "containerId": "baeldung",
+ "attributes": {}
+ }
+ ],
+ "client": {
+ "newClient": [],
+ "realm-management": [
+ {
+ "id": "5d00243f-ceec-4b0c-995e-d86d5b8a0ae6",
+ "name": "view-clients",
+ "description": "${role_view-clients}",
+ "composite": true,
+ "composites": {
+ "client": {
+ "realm-management": [
+ "query-clients"
+ ]
+ }
+ },
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "941612de-bd85-47a5-8dfa-37c270dde28c",
+ "name": "view-authorization",
+ "description": "${role_view-authorization}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "5ea9810d-63cc-4277-9b32-ba8a3d3c6091",
+ "name": "manage-realm",
+ "description": "${role_manage-realm}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "8b7b0dd8-350b-473e-b8cd-8acad34f1358",
+ "name": "query-clients",
+ "description": "${role_query-clients}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "0f8e5ee8-b014-4b7c-9b69-50f46abcba5f",
+ "name": "query-groups",
+ "description": "${role_query-groups}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "911b1489-9383-4734-b134-bf49bf992ce9",
+ "name": "manage-clients",
+ "description": "${role_manage-clients}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "5d48274c-bd6b-4c26-ad54-f1a2254beac0",
+ "name": "view-realm",
+ "description": "${role_view-realm}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "3ea43b64-316f-4693-8346-9ee78b24adaf",
+ "name": "manage-identity-providers",
+ "description": "${role_manage-identity-providers}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "49735614-96ec-49b2-98fe-3af9bcd1a33a",
+ "name": "create-client",
+ "description": "${role_create-client}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "e8f8c3cc-0ff1-4f72-a271-db6821a3cdb6",
+ "name": "manage-users",
+ "description": "${role_manage-users}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "387418b1-4f80-4b00-b9dd-805ca041f805",
+ "name": "view-identity-providers",
+ "description": "${role_view-identity-providers}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "427c27d4-521a-464b-a0df-16d7f537e8d5",
+ "name": "realm-admin",
+ "description": "${role_realm-admin}",
+ "composite": true,
+ "composites": {
+ "client": {
+ "realm-management": [
+ "view-clients",
+ "view-authorization",
+ "query-groups",
+ "manage-realm",
+ "query-clients",
+ "manage-clients",
+ "view-realm",
+ "manage-identity-providers",
+ "create-client",
+ "manage-users",
+ "view-identity-providers",
+ "query-users",
+ "query-realms",
+ "view-users",
+ "impersonation",
+ "manage-authorization",
+ "manage-events",
+ "view-events"
+ ]
+ }
+ },
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "a574cf01-03e4-4573-ab9e-276d13a1ce8d",
+ "name": "query-users",
+ "description": "${role_query-users}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "c3a253a8-a1b6-4d38-9677-f728f32482ad",
+ "name": "query-realms",
+ "description": "${role_query-realms}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "f3cb93da-273e-419a-b2f4-93f09896abcf",
+ "name": "view-users",
+ "description": "${role_view-users}",
+ "composite": true,
+ "composites": {
+ "client": {
+ "realm-management": [
+ "query-users",
+ "query-groups"
+ ]
+ }
+ },
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "6eedf2b7-50ef-4495-a89b-54aef751b7fa",
+ "name": "manage-authorization",
+ "description": "${role_manage-authorization}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "0332e99b-3dfc-4193-9e13-5728f8f3e6d6",
+ "name": "impersonation",
+ "description": "${role_impersonation}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "b690cb9c-0f4a-4be5-ade0-b40443d8149d",
+ "name": "view-events",
+ "description": "${role_view-events}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ },
+ {
+ "id": "aac3def5-f193-4a6c-9065-1667a0746a8a",
+ "name": "manage-events",
+ "description": "${role_manage-events}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "attributes": {}
+ }
+ ],
+ "security-admin-console": [],
+ "quotes-client": [],
+ "admin-cli": [],
+ "account-console": [],
+ "broker": [
+ {
+ "id": "397b5703-4c81-48fd-a24c-a7e8177ef657",
+ "name": "read-token",
+ "description": "${role_read-token}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "4b9609f0-48d1-4e71-9381-2ecec08616f9",
+ "attributes": {}
+ }
+ ],
+ "account": [
+ {
+ "id": "8daa8096-d14e-4d1c-ad1f-83f822016aa1",
+ "name": "manage-account",
+ "description": "${role_manage-account}",
+ "composite": true,
+ "composites": {
+ "client": {
+ "account": [
+ "manage-account-links"
+ ]
+ }
+ },
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ },
+ {
+ "id": "15f0d8be-932b-4565-8ad0-e8aa170093dd",
+ "name": "view-consent",
+ "description": "${role_view-consent}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ },
+ {
+ "id": "c5aa697c-bf87-47c6-bd94-9121b72420b9",
+ "name": "view-applications",
+ "description": "${role_view-applications}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ },
+ {
+ "id": "f0b3bbe4-aec1-4227-b9d3-2c314d612a04",
+ "name": "manage-consent",
+ "description": "${role_manage-consent}",
+ "composite": true,
+ "composites": {
+ "client": {
+ "account": [
+ "view-consent"
+ ]
+ }
+ },
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ },
+ {
+ "id": "948269c7-a69c-4c82-a7f3-88868713dfd9",
+ "name": "manage-account-links",
+ "description": "${role_manage-account-links}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ },
+ {
+ "id": "aed18201-2433-4998-8fa3-0979b0b31c10",
+ "name": "view-profile",
+ "description": "${role_view-profile}",
+ "composite": false,
+ "clientRole": true,
+ "containerId": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "attributes": {}
+ }
+ ]
+ }
+ },
+ "groups": [
+ {
+ "id": "635c3314-f15f-4c02-bcb7-8739fd4c21b7",
+ "name": "golden_customers",
+ "path": "/golden_customers",
+ "attributes": {},
+ "realmRoles": [
+ "gold"
+ ],
+ "clientRoles": {},
+ "subGroups": []
+ },
+ {
+ "id": "279c5ec4-0588-4884-91c1-2697ed5c9826",
+ "name": "silver_customers",
+ "path": "/silver_customers",
+ "attributes": {},
+ "realmRoles": [
+ "silver"
+ ],
+ "clientRoles": {},
+ "subGroups": []
+ }
+ ],
+ "defaultRoles": [
+ "uma_authorization",
+ "offline_access"
+ ],
+ "requiredCredentials": [
+ "password"
+ ],
+ "otpPolicyType": "totp",
+ "otpPolicyAlgorithm": "HmacSHA1",
+ "otpPolicyInitialCounter": 0,
+ "otpPolicyDigits": 6,
+ "otpPolicyLookAheadWindow": 1,
+ "otpPolicyPeriod": 30,
+ "otpSupportedApplications": [
+ "FreeOTP",
+ "Google Authenticator"
+ ],
+ "webAuthnPolicyRpEntityName": "keycloak",
+ "webAuthnPolicySignatureAlgorithms": [
+ "ES256"
+ ],
+ "webAuthnPolicyRpId": "",
+ "webAuthnPolicyAttestationConveyancePreference": "not specified",
+ "webAuthnPolicyAuthenticatorAttachment": "not specified",
+ "webAuthnPolicyRequireResidentKey": "not specified",
+ "webAuthnPolicyUserVerificationRequirement": "not specified",
+ "webAuthnPolicyCreateTimeout": 0,
+ "webAuthnPolicyAvoidSameAuthenticatorRegister": false,
+ "webAuthnPolicyAcceptableAaguids": [],
+ "webAuthnPolicyPasswordlessRpEntityName": "keycloak",
+ "webAuthnPolicyPasswordlessSignatureAlgorithms": [
+ "ES256"
+ ],
+ "webAuthnPolicyPasswordlessRpId": "",
+ "webAuthnPolicyPasswordlessAttestationConveyancePreference": "not specified",
+ "webAuthnPolicyPasswordlessAuthenticatorAttachment": "not specified",
+ "webAuthnPolicyPasswordlessRequireResidentKey": "not specified",
+ "webAuthnPolicyPasswordlessUserVerificationRequirement": "not specified",
+ "webAuthnPolicyPasswordlessCreateTimeout": 0,
+ "webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister": false,
+ "webAuthnPolicyPasswordlessAcceptableAaguids": [],
+ "scopeMappings": [
+ {
+ "clientScope": "offline_access",
+ "roles": [
+ "offline_access"
+ ]
+ }
+ ],
+ "clientScopeMappings": {
+ "account": [
+ {
+ "client": "account-console",
+ "roles": [
+ "manage-account"
+ ]
+ }
+ ]
+ },
+ "clients": [
+ {
+ "id": "12eebf0b-a3eb-49f8-9ecf-173cf8a00145",
+ "clientId": "account",
+ "name": "${client_account}",
+ "rootUrl": "${authBaseUrl}",
+ "baseUrl": "/realms/baeldung/account/",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "defaultRoles": [
+ "manage-account",
+ "view-profile"
+ ],
+ "redirectUris": [
+ "/realms/baeldung/account/*"
+ ],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": false,
+ "serviceAccountsEnabled": false,
+ "publicClient": false,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {},
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "8209784b-8540-43c2-aece-241acf12ea5a",
+ "clientId": "account-console",
+ "name": "${client_account-console}",
+ "rootUrl": "${authBaseUrl}",
+ "baseUrl": "/realms/baeldung/account/",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [
+ "/realms/baeldung/account/*"
+ ],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": false,
+ "serviceAccountsEnabled": false,
+ "publicClient": true,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {
+ "pkce.code.challenge.method": "S256"
+ },
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "protocolMappers": [
+ {
+ "id": "58395b96-1718-4787-8f92-74577e2bfc30",
+ "name": "audience resolve",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-audience-resolve-mapper",
+ "consentRequired": false,
+ "config": {}
+ }
+ ],
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "13d76feb-d762-4409-bb84-7a75bc395a61",
+ "clientId": "admin-cli",
+ "name": "${client_admin-cli}",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": false,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": true,
+ "serviceAccountsEnabled": false,
+ "publicClient": true,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {},
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "4b9609f0-48d1-4e71-9381-2ecec08616f9",
+ "clientId": "broker",
+ "name": "${client_broker}",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": false,
+ "serviceAccountsEnabled": false,
+ "publicClient": false,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {},
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "b88ce206-63d6-43b6-87c9-ea09d8c02f32",
+ "clientId": "newClient",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [
+ "http://localhost:8082/new-client/login/oauth2/code/custom",
+ "http://localhost:8089/",
+ "http://localhost:8089/auth/redirect/"
+ ],
+ "webOrigins": [
+ "+"
+ ],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": true,
+ "directAccessGrantsEnabled": true,
+ "serviceAccountsEnabled": false,
+ "publicClient": false,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {
+ "saml.assertion.signature": "false",
+ "saml.force.post.binding": "false",
+ "saml.multivalued.roles": "false",
+ "saml.encrypt": "false",
+ "saml.server.signature": "false",
+ "saml.server.signature.keyinfo.ext": "false",
+ "exclude.session.state.from.auth.response": "false",
+ "saml_force_name_id_format": "false",
+ "saml.client.signature": "false",
+ "tls.client.certificate.bound.access.tokens": "false",
+ "saml.authnstatement": "false",
+ "display.on.consent.screen": "false",
+ "saml.onetimeuse.condition": "false"
+ },
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": true,
+ "nodeReRegistrationTimeout": -1,
+ "defaultClientScopes": [
+ "role_list",
+ "profile"
+ ],
+ "optionalClientScopes": [
+ "web-origins",
+ "address",
+ "read",
+ "phone",
+ "roles",
+ "offline_access",
+ "microprofile-jwt",
+ "write",
+ "email"
+ ]
+ },
+ {
+ "id": "5898f71f-b91e-4c3f-9c86-48de0e8665c4",
+ "clientId": "quotes-client",
+ "name": "Quotes Client",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "0e082231-a70d-48e8-b8a5-fbfb743041b6",
+ "redirectUris": [
+ "http://localhost:8082/*",
+ "http://localhost:8087/*"
+ ],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": true,
+ "serviceAccountsEnabled": false,
+ "publicClient": false,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {
+ "saml.assertion.signature": "false",
+ "saml.multivalued.roles": "false",
+ "saml.force.post.binding": "false",
+ "saml.encrypt": "false",
+ "saml.server.signature": "false",
+ "saml.server.signature.keyinfo.ext": "false",
+ "exclude.session.state.from.auth.response": "false",
+ "saml_force_name_id_format": "false",
+ "saml.client.signature": "false",
+ "tls.client.certificate.bound.access.tokens": "false",
+ "saml.authnstatement": "false",
+ "display.on.consent.screen": "false",
+ "saml.onetimeuse.condition": "false"
+ },
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": true,
+ "nodeReRegistrationTimeout": -1,
+ "protocolMappers": [
+ {
+ "id": "008d32b5-ea7b-4739-89af-e90fe137bda9",
+ "name": "realm roles",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-realm-role-mapper",
+ "consentRequired": false,
+ "config": {
+ "user.attribute": "foo",
+ "access.token.claim": "true",
+ "claim.name": "realm_access.roles",
+ "jsonType.label": "String",
+ "multivalued": "true"
+ }
+ }
+ ],
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "6a4bfbd0-576d-4778-af56-56f876647355",
+ "clientId": "realm-management",
+ "name": "${client_realm-management}",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [],
+ "webOrigins": [],
+ "notBefore": 0,
+ "bearerOnly": true,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": false,
+ "serviceAccountsEnabled": false,
+ "publicClient": false,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {},
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ },
+ {
+ "id": "8e358d2f-b085-4243-8e6e-c175431e5eeb",
+ "clientId": "security-admin-console",
+ "name": "${client_security-admin-console}",
+ "rootUrl": "${authAdminUrl}",
+ "baseUrl": "/admin/baeldung/console/",
+ "surrogateAuthRequired": false,
+ "enabled": true,
+ "alwaysDisplayInConsole": false,
+ "clientAuthenticatorType": "client-secret",
+ "secret": "**********",
+ "redirectUris": [
+ "/admin/baeldung/console/*"
+ ],
+ "webOrigins": [
+ "+"
+ ],
+ "notBefore": 0,
+ "bearerOnly": false,
+ "consentRequired": false,
+ "standardFlowEnabled": true,
+ "implicitFlowEnabled": false,
+ "directAccessGrantsEnabled": false,
+ "serviceAccountsEnabled": false,
+ "publicClient": true,
+ "frontchannelLogout": false,
+ "protocol": "openid-connect",
+ "attributes": {
+ "pkce.code.challenge.method": "S256"
+ },
+ "authenticationFlowBindingOverrides": {},
+ "fullScopeAllowed": false,
+ "nodeReRegistrationTimeout": 0,
+ "protocolMappers": [
+ {
+ "id": "9cfca9ee-493d-4b5e-8170-2d364149de59",
+ "name": "locale",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "locale",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "locale",
+ "jsonType.label": "String"
+ }
+ }
+ ],
+ "defaultClientScopes": [
+ "web-origins",
+ "role_list",
+ "roles",
+ "profile",
+ "email"
+ ],
+ "optionalClientScopes": [
+ "address",
+ "phone",
+ "offline_access",
+ "microprofile-jwt"
+ ]
+ }
+ ],
+ "clientScopes": [
+ {
+ "id": "77c7e29d-1a22-4419-bbfb-4a62bb033449",
+ "name": "address",
+ "description": "OpenID Connect built-in scope: address",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true",
+ "consent.screen.text": "${addressScopeConsentText}"
+ },
+ "protocolMappers": [
+ {
+ "id": "94e1879d-b49e-4178-96e0-bf8d7f32c160",
+ "name": "address",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-address-mapper",
+ "consentRequired": false,
+ "config": {
+ "user.attribute.formatted": "formatted",
+ "user.attribute.country": "country",
+ "user.attribute.postal_code": "postal_code",
+ "userinfo.token.claim": "true",
+ "user.attribute.street": "street",
+ "id.token.claim": "true",
+ "user.attribute.region": "region",
+ "access.token.claim": "true",
+ "user.attribute.locality": "locality"
+ }
+ }
+ ]
+ },
+ {
+ "id": "b3526ac1-10e2-4344-8621-9c5a0853e97a",
+ "name": "email",
+ "description": "OpenID Connect built-in scope: email",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true",
+ "consent.screen.text": "${emailScopeConsentText}"
+ },
+ "protocolMappers": [
+ {
+ "id": "d30270dc-baa6-455a-8ff6-ddccf8a78d86",
+ "name": "email verified",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "emailVerified",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "email_verified",
+ "jsonType.label": "boolean"
+ }
+ },
+ {
+ "id": "f5b1684d-e479-4134-8578-457fa64717da",
+ "name": "email",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "email",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "email",
+ "jsonType.label": "String"
+ }
+ }
+ ]
+ },
+ {
+ "id": "c658ae14-e96a-4745-b21b-2ed5c4c63f5f",
+ "name": "microprofile-jwt",
+ "description": "Microprofile - JWT built-in scope",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "false"
+ },
+ "protocolMappers": [
+ {
+ "id": "959521bc-5ffd-465b-95f2-5b0c20d1909c",
+ "name": "upn",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "username",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "upn",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "07b8550c-b298-4cce-9ffb-900182575b76",
+ "name": "groups",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-realm-role-mapper",
+ "consentRequired": false,
+ "config": {
+ "multivalued": "true",
+ "userinfo.token.claim": "true",
+ "user.attribute": "foo",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "groups",
+ "jsonType.label": "String"
+ }
+ }
+ ]
+ },
+ {
+ "id": "569b3d44-4ecd-4768-a58c-70ff38f4b4fe",
+ "name": "offline_access",
+ "description": "OpenID Connect built-in scope: offline_access",
+ "protocol": "openid-connect",
+ "attributes": {
+ "consent.screen.text": "${offlineAccessScopeConsentText}",
+ "display.on.consent.screen": "true"
+ }
+ },
+ {
+ "id": "a3e7b19d-df6c-437e-9eea-06fec1becb2f",
+ "name": "phone",
+ "description": "OpenID Connect built-in scope: phone",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true",
+ "consent.screen.text": "${phoneScopeConsentText}"
+ },
+ "protocolMappers": [
+ {
+ "id": "72a070f7-4363-4c88-8153-6fd2d12b9b04",
+ "name": "phone number verified",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "phoneNumberVerified",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "phone_number_verified",
+ "jsonType.label": "boolean"
+ }
+ },
+ {
+ "id": "24b42c6d-a93c-4aa1-9a03-2a2b55954c13",
+ "name": "phone number",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "phoneNumber",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "phone_number",
+ "jsonType.label": "String"
+ }
+ }
+ ]
+ },
+ {
+ "id": "ba8c9950-fd0b-4434-8be6-b58456d7b6d4",
+ "name": "profile",
+ "description": "OpenID Connect built-in scope: profile",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true",
+ "consent.screen.text": "${profileScopeConsentText}"
+ },
+ "protocolMappers": [
+ {
+ "id": "0a9ddd71-309c-40f0-8ea6-a0791070c6ed",
+ "name": "profile",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "profile",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "profile",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "fbf53bbd-1ad0-4bf8-8030-50f81696d8ee",
+ "name": "nickname",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "nickname",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "nickname",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "423be2cd-42c0-462e-9030-18f9b28ff2d3",
+ "name": "gender",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "gender",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "gender",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "53eb9006-4b81-474a-8b60-80f775d54b63",
+ "name": "picture",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "picture",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "picture",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "4d8bc82a-eaeb-499e-8eb2-0f1dcbe91699",
+ "name": "locale",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "locale",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "locale",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "d3b25485-4042-419d-afff-cfd63a76e229",
+ "name": "full name",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-full-name-mapper",
+ "consentRequired": false,
+ "config": {
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "userinfo.token.claim": "true"
+ }
+ },
+ {
+ "id": "422cfa5a-f2f4-4f36-82df-91b47ae1ea50",
+ "name": "given name",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "firstName",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "given_name",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "3f2863c1-d98d-45b5-b08f-af9c4d9c10f8",
+ "name": "website",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "website",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "website",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "c98c063d-eee4-41a0-9130-595afd709d1f",
+ "name": "middle name",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "middleName",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "middle_name",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "8dbed80a-d672-4185-8dda-4bba2a56ec83",
+ "name": "family name",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "lastName",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "family_name",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "5e5c690c-93cf-489d-a054-b109eab8911b",
+ "name": "updated at",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "updatedAt",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "updated_at",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "3b985202-af8a-42f1-ac5f-0966a404f5d7",
+ "name": "birthdate",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "birthdate",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "birthdate",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "6eafd1b3-7121-4919-ad1e-039fa58acc32",
+ "name": "username",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-property-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "username",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "preferred_username",
+ "jsonType.label": "String"
+ }
+ },
+ {
+ "id": "73cba925-8c31-443f-9601-b1514e6396c1",
+ "name": "zoneinfo",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-attribute-mapper",
+ "consentRequired": false,
+ "config": {
+ "userinfo.token.claim": "true",
+ "user.attribute": "zoneinfo",
+ "id.token.claim": "true",
+ "access.token.claim": "true",
+ "claim.name": "zoneinfo",
+ "jsonType.label": "String"
+ }
+ }
+ ]
+ },
+ {
+ "id": "c1a2eb23-25c6-4be7-a791-bbdca99c83f7",
+ "name": "read",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true"
+ }
+ },
+ {
+ "id": "18e141bf-dabe-4858-879c-dbc439cdead4",
+ "name": "role_list",
+ "description": "SAML role list",
+ "protocol": "saml",
+ "attributes": {
+ "consent.screen.text": "${samlRoleListScopeConsentText}",
+ "display.on.consent.screen": "true"
+ },
+ "protocolMappers": [
+ {
+ "id": "10cbe37f-0198-4d65-bc8a-bfe5ad8145d1",
+ "name": "role list",
+ "protocol": "saml",
+ "protocolMapper": "saml-role-list-mapper",
+ "consentRequired": false,
+ "config": {
+ "single": "false",
+ "attribute.nameformat": "Basic",
+ "attribute.name": "Role"
+ }
+ }
+ ]
+ },
+ {
+ "id": "111ed87a-5fd3-4cee-96df-8dbfb88cfdc0",
+ "name": "roles",
+ "description": "OpenID Connect scope for add user roles to the access token",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "false",
+ "display.on.consent.screen": "true",
+ "consent.screen.text": "${rolesScopeConsentText}"
+ },
+ "protocolMappers": [
+ {
+ "id": "24924d8d-6071-4a93-b40f-326176cb335e",
+ "name": "realm roles",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-realm-role-mapper",
+ "consentRequired": false,
+ "config": {
+ "user.attribute": "foo",
+ "access.token.claim": "true",
+ "claim.name": "realm_access.roles",
+ "jsonType.label": "String",
+ "multivalued": "true"
+ }
+ },
+ {
+ "id": "2f6a9bdf-3758-484c-996d-e4f93555559f",
+ "name": "audience resolve",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-audience-resolve-mapper",
+ "consentRequired": false,
+ "config": {}
+ },
+ {
+ "id": "804d4798-d9a3-4fd3-8b28-d12142e8cb3d",
+ "name": "client roles",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-usermodel-client-role-mapper",
+ "consentRequired": false,
+ "config": {
+ "user.attribute": "foo",
+ "access.token.claim": "true",
+ "claim.name": "resource_access.${client_id}.roles",
+ "jsonType.label": "String",
+ "multivalued": "true"
+ }
+ }
+ ]
+ },
+ {
+ "id": "51d49314-b511-43e0-9258-bfb873758a78",
+ "name": "web-origins",
+ "description": "OpenID Connect scope for add allowed web origins to the access token",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "false",
+ "display.on.consent.screen": "false",
+ "consent.screen.text": ""
+ },
+ "protocolMappers": [
+ {
+ "id": "2b384cd0-9e85-4a87-8eeb-2b480b0587b7",
+ "name": "allowed web origins",
+ "protocol": "openid-connect",
+ "protocolMapper": "oidc-allowed-origins-mapper",
+ "consentRequired": false,
+ "config": {}
+ }
+ ]
+ },
+ {
+ "id": "c3e253fb-7361-47cf-9d4a-86245686fdf1",
+ "name": "write",
+ "protocol": "openid-connect",
+ "attributes": {
+ "include.in.token.scope": "true",
+ "display.on.consent.screen": "true"
+ }
+ }
+ ],
+ "defaultDefaultClientScopes": [
+ "roles",
+ "role_list",
+ "web-origins",
+ "email",
+ "profile"
+ ],
+ "defaultOptionalClientScopes": [
+ "offline_access",
+ "address",
+ "phone",
+ "microprofile-jwt"
+ ],
+ "browserSecurityHeaders": {
+ "contentSecurityPolicyReportOnly": "",
+ "xContentTypeOptions": "nosniff",
+ "xRobotsTag": "none",
+ "xFrameOptions": "SAMEORIGIN",
+ "contentSecurityPolicy": "frame-src 'self'; frame-ancestors 'self'; object-src 'none';",
+ "xXSSProtection": "1; mode=block",
+ "strictTransportSecurity": "max-age=31536000; includeSubDomains"
+ },
+ "smtpServer": {},
+ "eventsEnabled": false,
+ "eventsListeners": [
+ "jboss-logging"
+ ],
+ "enabledEventTypes": [],
+ "adminEventsEnabled": false,
+ "adminEventsDetailsEnabled": false,
+ "components": {
+ "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy": [
+ {
+ "id": "84305f42-4b6d-4b0a-ac7c-53e406e3ac63",
+ "name": "Allowed Client Scopes",
+ "providerId": "allowed-client-templates",
+ "subType": "authenticated",
+ "subComponents": {},
+ "config": {
+ "allow-default-scopes": [
+ "true"
+ ]
+ }
+ },
+ {
+ "id": "c7c38a95-744f-4558-a403-9cf692fe1944",
+ "name": "Allowed Client Scopes",
+ "providerId": "allowed-client-templates",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {
+ "allow-default-scopes": [
+ "true"
+ ]
+ }
+ },
+ {
+ "id": "365b2899-befe-4417-b89b-562650ec4446",
+ "name": "Full Scope Disabled",
+ "providerId": "scope",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {}
+ },
+ {
+ "id": "81c32244-7921-43e9-9356-a3469259b78c",
+ "name": "Trusted Hosts",
+ "providerId": "trusted-hosts",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {
+ "host-sending-registration-request-must-match": [
+ "true"
+ ],
+ "client-uris-must-match": [
+ "true"
+ ]
+ }
+ },
+ {
+ "id": "d09b2147-afea-4f7f-a49c-0aec7eee10de",
+ "name": "Max Clients Limit",
+ "providerId": "max-clients",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {
+ "max-clients": [
+ "200"
+ ]
+ }
+ },
+ {
+ "id": "41ffde1b-72a2-416f-87a7-94989e940dc0",
+ "name": "Allowed Protocol Mapper Types",
+ "providerId": "allowed-protocol-mappers",
+ "subType": "authenticated",
+ "subComponents": {},
+ "config": {
+ "allowed-protocol-mapper-types": [
+ "saml-user-property-mapper",
+ "oidc-address-mapper",
+ "oidc-usermodel-property-mapper",
+ "oidc-full-name-mapper",
+ "oidc-sha256-pairwise-sub-mapper",
+ "saml-role-list-mapper",
+ "oidc-usermodel-attribute-mapper",
+ "saml-user-attribute-mapper"
+ ]
+ }
+ },
+ {
+ "id": "76075388-2782-4656-a986-313493239a9f",
+ "name": "Consent Required",
+ "providerId": "consent-required",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {}
+ },
+ {
+ "id": "3caaf57a-9cd7-48c1-b709-b40b887414f7",
+ "name": "Allowed Protocol Mapper Types",
+ "providerId": "allowed-protocol-mappers",
+ "subType": "anonymous",
+ "subComponents": {},
+ "config": {
+ "allowed-protocol-mapper-types": [
+ "oidc-usermodel-attribute-mapper",
+ "saml-user-property-mapper",
+ "oidc-usermodel-property-mapper",
+ "oidc-full-name-mapper",
+ "saml-user-attribute-mapper",
+ "oidc-address-mapper",
+ "saml-role-list-mapper",
+ "oidc-sha256-pairwise-sub-mapper"
+ ]
+ }
+ }
+ ],
+ "org.keycloak.keys.KeyProvider": [
+ {
+ "id": "d67a940a-52e4-44a5-9f69-6ffdd67a188f",
+ "name": "rsa-generated",
+ "providerId": "rsa-generated",
+ "subComponents": {},
+ "config": {
+ "priority": [
+ "100"
+ ]
+ }
+ },
+ {
+ "id": "48d40de3-6234-42e8-9449-f68f56abb54b",
+ "name": "aes-generated",
+ "providerId": "aes-generated",
+ "subComponents": {},
+ "config": {
+ "priority": [
+ "100"
+ ]
+ }
+ },
+ {
+ "id": "52ea1c5d-2a30-459f-b66a-249f298b32f8",
+ "name": "hmac-generated",
+ "providerId": "hmac-generated",
+ "subComponents": {},
+ "config": {
+ "priority": [
+ "100"
+ ],
+ "algorithm": [
+ "HS256"
+ ]
+ }
+ }
+ ]
+ },
+ "internationalizationEnabled": false,
+ "supportedLocales": [],
+ "authenticationFlows": [
+ {
+ "id": "b35b726e-c1cc-4a31-8670-8c858c088498",
+ "alias": "Handle Existing Account",
+ "description": "Handle what to do if there is existing account with same email/username like authenticated identity provider",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "idp-confirm-link",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "flowAlias": "Handle Existing Account - Alternatives - 0",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "b7cb4b8c-0064-4c6b-95ee-d7f50011bae7",
+ "alias": "Handle Existing Account - Alternatives - 0",
+ "description": "Subflow of Handle Existing Account with alternative executions",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "idp-email-verification",
+ "requirement": "ALTERNATIVE",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "ALTERNATIVE",
+ "priority": 20,
+ "flowAlias": "Verify Existing Account by Re-authentication",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "2576bf21-a516-4e22-8ed8-8a1a3d35c06a",
+ "alias": "Verify Existing Account by Re-authentication",
+ "description": "Reauthentication of existing account",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "idp-username-password-form",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "CONDITIONAL",
+ "priority": 20,
+ "flowAlias": "Verify Existing Account by Re-authentication - auth-otp-form - Conditional",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "867b0355-c2b0-4f4e-b535-09406e2bc086",
+ "alias": "Verify Existing Account by Re-authentication - auth-otp-form - Conditional",
+ "description": "Flow to determine if the auth-otp-form authenticator should be used or not.",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "conditional-user-configured",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "auth-otp-form",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "52e45a6a-292f-4a34-9c02-7f97d9997a9c",
+ "alias": "browser",
+ "description": "browser based authentication",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "auth-cookie",
+ "requirement": "ALTERNATIVE",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "auth-spnego",
+ "requirement": "DISABLED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "identity-provider-redirector",
+ "requirement": "ALTERNATIVE",
+ "priority": 25,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "ALTERNATIVE",
+ "priority": 30,
+ "flowAlias": "forms",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "ef818d24-fb06-418a-a093-16239068cb58",
+ "alias": "clients",
+ "description": "Base authentication for clients",
+ "providerId": "client-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "client-secret",
+ "requirement": "ALTERNATIVE",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "client-jwt",
+ "requirement": "ALTERNATIVE",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "client-secret-jwt",
+ "requirement": "ALTERNATIVE",
+ "priority": 30,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "client-x509",
+ "requirement": "ALTERNATIVE",
+ "priority": 40,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "f7864004-be4b-40f2-8534-454981f09f98",
+ "alias": "direct grant",
+ "description": "OpenID Connect Resource Owner Grant",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "direct-grant-validate-username",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "direct-grant-validate-password",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "CONDITIONAL",
+ "priority": 30,
+ "flowAlias": "direct grant - direct-grant-validate-otp - Conditional",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "233225f2-78b0-4756-9568-a775ea7cc975",
+ "alias": "direct grant - direct-grant-validate-otp - Conditional",
+ "description": "Flow to determine if the direct-grant-validate-otp authenticator should be used or not.",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "conditional-user-configured",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "direct-grant-validate-otp",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "2787939c-3312-4d56-9d61-22a71947e154",
+ "alias": "docker auth",
+ "description": "Used by Docker clients to authenticate against the IDP",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "docker-http-basic-authenticator",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "c80ca473-6e65-4140-a9d1-035414546bfb",
+ "alias": "first broker login",
+ "description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticatorConfig": "review profile config",
+ "authenticator": "idp-review-profile",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "flowAlias": "first broker login - Alternatives - 0",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "700a71e1-f176-432e-9e70-ccb06d539730",
+ "alias": "first broker login - Alternatives - 0",
+ "description": "Subflow of first broker login with alternative executions",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticatorConfig": "create unique user config",
+ "authenticator": "idp-create-user-if-unique",
+ "requirement": "ALTERNATIVE",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "ALTERNATIVE",
+ "priority": 20,
+ "flowAlias": "Handle Existing Account",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "13cd2ee9-8ebb-4651-8a9d-535d4020d889",
+ "alias": "forms",
+ "description": "Username, password, otp and other auth forms.",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "auth-username-password-form",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "CONDITIONAL",
+ "priority": 20,
+ "flowAlias": "forms - auth-otp-form - Conditional",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "80067ebf-72b9-4ba5-abc3-161dfdd53938",
+ "alias": "forms - auth-otp-form - Conditional",
+ "description": "Flow to determine if the auth-otp-form authenticator should be used or not.",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "conditional-user-configured",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "auth-otp-form",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "269354b1-7dd7-46ff-8a69-084cd2c7be80",
+ "alias": "http challenge",
+ "description": "An authentication flow based on challenge-response HTTP Authentication Schemes",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "no-cookie-redirect",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "basic-auth",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "basic-auth-otp",
+ "requirement": "DISABLED",
+ "priority": 30,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "auth-spnego",
+ "requirement": "DISABLED",
+ "priority": 40,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "c5fa64a0-e784-490f-8879-0e8a209e3636",
+ "alias": "registration",
+ "description": "registration flow",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "registration-page-form",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "flowAlias": "registration form",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "bc48f897-4d16-49a8-be70-183c7867e20a",
+ "alias": "registration form",
+ "description": "registration form",
+ "providerId": "form-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "registration-user-creation",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "registration-profile-action",
+ "requirement": "REQUIRED",
+ "priority": 40,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "registration-password-action",
+ "requirement": "REQUIRED",
+ "priority": 50,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "registration-recaptcha-action",
+ "requirement": "DISABLED",
+ "priority": 60,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "fddaba41-87b1-40d1-b147-f062c38e39ad",
+ "alias": "reset credentials",
+ "description": "Reset credentials for a user if they forgot their password or something",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "reset-credentials-choose-user",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "reset-credential-email",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "reset-password",
+ "requirement": "REQUIRED",
+ "priority": 30,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "requirement": "CONDITIONAL",
+ "priority": 40,
+ "flowAlias": "reset credentials - reset-otp - Conditional",
+ "userSetupAllowed": false,
+ "autheticatorFlow": true
+ }
+ ]
+ },
+ {
+ "id": "6b9fa295-1eb4-48b0-a286-b17ebd6be7e1",
+ "alias": "reset credentials - reset-otp - Conditional",
+ "description": "Flow to determine if the reset-otp authenticator should be used or not.",
+ "providerId": "basic-flow",
+ "topLevel": false,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "conditional-user-configured",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ },
+ {
+ "authenticator": "reset-otp",
+ "requirement": "REQUIRED",
+ "priority": 20,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ },
+ {
+ "id": "c890d4c4-e4e2-4618-b69d-8d30f8278965",
+ "alias": "saml ecp",
+ "description": "SAML ECP Profile Authentication Flow",
+ "providerId": "basic-flow",
+ "topLevel": true,
+ "builtIn": true,
+ "authenticationExecutions": [
+ {
+ "authenticator": "http-basic-authenticator",
+ "requirement": "REQUIRED",
+ "priority": 10,
+ "userSetupAllowed": false,
+ "autheticatorFlow": false
+ }
+ ]
+ }
+ ],
+ "authenticatorConfig": [
+ {
+ "id": "2b02fbe4-e05e-4238-bb0e-04da7d4efd4e",
+ "alias": "create unique user config",
+ "config": {
+ "require.password.update.after.registration": "false"
+ }
+ },
+ {
+ "id": "07dd933b-ce95-4a7c-bd81-3efa24f9558c",
+ "alias": "review profile config",
+ "config": {
+ "update.profile.on.first.login": "missing"
+ }
+ }
+ ],
+ "requiredActions": [
+ {
+ "alias": "CONFIGURE_TOTP",
+ "name": "Configure OTP",
+ "providerId": "CONFIGURE_TOTP",
+ "enabled": true,
+ "defaultAction": false,
+ "priority": 10,
+ "config": {}
+ },
+ {
+ "alias": "terms_and_conditions",
+ "name": "Terms and Conditions",
+ "providerId": "terms_and_conditions",
+ "enabled": false,
+ "defaultAction": false,
+ "priority": 20,
+ "config": {}
+ },
+ {
+ "alias": "UPDATE_PASSWORD",
+ "name": "Update Password",
+ "providerId": "UPDATE_PASSWORD",
+ "enabled": true,
+ "defaultAction": false,
+ "priority": 30,
+ "config": {}
+ },
+ {
+ "alias": "UPDATE_PROFILE",
+ "name": "Update Profile",
+ "providerId": "UPDATE_PROFILE",
+ "enabled": true,
+ "defaultAction": false,
+ "priority": 40,
+ "config": {}
+ },
+ {
+ "alias": "VERIFY_EMAIL",
+ "name": "Verify Email",
+ "providerId": "VERIFY_EMAIL",
+ "enabled": true,
+ "defaultAction": false,
+ "priority": 50,
+ "config": {}
+ },
+ {
+ "alias": "update_user_locale",
+ "name": "Update User Locale",
+ "providerId": "update_user_locale",
+ "enabled": true,
+ "defaultAction": false,
+ "priority": 1000,
+ "config": {}
+ }
+ ],
+ "browserFlow": "browser",
+ "registrationFlow": "registration",
+ "directGrantFlow": "direct grant",
+ "resetCredentialsFlow": "reset credentials",
+ "clientAuthenticationFlow": "clients",
+ "dockerAuthenticationFlow": "docker auth",
+ "attributes": {
+ "clientOfflineSessionMaxLifespan": "0",
+ "clientSessionIdleTimeout": "0",
+ "clientSessionMaxLifespan": "0",
+ "clientOfflineSessionIdleTimeout": "0"
+ },
+ "keycloakVersion": "11.0.2",
+ "userManagedAccessAllowed": false
+}
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml
index 609ba54481..dcad2b7da6 100644
--- a/spring-cloud/spring-cloud-gateway/pom.xml
+++ b/spring-cloud/spring-cloud-gateway/pom.xml
@@ -83,23 +83,99 @@
org.springframework.boot
spring-boot-devtools
+
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-resource-server
+
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-client
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.1
+
+ ${java.version}
+ ${java.version}
+
+
org.springframework.boot
spring-boot-maven-plugin
+
+
+
+ org.projectlombok
+ lombok
+
+
+
- Hoxton.SR3
- 2.2.6.RELEASE
+
+
6.0.2.Final
0.7.2
- 5.5.2
+ 9.19
+
-
+
+
+
+ quotes-application
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ com.baeldung.springcloudgateway.oauth.backend.QuotesApplication
+
+
+
+
+
+
+ gateway-as-resource-server
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ com.baeldung.springcloudgateway.oauth.server.ResourceServerGatewayApplication
+ -Dspring.profiles.active=resource-server
+
+
+
+
+
+
+ gateway-as-oauth-client
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ com.baeldung.springcloudgateway.oauth.server.ResourceServerGatewayApplication
+ -Dspring.profiles.active=oauth-client
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java
index 0e88b29bcf..ea58eb7e46 100644
--- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/custompredicates/config/CustomPredicatesConfig.java
@@ -1,6 +1,5 @@
package com.baeldung.springcloudgateway.custompredicates.config;
-import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
@@ -24,14 +23,20 @@ public class CustomPredicatesConfig {
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {
return builder.routes()
- .route("dsl_golden_route", r -> r.path("/dsl_api/**")
- .filters(f -> f.stripPrefix(1))
- .uri("https://httpbin.org")
- .predicate(gf.apply(new Config(true, "customerId"))))
- .route("dsl_common_route", r -> r.path("/dsl_api/**")
- .filters(f -> f.stripPrefix(1))
- .uri("https://httpbin.org")
- .predicate(gf.apply(new Config(false, "customerId"))))
+ .route("dsl_golden_route", r ->
+ r.predicate(gf.apply(new Config(true, "customerId")))
+ .and()
+ .path("/dsl_api/**")
+ .filters(f -> f.stripPrefix(1))
+ .uri("https://httpbin.org")
+ )
+ .route("dsl_common_route", r ->
+ r.predicate(gf.apply(new Config(false, "customerId")))
+ .and()
+ .path("/dsl_api/**")
+ .filters(f -> f.stripPrefix(1))
+ .uri("https://httpbin.org")
+ )
.build();
}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/QuotesApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/QuotesApplication.java
new file mode 100644
index 0000000000..96daf8a73d
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/QuotesApplication.java
@@ -0,0 +1,44 @@
+/**
+ *
+ */
+package com.baeldung.springcloudgateway.oauth.backend;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+import org.springframework.security.oauth2.server.resource.introspection.NimbusReactiveOpaqueTokenIntrospector;
+import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
+
+import com.baeldung.springcloudgateway.oauth.shared.KeycloakReactiveTokenInstrospector;
+
+/**
+ * @author Philippe
+ *
+ */
+@SpringBootApplication
+@PropertySource("classpath:quotes-application.properties")
+@EnableWebFluxSecurity
+public class QuotesApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(QuotesApplication.class);
+ }
+
+
+ @Bean
+ public ReactiveOpaqueTokenIntrospector keycloakIntrospector(OAuth2ResourceServerProperties props) {
+
+ NimbusReactiveOpaqueTokenIntrospector delegate = new NimbusReactiveOpaqueTokenIntrospector(
+ props.getOpaquetoken().getIntrospectionUri(),
+ props.getOpaquetoken().getClientId(),
+ props.getOpaquetoken().getClientSecret());
+
+ return new KeycloakReactiveTokenInstrospector(delegate);
+ }
+
+
+}
+
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/domain/Quote.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/domain/Quote.java
new file mode 100644
index 0000000000..042cfa63fa
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/domain/Quote.java
@@ -0,0 +1,35 @@
+package com.baeldung.springcloudgateway.oauth.backend.domain;
+
+
+public class Quote {
+
+ private String symbol;
+ private double price;
+
+ /**
+ * @return the symbol
+ */
+ public String getSymbol() {
+ return symbol;
+ }
+ /**
+ * @param symbol the symbol to set
+ */
+ public void setSymbol(String symbol) {
+ this.symbol = symbol;
+ }
+ /**
+ * @return the price
+ */
+ public double getPrice() {
+ return price;
+ }
+ /**
+ * @param price the price to set
+ */
+ public void setPrice(double price) {
+ this.price = price;
+ }
+
+
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/web/QuoteApi.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/web/QuoteApi.java
new file mode 100644
index 0000000000..6d3721166c
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/backend/web/QuoteApi.java
@@ -0,0 +1,34 @@
+package com.baeldung.springcloudgateway.oauth.backend.web;
+
+import javax.annotation.PostConstruct;
+
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.springcloudgateway.oauth.backend.domain.Quote;
+
+import reactor.core.publisher.Mono;
+
+@RestController
+public class QuoteApi {
+ private static final GrantedAuthority GOLD_CUSTOMER = new SimpleGrantedAuthority("gold");
+
+ @GetMapping("/quotes/{symbol}")
+ public Mono getQuote(@PathVariable("symbol") String symbol, BearerTokenAuthentication auth ) {
+
+ Quote q = new Quote();
+ q.setSymbol(symbol);
+
+ if ( auth.getAuthorities().contains(GOLD_CUSTOMER)) {
+ q.setPrice(10.0);
+ }
+ else {
+ q.setPrice(12.0);
+ }
+ return Mono.just(q);
+ }
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/server/ResourceServerGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/server/ResourceServerGatewayApplication.java
new file mode 100644
index 0000000000..1b85867f3b
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/server/ResourceServerGatewayApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.springcloudgateway.oauth.server;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+
+@SpringBootApplication
+@EnableWebFluxSecurity
+public class ResourceServerGatewayApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(ResourceServerGatewayApplication.class,args);
+ }
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/shared/KeycloakReactiveTokenInstrospector.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/shared/KeycloakReactiveTokenInstrospector.java
new file mode 100644
index 0000000000..e834e6934d
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/oauth/shared/KeycloakReactiveTokenInstrospector.java
@@ -0,0 +1,65 @@
+/**
+ *
+ */
+package com.baeldung.springcloudgateway.oauth.shared;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
+import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
+import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
+
+import reactor.core.publisher.Mono;
+
+/**
+ * Custom ReactiveTokenIntrospector to map realm roles into Spring GrantedAuthorities
+ *
+ */
+public class KeycloakReactiveTokenInstrospector implements ReactiveOpaqueTokenIntrospector {
+
+ private final ReactiveOpaqueTokenIntrospector delegate;
+
+ public KeycloakReactiveTokenInstrospector(ReactiveOpaqueTokenIntrospector delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Mono introspect(String token) {
+
+ return delegate.introspect(token)
+ .map( this::mapPrincipal);
+ }
+
+ protected OAuth2AuthenticatedPrincipal mapPrincipal(OAuth2AuthenticatedPrincipal principal) {
+
+ return new DefaultOAuth2AuthenticatedPrincipal(
+ principal.getName(),
+ principal.getAttributes(),
+ extractAuthorities(principal));
+ }
+
+ protected Collection extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
+
+ //
+ Map> realm_access = principal.getAttribute("realm_access");
+ List roles = realm_access.getOrDefault("roles", Collections.emptyList());
+ List rolesAuthorities = roles.stream()
+ .map(SimpleGrantedAuthority::new)
+ .collect(Collectors.toList());
+
+ Set allAuthorities = new HashSet<>();
+ allAuthorities.addAll(principal.getAuthorities());
+ allAuthorities.addAll(rolesAuthorities);
+
+ return allAuthorities;
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-oauth-client.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-oauth-client.yml
new file mode 100644
index 0000000000..b097c54eb1
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-oauth-client.yml
@@ -0,0 +1,26 @@
+server:
+ port: 8087
+spring:
+ cloud:
+ gateway:
+ redis:
+ enabled: false
+ routes:
+ - id: quotes
+ uri: http://localhost:8085
+ predicates:
+ - Path=/quotes/**
+ filters:
- TokenRelay=
+ security:
+ oauth2:
+ client:
provider:
keycloak:
+ issuer-uri: http://localhost:8083/auth/realms/baeldung
+ registration:
quotes-client:
+ provider: keycloak
+ client-id: quotes-client
+ client-secret: 0e082231-a70d-48e8-b8a5-fbfb743041b6
+ scope:
- email
+ - profile
+ - roles
+
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-resource-server.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-resource-server.yml
new file mode 100644
index 0000000000..14f713a04a
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-resource-server.yml
@@ -0,0 +1,19 @@
+server:
+ port: 8086
+spring:
+ security:
+ oauth2:
+ resourceserver:
+ opaquetoken:
+ introspection-uri: http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token/introspect
+ client-id: quotes-client
+ client-secret: 0e082231-a70d-48e8-b8a5-fbfb743041b6
+ cloud:
+ gateway:
+ redis:
+ enabled: false
+ routes:
+ - id: quotes
+ uri: http://localhost:8085
+ predicates:
+ - Path=/quotes/**
diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/quotes-application.properties b/spring-cloud/spring-cloud-gateway/src/main/resources/quotes-application.properties
new file mode 100644
index 0000000000..48e8999b1b
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/resources/quotes-application.properties
@@ -0,0 +1,12 @@
+server.port=8085
+# Disable gateway & redis as we don't need them in this application
+spring.cloud.gateway.enabled=false
+spring.cloud.gateway.redis.enabled=false
+
+# Resource server settings
+spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token/introspect
+spring.security.oauth2.resourceserver.opaquetoken.client-id=quotes-client
+spring.security.oauth2.resourceserver.opaquetoken.client-secret=0e082231-a70d-48e8-b8a5-fbfb743041b6
+
+
+
diff --git a/spring-cloud/spring-cloud-gateway/src/test/postman/OAuth_Gateway.postman_collection.json b/spring-cloud/spring-cloud-gateway/src/test/postman/OAuth_Gateway.postman_collection.json
new file mode 100644
index 0000000000..ac920a271b
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/test/postman/OAuth_Gateway.postman_collection.json
@@ -0,0 +1,203 @@
+{
+ "info": {
+ "_postman_id": "b3d00e23-c2cd-40ce-a90b-673efb25e5c0",
+ "name": "Baeldung - OAuth",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
+ },
+ "item": [
+ {
+ "name": "Token",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "var jsonData = pm.response.json();\r",
+ "pm.environment.set(\"access_token\", jsonData.access_token);\r",
+ "pm.environment.set(\"refresh_token\", jsonData.refresh_token);\r",
+ "pm.environment.set(\"backend_token\", \"Bearer \" + jsonData.access_token);"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [],
+ "body": {
+ "mode": "urlencoded",
+ "urlencoded": [
+ {
+ "key": "client_id",
+ "value": "{{client_id}}",
+ "type": "text"
+ },
+ {
+ "key": "client_secret",
+ "value": "{{client_secret}}",
+ "type": "text"
+ },
+ {
+ "key": "grant_type",
+ "value": "password",
+ "type": "text"
+ },
+ {
+ "key": "scope",
+ "value": "email roles profile",
+ "type": "text"
+ },
+ {
+ "key": "username",
+ "value": "maxwell.smart",
+ "type": "text"
+ },
+ {
+ "key": "password",
+ "value": "1234",
+ "type": "text"
+ }
+ ]
+ },
+ "url": {
+ "raw": "{{keycloack_base}}/token",
+ "host": [
+ "{{keycloack_base}}"
+ ],
+ "path": [
+ "token"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Quote",
+ "protocolProfileBehavior": {
+ "disabledSystemHeaders": {
+ "accept": true
+ }
+ },
+ "request": {
+ "auth": {
+ "type": "bearer",
+ "bearer": [
+ {
+ "key": "token",
+ "value": "{{access_token}}",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json",
+ "type": "text"
+ }
+ ],
+ "url": {
+ "raw": "http://localhost:8085/quotes/:symbol",
+ "protocol": "http",
+ "host": [
+ "localhost"
+ ],
+ "port": "8085",
+ "path": [
+ "quotes",
+ ":symbol"
+ ],
+ "variable": [
+ {
+ "key": "symbol",
+ "value": "IBM"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Quote via Gateway",
+ "protocolProfileBehavior": {
+ "disabledSystemHeaders": {
+ "accept": true
+ }
+ },
+ "request": {
+ "auth": {
+ "type": "bearer",
+ "bearer": [
+ {
+ "key": "token",
+ "value": "{{access_token}}",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json",
+ "type": "text"
+ }
+ ],
+ "url": {
+ "raw": "http://localhost:8086/quotes/:symbol",
+ "protocol": "http",
+ "host": [
+ "localhost"
+ ],
+ "port": "8086",
+ "path": [
+ "quotes",
+ ":symbol"
+ ],
+ "variable": [
+ {
+ "key": "symbol",
+ "value": "IBM"
+ }
+ ]
+ }
+ },
+ "response": []
+ }
+ ],
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "type": "text/javascript",
+ "exec": [
+ ""
+ ]
+ }
+ }
+ ],
+ "variable": [
+ {
+ "key": "keycloack_base",
+ "value": "http://localhost:8083/auth/realms/baeldung/protocol/openid-connect"
+ },
+ {
+ "key": "client_id",
+ "value": "quotes-client"
+ },
+ {
+ "key": "client_secret",
+ "value": "56be94c8-b20a-4374-899c-e39cb022d3f8"
+ }
+ ]
+}
\ No newline at end of file
From 4d159f7808ad3d8d312f3778c0b06caa87e60845 Mon Sep 17 00:00:00 2001
From: lucaCambi77
Date: Sun, 23 Jan 2022 04:36:25 +0100
Subject: [PATCH 008/235] BAEL-5263 : Access Entity Manager with Spring Boot
and Spring Data (#11680)
* feat: entity manager with spring data
* fix typo
* fix: article and code review
---
.../CustomRepositoryApplication.java | 12 ++++
.../customrepository/model/User.java | 55 +++++++++++++++++++
.../repository/CustomUserRepository.java | 9 +++
.../repository/CustomUserRepositoryImpl.java | 26 +++++++++
.../repository/UserRepository.java | 10 ++++
.../CustomRepositoryUnitTest.java | 27 +++++++++
6 files changed, 139 insertions(+)
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryApplication.java
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/model/User.java
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepository.java
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepositoryImpl.java
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/UserRepository.java
create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryUnitTest.java
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryApplication.java
new file mode 100644
index 0000000000..f8f42aa67c
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryApplication.java
@@ -0,0 +1,12 @@
+package com.baeldung.spring.data.persistence.customrepository;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CustomRepositoryApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CustomRepositoryApplication.class, args);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/model/User.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/model/User.java
new file mode 100644
index 0000000000..ba217577f3
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/model/User.java
@@ -0,0 +1,55 @@
+package com.baeldung.spring.data.persistence.customrepository.model;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import java.util.Objects;
+
+@Entity
+public class User {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+ private String name;
+ private String email;
+
+ 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 String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ User user = (User) o;
+ return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(email, user.email);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name, email);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepository.java
new file mode 100644
index 0000000000..2c79e518b6
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.spring.data.persistence.customrepository.repository;
+
+import com.baeldung.spring.data.persistence.customrepository.model.User;
+
+public interface CustomUserRepository {
+
+ User customFindMethod(Long id);
+
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepositoryImpl.java
new file mode 100644
index 0000000000..dc006580c1
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/CustomUserRepositoryImpl.java
@@ -0,0 +1,26 @@
+package com.baeldung.spring.data.persistence.customrepository.repository;
+
+import com.baeldung.spring.data.persistence.customrepository.model.User;
+
+import javax.annotation.PostConstruct;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import java.util.Objects;
+
+public class CustomUserRepositoryImpl implements CustomUserRepository {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ @Override
+ public User customFindMethod(Long id) {
+ return (User) entityManager.createQuery("FROM User u WHERE u.id = :id")
+ .setParameter("id", id)
+ .getSingleResult();
+ }
+
+ @PostConstruct
+ public void postConstruct() {
+ Objects.requireNonNull(entityManager);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/UserRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/UserRepository.java
new file mode 100644
index 0000000000..d9f60015cc
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/customrepository/repository/UserRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.spring.data.persistence.customrepository.repository;
+
+import com.baeldung.spring.data.persistence.customrepository.model.User;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface UserRepository extends JpaRepository, CustomUserRepository {
+
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryUnitTest.java
new file mode 100644
index 0000000000..ed54225a14
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/customrepository/CustomRepositoryUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.spring.data.persistence.customrepository;
+
+import com.baeldung.spring.data.persistence.customrepository.model.User;
+import com.baeldung.spring.data.persistence.customrepository.repository.UserRepository;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+@SpringBootTest(classes = CustomRepositoryApplication.class)
+class CustomRepositoryUnitTest {
+
+ @Autowired
+ private UserRepository userRepository;
+
+ @Test
+ void givenCustomRepository_whenInvokeCustomFindMethod_thenEntityIsFound() {
+ User user = new User();
+ user.setEmail("foo@gmail.com");
+ user.setName("userName");
+
+ User persistedUser = userRepository.save(user);
+
+ assertEquals(persistedUser, userRepository.customFindMethod(user.getId()));
+ }
+}
From 7cfd820f5bbc03e8143ebec150fa0f75c5890d9f Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 09:40:01 +0500
Subject: [PATCH 009/235] Update README.md
added link back to article: Generating a Java String of N Repeated Characters
---
core-java-modules/core-java-string-algorithms-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md
index e6dbf3a489..ba8509306e 100644
--- a/core-java-modules/core-java-string-algorithms-3/README.md
+++ b/core-java-modules/core-java-string-algorithms-3/README.md
@@ -4,6 +4,7 @@ This module contains articles about string-related algorithms.
### Relevant Articles:
+- [Generating a Java String of N Repeated Characters](https://www.baeldung.com/java-string-of-repeated-characters)
- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams)
- [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex)
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
From 4d0b7e68998904c6c747edbd619dbf4b811c607c Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 09:57:22 +0500
Subject: [PATCH 010/235] Update README.md
added link back to article
---
core-java-modules/core-java-17/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-17/README.md b/core-java-modules/core-java-17/README.md
index 4d1d7a5c49..1f061bd7c1 100644
--- a/core-java-modules/core-java-17/README.md
+++ b/core-java-modules/core-java-17/README.md
@@ -1,5 +1,6 @@
### Relevant articles:
+- [An Introduction to InstantSource in Java 17](https://www.baeldung.com/java-instantsource)
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)
- [Introduction to HexFormat in Java 17](https://www.baeldung.com/java-hexformat)
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
From 21b2f0127aa7ac3a9f587a246b9c38f2ca36af14 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 10:08:00 +0500
Subject: [PATCH 011/235] Update README.md
add link back to article: Hidden Classes in Java 15
---
core-java-modules/core-java-15/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-15/README.md b/core-java-modules/core-java-15/README.md
index de503fbb31..4b163fcfb5 100644
--- a/core-java-modules/core-java-15/README.md
+++ b/core-java-modules/core-java-15/README.md
@@ -4,4 +4,5 @@ This module contains articles about Java 15.
### Relevant articles
+- [Hidden Classes in Java 15](https://www.baeldung.com/java-hidden-classes)
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
From 118a96846cc38086c0672eb4b2bd2c4a36840771 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 10:17:43 +0500
Subject: [PATCH 012/235] Create README.md
added link back to article: Convert a Maven Build to Gradle
---
gradle/maven-to-gradle/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 gradle/maven-to-gradle/README.md
diff --git a/gradle/maven-to-gradle/README.md b/gradle/maven-to-gradle/README.md
new file mode 100644
index 0000000000..bd6e435c9a
--- /dev/null
+++ b/gradle/maven-to-gradle/README.md
@@ -0,0 +1,3 @@
+## Relevant Articles:
+
+[Convert a Maven Build to Gradle](https://www.baeldung.com/maven-convert-to-gradle)
From 4bebebad691d4ca2cfe886a9a0a2f08121ff8019 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 10:22:06 +0500
Subject: [PATCH 013/235] Update README.md
added link back to article: Get the Name of the Currently Executing Test in JUnit
---
testing-modules/junit-5-advanced/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md
index 7790cb6770..e970ba8c96 100644
--- a/testing-modules/junit-5-advanced/README.md
+++ b/testing-modules/junit-5-advanced/README.md
@@ -1,5 +1,6 @@
## Relevant Articles:
+- [Get the Name of the Currently Executing Test in JUnit](https://www.baeldung.com/junit-get-name-of-currently-executing-test)
- [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher)
- [JUnit Custom Display Name Generator API](https://www.baeldung.com/junit-custom-display-name-generator)
- [@TestInstance Annotation in JUnit 5](https://www.baeldung.com/junit-testinstance-annotation)
From de6d285eef568a3095913ab0248dd9fb71b6e4c1 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 23 Jan 2022 10:25:53 +0500
Subject: [PATCH 014/235] Update README.md
added link back to article: Cassandra Batch in Cassandra Query Language and Java
---
persistence-modules/java-cassandra/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/persistence-modules/java-cassandra/README.md b/persistence-modules/java-cassandra/README.md
index 735aabdf62..792ef143ab 100644
--- a/persistence-modules/java-cassandra/README.md
+++ b/persistence-modules/java-cassandra/README.md
@@ -1,4 +1,6 @@
### Relevant Articles:
+
+- [Cassandra Batch in Cassandra Query Language and Java](https://www.baeldung.com/java-cql-cassandra-batch)
- [A Guide to Cassandra with Java](http://www.baeldung.com/cassandra-with-java)
- [Intro to DataStax Java Driver for Apache Cassandra](https://www.baeldung.com/cassandra-datastax-java-driver)
- [CQL Data Types](https://www.baeldung.com/cassandra-data-types)
From 5c694082fa527f5dbfb8702c0c541c7db1a4a40e Mon Sep 17 00:00:00 2001
From: sampadawagde
Date: Sun, 23 Jan 2022 12:43:25 +0530
Subject: [PATCH 015/235] JAVA-9510: Fix SpringContextTest in
spring-cloud-openfeign
---
spring-cloud/spring-cloud-openfeign/pom.xml | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml
index 1cb618c7e1..3e59f512db 100644
--- a/spring-cloud/spring-cloud-openfeign/pom.xml
+++ b/spring-cloud/spring-cloud-openfeign/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.cloud
spring-cloud-openfeign
- 0.0.1-SNAPSHOT
spring-cloud-openfeign
OpenFeign project for Spring Boot
@@ -49,8 +48,7 @@
io.github.openfeign.form
feign-form-spring
- 3.8.0
-
+
org.springframework.boot
spring-boot-starter-test
@@ -59,7 +57,7 @@
- Hoxton.SR6
+ 2021.0.0
\ No newline at end of file
From 856f101dc8b4a31d75a1b3106e88c9aa1a2931ba Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 24 Jan 2022 11:10:50 +0500
Subject: [PATCH 016/235] Update README.md
added link back to article: Running a TestNG Project From the Command Line
[skip ci]
---
testing-modules/testng_command_line/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/testing-modules/testng_command_line/README.md b/testing-modules/testng_command_line/README.md
index 881477f036..74cdafdbc6 100644
--- a/testing-modules/testng_command_line/README.md
+++ b/testing-modules/testng_command_line/README.md
@@ -1 +1,3 @@
### Relevant articles
+
+- [Running a TestNG Project From the Command Line](https://www.baeldung.com/testng-run-command-line)
From ca79812da76361c3486a5104791b0606f967d4fb Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Mon, 24 Jan 2022 10:31:06 +0100
Subject: [PATCH 017/235] JAVA-9555: Fix YahooQuoteManagerImpl
---
.../main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java
index 8cc68259be..f5c60699c7 100644
--- a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java
+++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java
@@ -24,7 +24,7 @@ public class YahooQuoteManagerImpl implements QuoteManager {
StringBuilder sb = new StringBuilder();
Currency.getAvailableCurrencies().forEach(currency -> {
- if (!currency.equals(currency.getCurrencyCode())) {
+ if (!baseCurrency.equals(currency.getCurrencyCode())) {
sb.append(baseCurrency).append(currency.getCurrencyCode()).append("=X").append(",");
}
});
From e677f7a3ea880349d66e1c5813c9bc80f8ba9a72 Mon Sep 17 00:00:00 2001
From: mdabrowski-eu
Date: Mon, 24 Jan 2022 23:27:48 +0100
Subject: [PATCH 018/235] BAEL-5301 Fix indentation
---
.../baeldung/feign/retry/Custom5xxErrorDecoder.java | 12 ++++++------
.../feign/retry/ResilientFeignClientBuilder.java | 12 ++++++------
.../feign/retry/Custom5xxErrorDecoderUnitTest.java | 2 +-
3 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java b/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
index c4edfe219f..6ff3c42ba1 100644
--- a/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
+++ b/feign/src/main/java/com/baeldung/feign/retry/Custom5xxErrorDecoder.java
@@ -15,12 +15,12 @@ public class Custom5xxErrorDecoder implements ErrorDecoder {
int status = response.status();
if (status >= 500) {
return new RetryableException(
- response.status(),
- exception.getMessage(),
- response.request().httpMethod(),
- exception,
- null,
- response.request());
+ response.status(),
+ exception.getMessage(),
+ response.request().httpMethod(),
+ exception,
+ null,
+ response.request());
}
return exception;
}
diff --git a/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
index edcaf13242..d8285d362a 100644
--- a/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
+++ b/feign/src/main/java/com/baeldung/feign/retry/ResilientFeignClientBuilder.java
@@ -18,11 +18,11 @@ public class ResilientFeignClientBuilder {
public static T createClient(Class type, String uri) {
return Feign.builder()
- .client(new OkHttpClient())
- .encoder(new GsonEncoder())
- .decoder(new GsonDecoder())
- .retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(3L), 5))
- .errorDecoder(new Custom5xxErrorDecoder())
- .target(type, uri);
+ .client(new OkHttpClient())
+ .encoder(new GsonEncoder())
+ .decoder(new GsonDecoder())
+ .retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(3L), 5))
+ .errorDecoder(new Custom5xxErrorDecoder())
+ .target(type, uri);
}
}
diff --git a/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
index 0b67090268..b51a1a65b3 100644
--- a/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
+++ b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
@@ -44,7 +44,7 @@ public class Custom5xxErrorDecoderUnitTest {
private Response responseStub(int status) {
return Response.builder()
.request(Request.create(
- Request.HttpMethod.GET, "url", new HashMap>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
+ Request.HttpMethod.GET, "url", new HashMap>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
.status(status)
.build();
}
From c81fe2f74e5d4b3b3996c58c23e49235591371ca Mon Sep 17 00:00:00 2001
From: AttilaUhrin
Date: Tue, 25 Jan 2022 06:49:12 +0100
Subject: [PATCH 019/235] [BAEL-3946] Javafx adding ActionListener to button
(#11701)
* Add implementation for article.
* Add new line at the end of FXML layout file.
* Remove default prefWidth from button, convert eventHandler to lambda.
* Fix FXML file formatting.
---
.../ButtonEventHandlerController.java | 64 +++++++++++++++++++
.../baeldung/button/eventhandler/Main.java | 24 +++++++
.../main/resources/button_event-handler.fxml | 16 +++++
3 files changed, 104 insertions(+)
create mode 100644 javafx/src/main/java/com/baeldung/button/eventhandler/ButtonEventHandlerController.java
create mode 100644 javafx/src/main/java/com/baeldung/button/eventhandler/Main.java
create mode 100644 javafx/src/main/resources/button_event-handler.fxml
diff --git a/javafx/src/main/java/com/baeldung/button/eventhandler/ButtonEventHandlerController.java b/javafx/src/main/java/com/baeldung/button/eventhandler/ButtonEventHandlerController.java
new file mode 100644
index 0000000000..8d54a366f0
--- /dev/null
+++ b/javafx/src/main/java/com/baeldung/button/eventhandler/ButtonEventHandlerController.java
@@ -0,0 +1,64 @@
+package com.baeldung.button.eventhandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javafx.event.ActionEvent;
+import javafx.event.EventHandler;
+import javafx.fxml.FXML;
+import javafx.scene.control.Button;
+import javafx.scene.control.Label;
+import javafx.scene.effect.DropShadow;
+import javafx.scene.effect.Effect;
+import javafx.scene.input.MouseButton;
+import javafx.scene.input.MouseEvent;
+import javafx.scene.text.Font;
+
+public class ButtonEventHandlerController {
+
+ private static final Logger logger = LoggerFactory.getLogger(ButtonEventHandlerController.class);
+
+ @FXML
+ private Button button;
+
+ @FXML
+ private Label label;
+
+ @FXML
+ private void initialize() {
+ button.setText("Click me");
+
+ handleClickEvent();
+ handleHoverEffect();
+ reuseRightClickEventHandler();
+ }
+
+ private void handleClickEvent() {
+ button.setOnAction(new EventHandler() {
+ @Override
+ public void handle(ActionEvent event) {
+ logger.info("OnAction {}", event);
+ }
+ });
+
+ button.setOnAction(event -> logger.info("OnAction {}", event));
+ button.setOnAction(event -> logger.info("OnAction2 {}", event));
+ }
+
+ private void handleHoverEffect() {
+ Effect shadow = new DropShadow();
+ button.setOnMouseEntered(e -> button.setEffect(shadow));
+ button.setOnMouseExited(e -> button.setEffect(null));
+ }
+
+ private void reuseRightClickEventHandler() {
+ EventHandler rightClickHandler = event -> {
+ if (MouseButton.SECONDARY.equals(event.getButton())) {
+ button.setFont(new Font(button.getFont()
+ .getSize() + 1));
+ }
+ };
+ button.setOnMousePressed(rightClickHandler);
+ label.setOnMousePressed(rightClickHandler);
+ }
+}
diff --git a/javafx/src/main/java/com/baeldung/button/eventhandler/Main.java b/javafx/src/main/java/com/baeldung/button/eventhandler/Main.java
new file mode 100644
index 0000000000..0c4e2eaa08
--- /dev/null
+++ b/javafx/src/main/java/com/baeldung/button/eventhandler/Main.java
@@ -0,0 +1,24 @@
+package com.baeldung.button.eventhandler;
+
+import javafx.application.Application;
+import javafx.fxml.FXMLLoader;
+import javafx.scene.Scene;
+import javafx.scene.layout.Pane;
+import javafx.stage.Stage;
+
+public class Main extends Application {
+
+ public static void main(String[] args) {
+ launch(args);
+ }
+
+ @Override
+ public void start(Stage primaryStage) throws Exception {
+ FXMLLoader loader = new FXMLLoader(getClass().getResource("/button_event-handler.fxml"));
+ Pane page = loader.load();
+
+ primaryStage.setTitle("Button event handler");
+ primaryStage.setScene(new Scene(page));
+ primaryStage.show();
+ }
+}
diff --git a/javafx/src/main/resources/button_event-handler.fxml b/javafx/src/main/resources/button_event-handler.fxml
new file mode 100644
index 0000000000..2f7b1eeff6
--- /dev/null
+++ b/javafx/src/main/resources/button_event-handler.fxml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
From ba226f327b577498d331a82b81343760c7f9e5b9 Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Tue, 25 Jan 2022 22:21:39 +0530
Subject: [PATCH 020/235] JAVA-8292 : Split or move spring-data-jpa-enterprise
module
---
.../spring-data-jpa-enterprise-2/README.md | 18 ++++++
.../spring-data-jpa-enterprise-2/pom.xml | 58 +++++++++++++++++++
.../main/java/com/baeldung/Application.java | 13 +++++
.../multipledb/MultipleDbApplication.java | 0
.../PersistenceProductAutoConfiguration.java | 1 -
.../PersistenceProductConfiguration.java | 0
.../PersistenceUserAutoConfiguration.java | 1 -
.../PersistenceUserConfiguration.java | 0
.../dao/product/ProductRepository.java | 0
.../dao/user/PossessionRepository.java | 0
.../multipledb/dao/user/UserRepository.java | 0
.../multipledb/model/product/Product.java | 0
.../multipledb/model/user/Possession.java | 0
.../baeldung/multipledb/model/user/User.java | 0
.../src/main/resources/application.properties | 15 +++++
.../persistence-multiple-db-boot.properties | 0
.../persistence-multiple-db.properties | 0
.../JpaMultipleDBIntegrationTest.java | 0
.../ProductRepositoryIntegrationTest.java | 2 -
.../src/test/resources/logback-test.xml | 13 +++++
.../spring-data-jpa-enterprise/README.md | 2 -
.../SpringJpaContextIntegrationTest.java | 6 +-
22 files changed, 118 insertions(+), 11 deletions(-)
create mode 100644 persistence-modules/spring-data-jpa-enterprise-2/README.md
create mode 100644 persistence-modules/spring-data-jpa-enterprise-2/pom.xml
create mode 100644 persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/Application.java
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java (97%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java (97%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java (100%)
mode change 100755 => 100644
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/model/product/Product.java (100%)
mode change 100755 => 100644
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/model/user/Possession.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/java/com/baeldung/multipledb/model/user/User.java (100%)
create mode 100644 persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/application.properties
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/resources/persistence-multiple-db-boot.properties (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/main/resources/persistence-multiple-db.properties (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java (100%)
rename persistence-modules/{spring-data-jpa-enterprise => spring-data-jpa-enterprise-2}/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java (97%)
create mode 100644 persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/logback-test.xml
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/README.md b/persistence-modules/spring-data-jpa-enterprise-2/README.md
new file mode 100644
index 0000000000..9bb08cc497
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-enterprise-2/README.md
@@ -0,0 +1,18 @@
+## Spring Data JPA - Enterprise
+
+This module contains articles about Spring Data JPA used in enterprise applications such as transactions, sessions, naming conventions and more
+
+### Relevant Articles:
+
+- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases)
+- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
+
+### Eclipse Config
+After importing the project into Eclipse, you may see the following error:
+"No persistence xml file found in project"
+
+This can be ignored:
+- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
+Or:
+- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
+
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/pom.xml b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml
new file mode 100644
index 0000000000..7efa5f504f
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml
@@ -0,0 +1,58 @@
+
+
+ 4.0.0
+ spring-data-jpa-enterprise-2
+ spring-data-jpa-enterprise-2
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jdbc
+
+
+ org.springframework.boot
+ spring-boot-starter-cache
+
+
+ com.h2database
+ h2
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+
+ src/main/java
+
+
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/Application.java
new file mode 100644
index 0000000000..37dbe7dab8
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/Application.java
@@ -0,0 +1,13 @@
+package com.baeldung;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+}
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java
similarity index 97%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java
index a6f8f0829f..bc7ab57b06 100644
--- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java
@@ -8,7 +8,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java
similarity index 97%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java
index e04a1621b2..8080885b37 100644
--- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java
@@ -8,7 +8,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java
old mode 100755
new mode 100644
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/product/Product.java
old mode 100755
new mode 100644
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/product/Product.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/Possession.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/user/Possession.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/Possession.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/user/Possession.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/User.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/user/User.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/User.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/multipledb/model/user/User.java
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/application.properties
new file mode 100644
index 0000000000..0ca1872207
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/application.properties
@@ -0,0 +1,15 @@
+
+spring.datasource.url=jdbc:h2:mem:baeldung
+
+# JPA-Schema-Generation
+# Use below configuration to generate database schema create commands based on the entity models
+# and export them into the create.sql file
+#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
+#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql
+#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata
+#spring.jpa.properties.hibernate.format_sql=true
+
+spring.jpa.show-sql=false
+
+#hibernate.dialect=org.hibernate.dialect.H2Dialect
+spring.jpa.properties.hibernate.id.new_generator_mappings=false
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/persistence-multiple-db-boot.properties
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/persistence-multiple-db-boot.properties
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/persistence-multiple-db.properties
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties
rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/resources/persistence-multiple-db.properties
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java
similarity index 100%
rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java
similarity index 97%
rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java
rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java
index 9bfba61a3b..831790af95 100644
--- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java
@@ -18,12 +18,10 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
-import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
-import com.baeldung.multipledb.PersistenceProductConfiguration;
import com.baeldung.multipledb.dao.product.ProductRepository;
import com.baeldung.multipledb.model.product.Product;
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/logback-test.xml
new file mode 100644
index 0000000000..1595326253
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/logback-test.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md
index 42fbecc880..ca89bd54e7 100644
--- a/persistence-modules/spring-data-jpa-enterprise/README.md
+++ b/persistence-modules/spring-data-jpa-enterprise/README.md
@@ -4,9 +4,7 @@ This module contains articles about Spring Data JPA used in enterprise applicati
### Relevant Articles:
-- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8)
-- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting)
- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test)
- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view)
- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections)
diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java
index f3697bf39f..ecaa83f3f3 100644
--- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java
+++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java
@@ -8,14 +8,10 @@ import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.config.PersistenceConfiguration;
-import com.baeldung.multipledb.PersistenceProductConfiguration;
-import com.baeldung.multipledb.PersistenceUserConfiguration;
@RunWith(SpringRunner.class)
@DataJpaTest(excludeAutoConfiguration = {
- PersistenceConfiguration.class,
- PersistenceUserConfiguration.class,
- PersistenceProductConfiguration.class })
+ PersistenceConfiguration.class })
@ContextConfiguration(classes = Application.class)
public class SpringJpaContextIntegrationTest {
From 480d9fb405f894daadf6dee77aae054ad8058344 Mon Sep 17 00:00:00 2001
From: HarisHashim
Date: Wed, 26 Jan 2022 09:28:57 +0800
Subject: [PATCH 021/235] BAEL-5204: Change the font color of a cell with
Apache POI (#11554)
* BAEL-5204: First commit "Change the font color of a cell with Apache POI"
* BAEL-5204: Create class and unit test
* BAEL-5204: finalize unit test
* BAEL-5204: fix indent
* BAEL-5204: add missing excel template
---
.../poi/excel/cellstyle/CellStyler.java | 26 +++++++++
.../poi/excel/cellstyle/CellStyle.xlsx | Bin 0 -> 8393 bytes
.../excel/cellstyle/CellStylerUnitTest.java | 52 ++++++++++++++++++
3 files changed, 78 insertions(+)
create mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
create mode 100644 apache-poi/src/main/resources/com/baeldung/poi/excel/cellstyle/CellStyle.xlsx
create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStylerUnitTest.java
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java b/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
new file mode 100644
index 0000000000..6d8b303fd3
--- /dev/null
+++ b/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
@@ -0,0 +1,26 @@
+package com.baeldung.poi.excel.cellstyle;
+
+import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.VerticalAlignment;
+import org.apache.poi.ss.usermodel.Workbook;
+
+public class CellStyler {
+ public CellStyle createWarningColor(Workbook workbook) {
+ CellStyle style = workbook.createCellStyle();
+
+ Font font = workbook.createFont();
+ font.setFontName("Courier New");
+ font.setBold(true);
+ font.setUnderline(Font.U_SINGLE);
+ font.setColor(HSSFColorPredefined.DARK_RED.getIndex());
+ style.setFont(font);
+
+ style.setAlignment(HorizontalAlignment.CENTER);
+ style.setVerticalAlignment(VerticalAlignment.CENTER);
+ return style;
+ }
+}
diff --git a/apache-poi/src/main/resources/com/baeldung/poi/excel/cellstyle/CellStyle.xlsx b/apache-poi/src/main/resources/com/baeldung/poi/excel/cellstyle/CellStyle.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..ca9394246a706801c2db17a2ab89446c69fe505b
GIT binary patch
literal 8393
zcmeHMgRd^f#c?DzTqMTE&!6T1GF=*bGf51+V7L
z_UnKa`uNHa
zX*9cDWhlLKV`}1=G%>%k0FFp($Ayn9qP4ygpito@t$iJHQm)^ZXvf;&Z{Y9S!4w~R
zqJGuFPh@S({v=N#ggSJ58lY|$TYs;L+YuJfD^66XJao`a1^-6BOhDedNM_NJmyl?o
zdY{IDZK=3FPeu(Qz!Dl*IxyHI*r~Q_PVVnmGKRi}^6=u8@C>xsa@;8e9PFf~3y9oZ
z8rT%}+ZkPd61I1kz8S=Qg9ZTH-Xa6k|3*uwHkkGVfi-0W>#z{CG&^Q{5uvlZUTSbRcZ+6J$xh>R;24|Em=*K}Ez%H>{==j7?+S(col50htm
z0!u|x*(;^NMOxWUhcY!l7{_B$OoC$ahzzA{0Ho*PcKQeHLW2w)n<9FLNq?c7WSRTGC3Ut-~HKD
zUkqr_@Zw)^!{qwuU!Df(*Yh3@<@)prVD?lD91MoWQkE?s6zZQO5l4GNat9dzI73hf
z4>2>|_MBc$u6AZlPIf#_zks&9=T2Y)Ckt8P#Y?W_*XnAmxp{n$j0#ZUuFy8W(l
z6=YbYtC`&rXeNTK$igx~O?O3m-?o`B4n}CFXf%T>q%g>MMR
zfkzA|Iq>`b*vxl%JBT?VIV(>NQYs@jb$i(FcNxplQdQ}&VxsJ)SRZ0F0#$I+rH-~$
zTPUiwjqBaBk_S>IrhPcrV4A$4uk??1(GL^_PU}JVm8OJ|w1mn=YyNLc0nOsc>Dw{-
zft4&+8h#}=+IrCG{_r~>KjLdOTHeT6B+L-uQH}J`a7byx0V%sCuTm{Z2kc(zP}^&r
zEQiYRP{ow7Y^mZ)D1O!$n_GA)Qo1egDg*MQ193CNzo+TrQc|Cod|o>~C%h^(D3Q~W
z!xu@W^0?eDh*H#9m9bq0R&}=Y-Q5$-rlsgSkvCEH#^6(FA`y2}Ri^5|uK9h{L#pnY
zAQ5`TK;CT1OF3!oGpp4uZ(xLl81^B7U|}StW_`{3Itp_47#jJT_)SLm$-U4N*|jI6
z2^W_~hPQ7v9n?lly^ajA-tj+KZ+g|(4AOq{nfVAaBIS5_*BMUgB;y!Mh;wiQsGkn_
z*7d#|&}TuuGLVG(ppLNJlz01nZs&UI7o5T+qT;hSR9lCAZ3jbx7PpK})4ePH0d@4~
zIqCc_MJi?;agPQ^pc^foX5@WExm^NhAEyVAPF|`Zoyb2+ko6WnI`jvA8}k-F=^vvy
zNhs74OprUC@h5G)ZVHk)5?B4upqzZOv8sDdYmQZA=D~F>$AzmR4o0~fhIc51-)G4V
z+auzCqf3ZbYQ`~wCM^g}Aq8L{A?WhIvhr8b{3$U=h>Qq*pOrX~og#ephx89N$ec8f
zNATK?fIYZv-9{gLK!n(#`nBMzXPP@zq4kZ8RN2f=*KeDp=g!dbLwzX6j!7^TL~win
zV_zqzSueUCo?#rdT|ZUv8L{gsyuw~5uTY{W=M(jhaHonKkfRJ@PIg-_$ZFNzUv`)J
z_JO%$?uc#ZWdG^fVE^PIVx|8XVR3zl>sSzQVM6Q@E2g^Mc9mLiuG*JA{Vnl>AcKCXYh^p
zh|g}umS-uE59&rSAK!3tDn7WIf4tK6>iXElRXQ4Pp4UJRnGYUT+87JVFR${jTSP($
zMOn3*4Ij;j^BD{IB32`MpWLSElgLu(6Rt(!rQvFMR(_RFb|uZcClX9>dhEFdjm|J4
zG8_hSDqKQ5-Hv^WeYxy=8B4rg+bZH9o%1MNMf#q=V2y%@m-XDA4~wPXt(8lmJLC(R
z{zqKHqe1BkO3Rgv4)Tc~aryFx^6Mb0EAm29K_CX!%&^BKcn8n211pPmwg$5EOfJz)
zr{r|!IUYM&Xnqpkoa5{Ax+m>>cXishrHnM1kz5;u?x50Pv2G|kQ$TusOk=ve2vt}b
zqI@ZV(n(H2KbEItH|4TI;8`qx((_FIq~q4Ame&1I?yPxee^<{Uxy{RUGNQezEBc(#
z$rFaG;io=Hus2@?FW`?5nrfPxBZjW+iv&tnay56ZCM8l@ww&Vmxfy9$@|^q0+GBUxKBMO#pmRb^3PdcN_U
z)vt3iUo$p{Es3p)O46r)#FBsFD>l?oHwB^I@uWX?pFi>CZf)sc$@#PY39TJHSS*b0>$z(J?py
z&_LwVjPoJkI6OPskM6$Jq!Y*foL?(3
zUQjGa-b;{$OB54CKDth+1Vp!hO&=%iR;)v!wRK>8BjQmk650SB_f<0LeD;=4K@69&
z*n(kpFVbXkl8Q4w;Pz;SU}L?mpAj!FPvl~AZMi1}UHoZ7T)Z$-*46`K|8Fz-#z8yR
zhif^+3Gb>`o8xa!Bh>;gFWrQJ3{Sk5FEbK?{H`u8ALrlPz-h7CQVNhCh|zI<8PWFN
znK$A3sN&OQ5sx<>^x6DAwb_XTXu2VDFLnT6WJqP(<59EO_JkQD4#(Rkuz#tAve-?M
zjn+8Y47sWQ{%-BWRxqn8+i*{h4>uGqZ^UCB=UKeHc_b5;)LcGHLN9vQ;=XCv7mpbH
zkP^YJ?j+bWbzk}noT2w%n}Vb`t}fcyk)Sj-YLZ^s)r3xC%qFrIm=XS*>e=kU@B(}3
zP?^JLQGW}X<#34!slce$%Y8%E9P0Kw5E-t?2k&BKENGiM8p%s)0)
z!Jvd+Dp0@QjfxfB@pA{|3}_`v=L{S6X2$Q-^nj%fKYqxfON##SnCUDm-)uM~?=T>8{X^YFc6yx}cVp_~i^(`X1pAMoqs}|jI
zt2$9v?yf%}%v|$MU%0f$pI}d%X-Sk8qabniosq7-OBvq-E4r^1RB+%$H}P>K{NYe{0rN1YG&FAI1CfLS
z5s|JqqLh0|8aF5e_Bj
z2W|#bgyrjbdAUkH7()tjF7LCzfh-0fH
zJn~ZwC>sjL+__%n&Xe48Zr*$7ez)I>Ht8wn^)}NG+j>EycPhjnTD1g?3nb{l6g~Im
z#SIIYbpfx8OT}ji;DWv@dtzGSb8-|oHg}%#f&5p~DgC0-x+m%v%B+=Y+UHZ~LwWYN
z%L@s8{Ub=Zr2@dB%*8TA^mxojF1^aZ>$Me>%;n@CW(6`Oa#wYB=_d0hqRN`2sy3478)bzA>
zTPN_Vmyn%hi0&I!?Uf2O%Bv|%PiOSrLiCMJHfYZHJneJO*=cVV{Nis@%5(HR&o6PR7F6C{-%fB`K#(ErZ-nJRvAbyYt9hTsv(U)?meM
zDK-M~`-T~P6?hW%?TuSer%@?|uVjbb-EvdiqtKY5Mf)^TqpHt`q`6NQx94FQT;OA6
zF<0YYKcct09sjCfTB~F{!-yQ|JwnHD{#V1?+(a=GNo_|_LP=>x2a3^pmQyTEfKB94i4@=6v
z*)n++3l2sVfbu5`31;KeJU6Ycy-6aZ!|h>CN@bm=WwW^Cq)N{2HzY{a=bt#_Bc6XC
z#1?1K+%(7J@Kql$$)7!n4;`E6E#vE_$~}EZKB!b!^#+c*gl{<2X2H2RGWcTjC=O-d
zt#k}Nejm)$X_z&Mp|@J}{AgLE3hH_<&9{_13R5Nk^In2t(BtrqqrL@JwOxW)O{8>;
z6cKjlC>kUYmt{(iFs<^u=~d`koO4IMGy`&9w;i0^*|7XIbw4M%y#8uk@7{31nix?e
z@EY^LM&=__^3m!bL0+JdWa%k5chR^_AcCSmkVKTquv5g)PE*n?Fu)aO2B)L_?l*S(CxQ<{RvuTD
z2rpBpW{`;Oi`T^LTlgPcb)V0A0DoLxeTga&L$ia+VLiZMoh8XzrfeL-JDzj^q1QP>
zuoyDfFux4C649mPtlMgT>=A6cgk(dUG6msL&%~k_uvkqvvZ!aM-+!xP?(E5C
zPH2X$+IZ*6n5r8@JOXEp>w$BO7$lQq4sC_>78o9KujIA4a);B!T#;-HGGg`96Bs;z
z3bF7ugvvW#OXIJVp+IhL*Zv*%qjA+({s_E>Al`(3;NIHQ)zU)K-POj?>L>iMha~TI
zgMkub?Mn~3cN_|^KsK|vjHAfd!_z3q3Io^$jRHfkRoHf;#qleS*R_$yYn?zRKDq_b
zw!DN-IB`s_od#JV*YYNY@sWBm!`^x#GLxQ-It}uumgUdA2U^cUg=+V8^ck`7qw6jF
zT=s0S7|>d;|Fu?>O#S7HHsTu_1XDqX&98-%xw@;9vm2+mldI()ryT#?^CFhfKlzbe
zH<&Pd5&at;{XU<9hmcfNHO`@Fw+T`If|ToIH3N=9!&Zl}K2($cEc1n1#|t+FvAJ!Q
z%R3v|4kb~z7>b=y`Yd(11=`gB_8IvqT
z2s~pvsdXc2h=oVz@d|omTr`D;rA1oU8w~sp*q7oGxjqA%)10XE8U?|`_B*qCbq5s_Vm?~fbqY+pHA@*9pzhcqU+4;XvL`>Nq?M1Sr
z6GA-0_mQtCvEgJ8xH@)7rJ4NWlWJ3>~Mn}kdyz1nJ&I8}uY
zE)HD0l(8!(8&lirA}-ReO6wqI_GK4=)k|qFVq-QNOpI#_3pvtWG}_udkK{w&?(;^W
zUqsuY_*h;4+=T?XWiuI8oQdTgut3`KGxaMh3xRt+rtG6A7(Ugyv*4$@{vP)FeZ84k)Q77(i)E4mU>d33f;|{RM
z&FV?d>5=cFK#og8D<1mAo7x+!KjDjXhaC~*|NYST&*l1a{FftSb)~;M`1|qJpN2oi
z3Oob3-KEyP-{jTJ{d-%Ja
v{;~%Ez9KyQLtTG2|9c4htGPSbU(Ejqi0VqHh}8uE?jl~n2m$Az_;K|=SI=Sd
literal 0
HcmV?d00001
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStylerUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStylerUnitTest.java
new file mode 100644
index 0000000000..074e51919a
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStylerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.poi.excel.cellstyle;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Paths;
+
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.junit.Before;
+import org.junit.Test;
+
+public class CellStylerUnitTest {
+ private static String FILE_NAME = "com/baeldung/poi/excel/cellstyle/CellStyle.xlsx";
+ private static final String NEW_FILE_NAME = "CellStyleTest_output.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void setup() throws IOException, URISyntaxException {
+ fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
+ .toURI())
+ .toString();
+ }
+
+ @Test
+ public void testApplyWarningColor() throws IOException {
+ Workbook workbook = new XSSFWorkbook(fileLocation);
+ Sheet sheet = workbook.getSheetAt(0);
+ Row row1 = sheet.createRow(0);
+ row1.setHeightInPoints((short) 40);
+
+ CellStyler styler = new CellStyler();
+ CellStyle style = styler.createWarningColor(workbook);
+
+ Cell cell1 = row1.createCell(0);
+ cell1.setCellStyle(style);
+ cell1.setCellValue("Hello");
+
+ Cell cell2 = row1.createCell(1);
+ cell2.setCellStyle(style);
+ cell2.setCellValue("world!");
+
+ FileOutputStream outputStream = new FileOutputStream(NEW_FILE_NAME);
+ workbook.write(outputStream);
+ outputStream.close();
+ workbook.close();
+ }
+}
From a5defe6121e639ccc79a96d15d8f365acd7b87b2 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:26:50 +0800
Subject: [PATCH 022/235] Update README.md
---
core-java-modules/core-java-security-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-security-3/README.md b/core-java-modules/core-java-security-3/README.md
index 30cfd8a947..8623fa5aa8 100644
--- a/core-java-modules/core-java-security-3/README.md
+++ b/core-java-modules/core-java-security-3/README.md
@@ -8,4 +8,5 @@ This module contains articles about core Java Security
- [Enabling Unlimited Strength Cryptography in Java](https://www.baeldung.com/jce-enable-unlimited-strength)
- [Initialization Vector for Encryption](https://www.baeldung.com/java-encryption-iv)
- [HMAC in Java](https://www.baeldung.com/java-hmac)
+- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
From 34e7cc8112a2328c16ccc0a1542e7dfefd9eec52 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:31:09 +0800
Subject: [PATCH 023/235] Update README.md
---
java-collections-maps-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md
index 87817331b5..75842c85a4 100644
--- a/java-collections-maps-3/README.md
+++ b/java-collections-maps-3/README.md
@@ -6,3 +6,4 @@
- [Optimizing HashMap’s Performance](https://www.baeldung.com/java-hashmap-optimize-performance)
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map – keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
+- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
From af7c764ce9499eed8ca1536087bad3b4658bc57e Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:35:42 +0800
Subject: [PATCH 024/235] Update README.md
---
core-java-modules/core-java-lang-oop-constructors/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md
index 6083f1d0df..ddd0ec6afb 100644
--- a/core-java-modules/core-java-lang-oop-constructors/README.md
+++ b/core-java-modules/core-java-lang-oop-constructors/README.md
@@ -10,3 +10,4 @@ This module contains article about constructors in Java
- [Throwing Exceptions in Constructors](https://www.baeldung.com/java-constructors-exceptions)
- [Constructors in Java Abstract Classes](https://www.baeldung.com/java-abstract-classes-constructors)
- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error)
+- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)
From 85c929b74bab6bf63e7ef5e129ca8cefcd811fee Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:38:14 +0800
Subject: [PATCH 025/235] Update README.md
---
persistence-modules/spring-data-jpa-repo-2/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md
index be5bab1b56..6403510e6f 100644
--- a/persistence-modules/spring-data-jpa-repo-2/README.md
+++ b/persistence-modules/spring-data-jpa-repo-2/README.md
@@ -1,7 +1,9 @@
## Spring Data JPA - Repositories
### Relevant Articles:
+
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
+- [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager)
- More articles: [[<-- prev]](../spring-data-jpa-repo)
From f1bdc807b55af870efa4d99e7f2fb6569c9d00ea Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:39:48 +0800
Subject: [PATCH 026/235] Update README.md
---
core-java-modules/core-java-concurrency-collections-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md
index 6ad6529efc..692c218395 100644
--- a/core-java-modules/core-java-concurrency-collections-2/README.md
+++ b/core-java-modules/core-java-concurrency-collections-2/README.md
@@ -2,4 +2,5 @@
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
+- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)
From f92a336512c6c676b0c602fba0ad65a5c0c7d762 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:41:44 +0800
Subject: [PATCH 027/235] Update README.md
---
core-java-modules/core-java-jndi/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-jndi/README.md b/core-java-modules/core-java-jndi/README.md
index b0b23fc0d0..9c6f489841 100644
--- a/core-java-modules/core-java-jndi/README.md
+++ b/core-java-modules/core-java-jndi/README.md
@@ -3,3 +3,4 @@
- [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi)
- [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth)
+- [Testing LDAP Connections With Java](https://www.baeldung.com/java-test-ldap-connections)
From 3874415836e757b78b4ebc3986903d5268326caa Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:45:09 +0800
Subject: [PATCH 028/235] Update README.md
---
core-java-modules/core-java-nio-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md
index 52efa0330a..9152a494d8 100644
--- a/core-java-modules/core-java-nio-2/README.md
+++ b/core-java-modules/core-java-nio-2/README.md
@@ -11,4 +11,5 @@ This module contains articles about core Java non-blocking input and output (IO)
- [How to Lock a File in Java](https://www.baeldung.com/java-lock-files)
- [Java NIO DatagramChannel](https://www.baeldung.com/java-nio-datagramchannel)
- [Java – Path vs File](https://www.baeldung.com/java-path-vs-file)
+- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [[<-- Prev]](/core-java-modules/core-java-nio)
From 61030e497fa37630bfd9fe58547bfd5e6f69a18e Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:47:15 +0800
Subject: [PATCH 029/235] Update README.md
---
javafx/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/javafx/README.md b/javafx/README.md
index 8ef06eb012..5e034adb38 100644
--- a/javafx/README.md
+++ b/javafx/README.md
@@ -3,6 +3,8 @@
This module contains articles about JavaFX.
### Relevant Articles:
+
- [Introduction to JavaFX](https://www.baeldung.com/javafx)
- [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items)
+- [Adding EventHandler to JavaFX Button](https://www.baeldung.com/javafx-button-eventhandler)
From 2b6ef895558923377f8d2f5e333f26d8ba5aeca3 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:48:52 +0800
Subject: [PATCH 030/235] Update README.md
---
core-java-modules/core-java-security-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-security-3/README.md b/core-java-modules/core-java-security-3/README.md
index 8623fa5aa8..31969cd270 100644
--- a/core-java-modules/core-java-security-3/README.md
+++ b/core-java-modules/core-java-security-3/README.md
@@ -9,4 +9,5 @@ This module contains articles about core Java Security
- [Initialization Vector for Encryption](https://www.baeldung.com/java-encryption-iv)
- [HMAC in Java](https://www.baeldung.com/java-hmac)
- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
+- [Computing an X509 Certificate’s Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
From 21316676200ddea1dc5a835b25e5aa7612807f45 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 17:59:31 +0800
Subject: [PATCH 031/235] Update README.md
---
spring-cloud/spring-cloud-gateway/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/spring-cloud/spring-cloud-gateway/README.md b/spring-cloud/spring-cloud-gateway/README.md
index 90e81fe9a2..6b199977e3 100644
--- a/spring-cloud/spring-cloud-gateway/README.md
+++ b/spring-cloud/spring-cloud-gateway/README.md
@@ -3,7 +3,9 @@
This module contains articles about Spring Cloud Gateway
### Relevant Articles:
+
- [Exploring the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway)
- [Writing Custom Spring Cloud Gateway Filters](https://www.baeldung.com/spring-cloud-custom-gateway-filters)
- [Spring Cloud Gateway Routing Predicate Factories](https://www.baeldung.com/spring-cloud-gateway-routing-predicate-factories)
- [Spring Cloud Gateway WebFilter Factories](https://www.baeldung.com/spring-cloud-gateway-webfilter-factories)
+- [Using Spring Cloud Gateway with OAuth 2.0 Patterns](https://www.baeldung.com/spring-cloud-gateway-oauth2)
From 7aaf834ff862c1248c765129fe89dfaca38edb9c Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 26 Jan 2022 18:02:03 +0800
Subject: [PATCH 032/235] Update README.md
---
apache-poi/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/apache-poi/README.md b/apache-poi/README.md
index 34e7631087..ed30d9a4f3 100644
--- a/apache-poi/README.md
+++ b/apache-poi/README.md
@@ -14,4 +14,5 @@ This module contains articles about Apache POI.
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
- [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders)
- [Reading Values From Excel in Java](https://www.baeldung.com/java-read-dates-excel)
+- [Change Cell Font Style with Apache POI](https://www.baeldung.com/apache-poi-change-cell-font)
- More articles: [[next -->]](../apache-poi-2)
From 57f91f9948a4350e851e42eba42638ccb8139daa Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Thu, 27 Jan 2022 10:15:16 +0100
Subject: [PATCH 033/235] JAVA-9605: Disable security for the integration tests
---
.../secondservice/SecondServiceIntegrationTest.java | 4 +++-
.../customfilters/service/ServiceIntegrationTest.java | 4 +++-
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/secondservice/SecondServiceIntegrationTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/secondservice/SecondServiceIntegrationTest.java
index 6b2a432d20..f4b3d0f00d 100644
--- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/secondservice/SecondServiceIntegrationTest.java
+++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/secondservice/SecondServiceIntegrationTest.java
@@ -2,12 +2,14 @@ package com.baeldung.springcloudgateway.customfilters.secondservice;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.test.web.reactive.server.WebTestClient;
import com.baeldung.springcloudgateway.customfilters.secondservice.web.SecondServiceRestController;
-@WebFluxTest(SecondServiceRestController.class)
+@WebFluxTest(controllers = SecondServiceRestController.class,
+ excludeAutoConfiguration = ReactiveSecurityAutoConfiguration.class)
public class SecondServiceIntegrationTest {
@Autowired
diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/service/ServiceIntegrationTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/service/ServiceIntegrationTest.java
index bfb3f23f0d..9990cd003c 100644
--- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/service/ServiceIntegrationTest.java
+++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/customfilters/service/ServiceIntegrationTest.java
@@ -2,13 +2,15 @@ package com.baeldung.springcloudgateway.customfilters.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.reactive.server.WebTestClient;
import com.baeldung.springcloudgateway.customfilters.service.web.ServiceRestController;
-@WebFluxTest(ServiceRestController.class)
+@WebFluxTest(controllers = ServiceRestController.class,
+ excludeAutoConfiguration = ReactiveSecurityAutoConfiguration.class)
public class ServiceIntegrationTest {
@Autowired
From 57495b7f15da1be2b561097ca7cc0f8a2de010a6 Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Fri, 28 Jan 2022 09:49:18 +0530
Subject: [PATCH 034/235] Remove unwanted dependencies
---
.../spring-data-jpa-enterprise-2/pom.xml | 22 -------------------
1 file changed, 22 deletions(-)
diff --git a/persistence-modules/spring-data-jpa-enterprise-2/pom.xml b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml
index 7efa5f504f..f35ee378d1 100644
--- a/persistence-modules/spring-data-jpa-enterprise-2/pom.xml
+++ b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml
@@ -22,14 +22,6 @@
org.springframework.boot
spring-boot-starter-data-jpa
-
- org.springframework.boot
- spring-boot-starter-data-jdbc
-
-
- org.springframework.boot
- spring-boot-starter-cache
-
com.h2database
h2
@@ -41,18 +33,4 @@
-
- src/main/java
-
-
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
\ No newline at end of file
From a8ce62042fb912b941b30fa775c630c8f6b21daf Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 28 Jan 2022 22:20:11 +0000
Subject: [PATCH 035/235] [JAVA-9019] Move sysout lines to info logging
---
.../baeldung/collections/iterators/Iterators.java | 13 ++++++-------
.../baeldung/collections/bitset/BitSetUnitTest.java | 10 +++++++---
.../src/test/resources/logback.xml | 13 +++++++++++++
3 files changed, 26 insertions(+), 10 deletions(-)
create mode 100644 core-java-modules/core-java-collections-3/src/test/resources/logback.xml
diff --git a/core-java-modules/core-java-collections-3/src/main/java/com/baeldung/collections/iterators/Iterators.java b/core-java-modules/core-java-collections-3/src/main/java/com/baeldung/collections/iterators/Iterators.java
index 23e6bbda77..4daf7dd9d1 100644
--- a/core-java-modules/core-java-collections-3/src/main/java/com/baeldung/collections/iterators/Iterators.java
+++ b/core-java-modules/core-java-collections-3/src/main/java/com/baeldung/collections/iterators/Iterators.java
@@ -1,17 +1,16 @@
package com.baeldung.collections.iterators;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
-/**
- * Source code https://github.com/eugenp/tutorials
- *
- * @author Santosh Thakur
- */
-
public class Iterators {
+ private static final Logger LOG = LoggerFactory.getLogger(Iterators.class);
+
public static int failFast1() {
ArrayList numbers = new ArrayList<>();
@@ -44,7 +43,7 @@ public class Iterators {
}
}
- System.out.println("using iterator's remove method = " + numbers);
+ LOG.debug("using iterator's remove method = {}", numbers);
iterator = numbers.iterator();
while (iterator.hasNext()) {
diff --git a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java
index d9340f45c1..7141dbf79f 100644
--- a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java
+++ b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java
@@ -3,6 +3,8 @@ package com.baeldung.collections.bitset;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.BitSet;
@@ -10,18 +12,20 @@ import static org.assertj.core.api.Assertions.assertThat;
public class BitSetUnitTest {
+ private static final Logger LOG = LoggerFactory.getLogger(BitSetUnitTest.class);
+
@Test
public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() {
boolean[] bits = new boolean[1024 * 1024];
- System.out.println(ClassLayout.parseInstance(bits).toPrintable());
+ LOG.debug(ClassLayout.parseInstance(bits).toPrintable());
}
@Test
public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() {
BitSet bitSet = new BitSet(1024 * 1024);
- System.out.println(GraphLayout.parseInstance(bitSet).toPrintable());
+ LOG.debug(GraphLayout.parseInstance(bitSet).toPrintable());
}
@Test
@@ -157,7 +161,7 @@ public class BitSetUnitTest {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
- bitSet.stream().forEach(System.out::println);
+ bitSet.stream().forEach(bit -> LOG.debug(String.valueOf(bit)));
assertThat(bitSet.stream().count()).isEqualTo(10);
}
diff --git a/core-java-modules/core-java-collections-3/src/test/resources/logback.xml b/core-java-modules/core-java-collections-3/src/test/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-modules/core-java-collections-3/src/test/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
From f72971181ef5722619a60c927ee59439a05fa46b Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 28 Jan 2022 22:50:49 +0000
Subject: [PATCH 036/235] [JAVA-9019] Logging clean up
---
.../concurrent/prioritytaskexecution/Job.java | 15 ++++--
.../forkjoin/CustomRecursiveAction.java | 10 ++--
.../PriorityJobSchedulerUnitTest.java | 16 +++----
.../Java8ForkJoinIntegrationTest.java | 19 ++++----
.../thread/join/ThreadJoinUnitTest.java | 48 +++++++++----------
.../src/test/resources/logback.xml | 13 +++++
6 files changed, 69 insertions(+), 52 deletions(-)
create mode 100644 core-java-modules/core-java-concurrency-advanced-2/src/test/resources/logback.xml
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java
index 9900d1c63d..b0866cb7f0 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java
@@ -1,9 +1,15 @@
package com.baeldung.concurrent.prioritytaskexecution;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public class Job implements Runnable {
- private String jobName;
- private JobPriority jobPriority;
-
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Job.class);
+
+ private final String jobName;
+ private final JobPriority jobPriority;
+
public Job(String jobName, JobPriority jobPriority) {
this.jobName = jobName;
this.jobPriority = jobPriority != null ? jobPriority : JobPriority.MEDIUM;
@@ -16,8 +22,7 @@ public class Job implements Runnable {
@Override
public void run() {
try {
- System.out.println("Job:" + jobName +
- " Priority:" + jobPriority);
+ LOGGER.debug("Job:{} Priority:{}", jobName, jobPriority);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
index ebe59e33b1..26d620ba07 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
@@ -1,19 +1,21 @@
package com.baeldung.forkjoin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
-import java.util.logging.Logger;
public class CustomRecursiveAction extends RecursiveAction {
+ final Logger logger = LoggerFactory.getLogger(CustomRecursiveAction.class);
+
private String workLoad = "";
private static final int THRESHOLD = 4;
- private static Logger logger = Logger.getAnonymousLogger();
-
public CustomRecursiveAction(String workLoad) {
this.workLoad = workLoad;
}
@@ -43,7 +45,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) {
String result = work.toUpperCase();
- logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
+ logger.debug("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java
index 1e67fe45c1..20e6a5ef5b 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java
@@ -3,9 +3,9 @@ package com.baeldung.concurrent.prioritytaskexecution;
import org.junit.Test;
public class PriorityJobSchedulerUnitTest {
- private static int POOL_SIZE = 1;
- private static int QUEUE_SIZE = 10;
-
+ private static final int POOL_SIZE = 1;
+ private static final int QUEUE_SIZE = 10;
+
@Test
public void whenMultiplePriorityJobsQueued_thenHighestPriorityJobIsPicked() {
Job job1 = new Job("Job1", JobPriority.LOW);
@@ -14,19 +14,19 @@ public class PriorityJobSchedulerUnitTest {
Job job4 = new Job("Job4", JobPriority.MEDIUM);
Job job5 = new Job("Job5", JobPriority.LOW);
Job job6 = new Job("Job6", JobPriority.HIGH);
-
+
PriorityJobScheduler pjs = new PriorityJobScheduler(POOL_SIZE, QUEUE_SIZE);
-
+
pjs.scheduleJob(job1);
pjs.scheduleJob(job2);
pjs.scheduleJob(job3);
pjs.scheduleJob(job4);
pjs.scheduleJob(job5);
pjs.scheduleJob(job6);
-
+
// ensure no tasks is pending before closing the scheduler
while (pjs.getQueuedTaskCount() != 0);
-
+
// delay to avoid job sleep (added for demo) being interrupted
try {
Thread.sleep(2000);
@@ -34,7 +34,7 @@ public class PriorityJobSchedulerUnitTest {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
-
+
pjs.closeScheduler();
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/forkjoin/Java8ForkJoinIntegrationTest.java b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/forkjoin/Java8ForkJoinIntegrationTest.java
index c469fe0195..ec10e2be79 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/forkjoin/Java8ForkJoinIntegrationTest.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/forkjoin/Java8ForkJoinIntegrationTest.java
@@ -1,18 +1,15 @@
package com.baeldung.forkjoin;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import com.baeldung.forkjoin.util.PoolUtil;
+import org.junit.Before;
+import org.junit.Test;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.baeldung.forkjoin.CustomRecursiveAction;
-import com.baeldung.forkjoin.CustomRecursiveTask;
-import com.baeldung.forkjoin.util.PoolUtil;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class Java8ForkJoinIntegrationTest {
@@ -63,11 +60,11 @@ public class Java8ForkJoinIntegrationTest {
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.execute(customRecursiveTask);
- int result = customRecursiveTask.join();
+ customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
forkJoinPool.submit(customRecursiveTask);
- int resultTwo = customRecursiveTask.join();
+ customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
}
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java
index 85cff51eb3..dc30ce6c74 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java
@@ -1,12 +1,12 @@
package com.baeldung.thread.join;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.logging.Logger;
-
import org.junit.Ignore;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
* Demonstrates Thread.join behavior.
@@ -14,55 +14,55 @@ import org.junit.Test;
*/
public class ThreadJoinUnitTest {
- final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
+ private static final Logger LOGGER = LoggerFactory.getLogger(ThreadJoinUnitTest.class);
- class SampleThread extends Thread {
- public int processingCount = 0;
+ static class SampleThread extends Thread {
+ public int processingCount;
SampleThread(int processingCount) {
this.processingCount = processingCount;
- LOGGER.info("Thread " + this.getName() + " created");
+ LOGGER.debug("Thread " + this.getName() + " created");
}
@Override
public void run() {
- LOGGER.info("Thread " + this.getName() + " started");
+ LOGGER.debug("Thread " + this.getName() + " started");
while (processingCount > 0) {
try {
Thread.sleep(1000); // Simulate some work being done by thread
} catch (InterruptedException e) {
- LOGGER.info("Thread " + this.getName() + " interrupted.");
+ LOGGER.debug("Thread " + this.getName() + " interrupted.");
}
processingCount--;
- LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
+ LOGGER.debug("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
}
- LOGGER.info("Thread " + this.getName() + " exiting");
+ LOGGER.debug("Thread " + this.getName() + " exiting");
}
}
@Test
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
Thread t1 = new SampleThread(0);
- LOGGER.info("Invoking join.");
+ LOGGER.debug("Invoking join.");
t1.join();
- LOGGER.info("Returned from join");
- LOGGER.info("Thread state is" + t1.getState());
+ LOGGER.debug("Returned from join");
+ LOGGER.debug("Thread state is" + t1.getState());
assertFalse(t1.isAlive());
}
@Test
- public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
+ public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
throws InterruptedException {
Thread t2 = new SampleThread(1);
t2.start();
- LOGGER.info("Invoking join.");
+ LOGGER.debug("Invoking join.");
t2.join();
- LOGGER.info("Returned from join");
+ LOGGER.debug("Returned from join");
assertFalse(t2.isAlive());
}
@Test
- public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
+ public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
throws InterruptedException {
Thread t3 = new SampleThread(10);
t3.start();
@@ -72,18 +72,18 @@ public class ThreadJoinUnitTest {
@Test
@Ignore
- public void givenThreadTerminated_checkForEffect_notGuaranteed()
+ public void givenThreadTerminated_checkForEffect_notGuaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
//not guaranteed to stop even if t4 finishes.
do {
-
- } while (t4.processingCount > 0);
+
+ } while (t4.processingCount > 0);
}
@Test
- public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
+ public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/test/resources/logback.xml b/core-java-modules/core-java-concurrency-advanced-2/src/test/resources/logback.xml
new file mode 100644
index 0000000000..b2fa0488f3
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/test/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
From c69343c8537443d278ff8fa14da586efb93ff3d8 Mon Sep 17 00:00:00 2001
From: sebx59
Date: Sat, 29 Jan 2022 06:58:08 +0100
Subject: [PATCH 037/235] Example class for BAEL-4888 (#11728)
code used to illustrate the article about retrieving the MongoDB ID
---
.../mongo/objectid/RetrieveIdExample.java | 57 +++++++++++++++++++
1 file changed, 57 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
new file mode 100644
index 0000000000..74279bbfcd
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
@@ -0,0 +1,57 @@
+package com.baeldung.mongo.objectid;
+
+import java.util.Date;
+
+import org.bson.Document;
+import org.bson.types.ObjectId;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+
+public class RetrieveIdExample {
+
+ public static void main(String[] args) {
+
+ try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) {
+
+ MongoDatabase database = mongoClient.getDatabase("myMongoDb");
+ MongoCollection collection = database.getCollection("example");
+
+// Create document with user-generated ID
+ ObjectId generatedId = new ObjectId();
+
+ System.out.println(generatedId.toString());
+
+ Document document = new Document();
+ document.put("_id", generatedId);
+ document.put("name", "Shubham");
+ document.put("company", "Baeldung");
+ collection.insertOne(document);
+
+// Check that the ID of the document is still the one we set
+ System.out.println(document.getObjectId("_id").equals(generatedId));
+
+
+// Create a second document by injecting the ID in the constructor
+
+ ObjectId generatedId2 = ObjectId.get();
+
+ Document document2 = new Document("_id", generatedId2);
+ document2.put("name", "Shubham");
+ document2.put("company", "Baeldung");
+ collection.insertOne(document2);
+
+ Date creationDate = generatedId.getDate();
+ System.out.println(creationDate);
+
+ int timestamp = generatedId.getTimestamp();
+
+ } catch (Exception e) {
+
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+}
From fc145be4a87f3994725f6f7bd360f35296521401 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Sat, 29 Jan 2022 16:24:15 +0000
Subject: [PATCH 038/235] [JAVA-9019] Logging clean up
---
.../core-java-io/src/main/resources/log4j.properties | 6 ------
.../src/main/resources/log4jstructuraldp.properties | 9 ---------
.../core-java-io/src/main/resources/logback.xml | 5 -----
3 files changed, 20 deletions(-)
delete mode 100644 core-java-modules/core-java-io/src/main/resources/log4j.properties
delete mode 100644 core-java-modules/core-java-io/src/main/resources/log4jstructuraldp.properties
diff --git a/core-java-modules/core-java-io/src/main/resources/log4j.properties b/core-java-modules/core-java-io/src/main/resources/log4j.properties
deleted file mode 100644
index 621cf01735..0000000000
--- a/core-java-modules/core-java-io/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-log4j.rootLogger=DEBUG, A1
-
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java-io/src/main/resources/log4jstructuraldp.properties b/core-java-modules/core-java-io/src/main/resources/log4jstructuraldp.properties
deleted file mode 100644
index 5bc2bfe4b9..0000000000
--- a/core-java-modules/core-java-io/src/main/resources/log4jstructuraldp.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-
-# Root logger
-log4j.rootLogger=INFO, file, stdout
-
-# Write to console
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.Target=System.out
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java-io/src/main/resources/logback.xml b/core-java-modules/core-java-io/src/main/resources/logback.xml
index 617917dca2..c404714347 100644
--- a/core-java-modules/core-java-io/src/main/resources/logback.xml
+++ b/core-java-modules/core-java-io/src/main/resources/logback.xml
@@ -7,13 +7,8 @@
-
-
-
-
-
From e046bc734b03023f959d008e143e2d8337cc0e6b Mon Sep 17 00:00:00 2001
From: mdabrowski-eu
Date: Sat, 29 Jan 2022 23:23:37 +0100
Subject: [PATCH 039/235] BAEL-5301 Fix indentation
---
.../feign/retry/Custom5xxErrorDecoderUnitTest.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
index b51a1a65b3..8c43b42b76 100644
--- a/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
+++ b/feign/src/test/java/com/baeldung/feign/retry/Custom5xxErrorDecoderUnitTest.java
@@ -43,9 +43,9 @@ public class Custom5xxErrorDecoderUnitTest {
@NotNull
private Response responseStub(int status) {
return Response.builder()
- .request(Request.create(
- Request.HttpMethod.GET, "url", new HashMap>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
- .status(status)
- .build();
+ .request(Request.create(
+ Request.HttpMethod.GET, "url", new HashMap<>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
+ .status(status)
+ .build();
}
}
From ad893be8ac4d6fea0f1e2799cad6b3c8c3ba40c1 Mon Sep 17 00:00:00 2001
From: palani-a
Date: Sun, 30 Jan 2022 22:12:18 +0530
Subject: [PATCH 040/235] Implementation for Simple Hexagonal Architecture
---
.../ConferenceApplication.java | 15 ++
.../controllers/SessionController.java | 54 ++++++++
.../controllers/SpeakerController.java | 57 ++++++++
.../simplehexagonal/domain/Session.java | 58 ++++++++
.../simplehexagonal/domain/Speaker.java | 90 ++++++++++++
.../domain/repository/SessionRepository.java | 17 +++
.../domain/repository/SpeakerRepository.java | 17 +++
.../domain/services/SessionService.java | 19 +++
.../domain/services/SessionServiceImpl.java | 40 ++++++
.../domain/services/SpeakerService.java | 19 +++
.../domain/services/SpeakerServiceImpl.java | 39 ++++++
.../config/BeanConfiguration.java | 30 ++++
.../repositories/SessionEntity.java | 99 ++++++++++++++
.../repositories/SessionJpaRepository.java | 9 ++
.../repositories/SessionRepositoryImpl.java | 42 ++++++
.../repositories/SpeakerEntity.java | 129 ++++++++++++++++++
.../repositories/SpeakerJpaRepository.java | 9 ++
.../repositories/SpeakerRepositoryImpl.java | 42 ++++++
.../resources/simple-hexagonal.properties | 8 ++
.../services/SessionServiceUnitTest.java | 74 ++++++++++
.../services/SpeakerServiceUnitTest.java | 74 ++++++++++
21 files changed, 941 insertions(+)
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
create mode 100644 ddd/src/main/resources/simple-hexagonal.properties
create mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
create mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
new file mode 100644
index 0000000000..106b013ab6
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.simplehexagonal;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.PropertySource;
+
+@SpringBootApplication(scanBasePackages = "com.baeldung.simplehexagonal")
+@PropertySource(value = { "classpath:simple-hexagonal.properties" })
+public class ConferenceApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ConferenceApplication.class, args);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
new file mode 100644
index 0000000000..5cc3880851
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
@@ -0,0 +1,54 @@
+package com.baeldung.simplehexagonal.application.controllers;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.simplehexagonal.domain.Session;
+import com.baeldung.simplehexagonal.domain.services.SessionService;
+
+@RestController
+@RequestMapping("/api/v1/sessions")
+public class SessionController {
+
+ private SessionService sessionService;
+
+ @Autowired
+ public SessionController(SessionService sessionService) {
+ this.sessionService = sessionService;
+ }
+
+ @GetMapping
+ public List findAll() {
+ return sessionService.findAll();
+ }
+
+ @GetMapping
+ @RequestMapping("{id}")
+ public Session get(@PathVariable Long id) {
+ return sessionService.get(id);
+ }
+
+ @PostMapping
+ public Session create(@RequestBody final Session session) {
+ return sessionService.create(session);
+ }
+
+ @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
+ public void delete(@PathVariable Long id) {
+ sessionService.delete(id);
+ }
+
+ @RequestMapping(value = "{id}", method = RequestMethod.PUT)
+ public Session update(@PathVariable Long id, @RequestBody Session session) {
+ return sessionService.update(id, session);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
new file mode 100644
index 0000000000..bea5370da7
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
@@ -0,0 +1,57 @@
+package com.baeldung.simplehexagonal.application.controllers;
+
+import java.util.List;
+
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+import com.baeldung.simplehexagonal.domain.services.SpeakerService;
+
+@RestController
+@RequestMapping("/api/v1/speakers")
+public class SpeakerController {
+
+ private SpeakerService speakerService;
+
+ @Autowired
+ public SpeakerController(SpeakerService speakerService) {
+ this.speakerService = speakerService;
+ }
+
+ @GetMapping
+ public List findAll() {
+ return speakerService.findAll();
+ }
+
+ @GetMapping
+ @RequestMapping("{id}")
+ public Speaker get(@PathVariable Long id) {
+ return speakerService.get(id);
+ }
+
+ @PostMapping
+ public Speaker create(@RequestBody final Speaker speaker) {
+ return speakerService.save(speaker);
+ }
+
+ @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
+ public void delete(@PathVariable Long id) {
+ speakerService.delete(id);
+ }
+
+ @RequestMapping(value = "{id}", method = RequestMethod.PUT)
+ public Speaker update(@PathVariable Long id, @RequestBody Speaker speaker) {
+ Speaker currentSpeaker = speakerService.get(id);
+ BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id");
+ return speakerService.save(currentSpeaker);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
new file mode 100644
index 0000000000..93c88b1461
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
@@ -0,0 +1,58 @@
+package com.baeldung.simplehexagonal.domain;
+
+import java.util.List;
+
+public class Session {
+
+ private Long sessionId;
+
+ private String sessionName;
+ private String sessionDescription;
+ private Integer sessionLength;
+
+ private List speakers;
+
+ public Session() {
+ }
+
+ public Long getSessionId() {
+ return sessionId;
+ }
+
+ public void setSessionId(Long sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ public String getSessionName() {
+ return sessionName;
+ }
+
+ public void setSessionName(String sessionName) {
+ this.sessionName = sessionName;
+ }
+
+ public String getSessionDescription() {
+ return sessionDescription;
+ }
+
+ public void setSessionDescription(String sessionDescription) {
+ this.sessionDescription = sessionDescription;
+ }
+
+ public Integer getSessionLength() {
+ return sessionLength;
+ }
+
+ public void setSessionLength(Integer sessionLength) {
+ this.sessionLength = sessionLength;
+ }
+
+ public List getSpeakers() {
+ return speakers;
+ }
+
+ public void setSpeakers(List speakers) {
+ this.speakers = speakers;
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
new file mode 100644
index 0000000000..078c7d38f7
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
@@ -0,0 +1,90 @@
+package com.baeldung.simplehexagonal.domain;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class Speaker {
+
+ private Long speakerId;
+
+ private String firstName;
+ private String lastName;
+ private String title;
+ private String company;
+ private String speakerBio;
+
+ private byte[] speakerPhoto;
+
+ @JsonIgnore
+ private List sessions;
+
+ public Speaker() {
+
+ }
+
+ public Long getSpeakerId() {
+ return speakerId;
+ }
+
+ public void setSpeakerId(Long speakerId) {
+ this.speakerId = speakerId;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getCompany() {
+ return company;
+ }
+
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ public String getSpeakerBio() {
+ return speakerBio;
+ }
+
+ public void setSpeakerBio(String speakerBio) {
+ this.speakerBio = speakerBio;
+ }
+
+ public byte[] getSpeakerPhoto() {
+ return speakerPhoto;
+ }
+
+ public void setSpeakerPhoto(byte[] speakerPhoto) {
+ this.speakerPhoto = speakerPhoto;
+ }
+
+ public List getSessions() {
+ return sessions;
+ }
+
+ public void setSessions(List sessions) {
+ this.sessions = sessions;
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
new file mode 100644
index 0000000000..7011506ffb
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
@@ -0,0 +1,17 @@
+package com.baeldung.simplehexagonal.domain.repository;
+
+import java.util.List;
+
+import com.baeldung.simplehexagonal.domain.Session;
+
+public interface SessionRepository {
+
+ List findAll();
+
+ Session findById(Long id);
+
+ Session save(Session session);
+
+ void deleteById(Long id);
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
new file mode 100644
index 0000000000..a12863f85f
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
@@ -0,0 +1,17 @@
+package com.baeldung.simplehexagonal.domain.repository;
+
+import java.util.List;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+
+public interface SpeakerRepository {
+
+ List findAll();
+
+ Speaker findById(Long id);
+
+ Speaker save(Speaker Speaker);
+
+ void deleteById(Long id);
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
new file mode 100644
index 0000000000..eff942672e
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
@@ -0,0 +1,19 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import java.util.List;
+
+import com.baeldung.simplehexagonal.domain.Session;
+
+public interface SessionService {
+
+ List findAll();
+
+ Session get(Long id);
+
+ Session create(Session session);
+
+ void delete(Long id);
+
+ Session update(Long id, Session session);
+
+}
\ No newline at end of file
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
new file mode 100644
index 0000000000..abf8ea1f86
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
@@ -0,0 +1,40 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import java.util.List;
+
+import org.springframework.beans.BeanUtils;
+
+import com.baeldung.simplehexagonal.domain.Session;
+import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
+
+public class SessionServiceImpl implements SessionService {
+
+ private SessionRepository sessionRepository;
+
+ public SessionServiceImpl(SessionRepository sessionRepository) {
+ this.sessionRepository = sessionRepository;
+ }
+
+ public List findAll() {
+ return sessionRepository.findAll();
+ }
+
+ public Session get(Long id) {
+ return sessionRepository.findById(id);
+ }
+
+ public Session create(Session session) {
+ return sessionRepository.save(session);
+ }
+
+ public void delete(Long id) {
+ sessionRepository.deleteById(id);
+ }
+
+ public Session update(Long id, Session session) {
+ Session currentSession = sessionRepository.findById(id);
+ BeanUtils.copyProperties(session, currentSession, "session_id");
+ return sessionRepository.save(currentSession);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
new file mode 100644
index 0000000000..041fb24fe1
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
@@ -0,0 +1,19 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import java.util.List;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+
+public interface SpeakerService {
+
+ List findAll();
+
+ Speaker get(Long id);
+
+ Speaker save(Speaker speaker);
+
+ void delete(Long id);
+
+ Speaker update(Long id, Speaker speaker);
+
+}
\ No newline at end of file
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
new file mode 100644
index 0000000000..cf01259983
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
@@ -0,0 +1,39 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import java.util.List;
+
+import org.springframework.beans.BeanUtils;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
+
+public class SpeakerServiceImpl implements SpeakerService {
+
+ private SpeakerRepository speakerRepository;
+
+ public SpeakerServiceImpl(SpeakerRepository speakerRepository) {
+ this.speakerRepository = speakerRepository;
+ }
+
+ public List findAll() {
+ return speakerRepository.findAll();
+ }
+
+ public Speaker get(Long id) {
+ return speakerRepository.findById(id);
+ }
+
+ public Speaker save(Speaker speaker) {
+ return speakerRepository.save(speaker);
+ }
+
+ public void delete(Long id) {
+ speakerRepository.deleteById(id);
+ }
+
+ public Speaker update(Long id, Speaker speaker) {
+ Speaker currentSpeaker = speakerRepository.findById(id);
+ BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id");
+ return speakerRepository.save(currentSpeaker);
+ }
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
new file mode 100644
index 0000000000..c1875354d9
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
@@ -0,0 +1,30 @@
+package com.baeldung.simplehexagonal.infrastructure.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+
+import com.baeldung.simplehexagonal.ConferenceApplication;
+import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
+import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
+import com.baeldung.simplehexagonal.domain.services.SessionService;
+import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl;
+import com.baeldung.simplehexagonal.domain.services.SpeakerService;
+import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl;
+
+@Configuration
+@ComponentScan(basePackageClasses = ConferenceApplication.class)
+@EnableJpaRepositories(basePackages = "com.baeldung.simplehexagonal")
+public class BeanConfiguration {
+
+ @Bean
+ SessionService sessionService(SessionRepository sessionRepository) {
+ return new SessionServiceImpl(sessionRepository);
+ }
+
+ @Bean
+ SpeakerService speakerService(SpeakerRepository speakerRepository) {
+ return new SpeakerServiceImpl(speakerRepository);
+ }
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
new file mode 100644
index 0000000000..b9d9c765da
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
@@ -0,0 +1,99 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import java.util.List;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+
+import com.baeldung.simplehexagonal.domain.Session;
+import com.baeldung.simplehexagonal.domain.Speaker;
+
+@Entity(name = "sessions")
+public class SessionEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long session_id;
+
+ private String session_name;
+ private String session_description;
+ private Integer session_length;
+
+ @ManyToMany
+ @JoinTable(name = "session_speakers", joinColumns = @JoinColumn(name = "session_id"), inverseJoinColumns = @JoinColumn(name = "speaker_id"))
+ private List speakerEntities;
+
+ public SessionEntity() {
+ }
+
+ public SessionEntity(Session session) {
+ this.setSession_id(session.getSessionId());
+ this.setSession_name(session.getSessionName());
+ this.setSession_description(session.getSessionDescription());
+ this.setSession_length(session.getSessionLength());
+ List speakerEntities = session.getSpeakers()
+ .stream()
+ .map(it -> new SpeakerEntity(it))
+ .toList();
+ this.speakerEntities = speakerEntities;
+ }
+
+ public Session toSession() {
+ Session session = new Session();
+ session.setSessionId(session_id);
+ session.setSessionName(session_name);
+ session.setSessionDescription(session_description);
+ session.setSessionLength(session_length);
+ List speakers = speakerEntities.stream()
+ .map(it -> it.toSpeaker())
+ .toList();
+ session.setSpeakers(speakers);
+ return session;
+ }
+
+ public Long getSession_id() {
+ return session_id;
+ }
+
+ public void setSession_id(Long session_id) {
+ this.session_id = session_id;
+ }
+
+ public String getSession_name() {
+ return session_name;
+ }
+
+ public void setSession_name(String session_name) {
+ this.session_name = session_name;
+ }
+
+ public String getSession_description() {
+ return session_description;
+ }
+
+ public void setSession_description(String session_description) {
+ this.session_description = session_description;
+ }
+
+ public Integer getSession_length() {
+ return session_length;
+ }
+
+ public void setSession_length(Integer session_length) {
+ this.session_length = session_length;
+ }
+
+ public List getSpeakerEntities() {
+ return speakerEntities;
+ }
+
+ public void setSpeakerEntities(List speakerEntities) {
+ this.speakerEntities = speakerEntities;
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
new file mode 100644
index 0000000000..83cc944dd6
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface SessionJpaRepository extends JpaRepository {
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
new file mode 100644
index 0000000000..3af9021fff
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
@@ -0,0 +1,42 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import com.baeldung.simplehexagonal.domain.Session;
+import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
+
+@Component
+public class SessionRepositoryImpl implements SessionRepository {
+
+ @Autowired
+ private SessionJpaRepository sessionJpaRepository;
+
+ @Override
+ public List findAll() {
+ return sessionJpaRepository.findAll()
+ .stream()
+ .map(SessionEntity::toSession)
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public Session findById(Long id) {
+ SessionEntity sessionEntity = sessionJpaRepository.getById(id);
+ return sessionEntity.toSession();
+ }
+
+ @Override
+ public Session save(Session session) {
+ return sessionJpaRepository.saveAndFlush(new SessionEntity(session))
+ .toSession();
+ }
+
+ public void deleteById(Long id) {
+ sessionJpaRepository.deleteById(id);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
new file mode 100644
index 0000000000..8937ac578f
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
@@ -0,0 +1,129 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import java.util.List;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Lob;
+import javax.persistence.ManyToMany;
+
+import org.hibernate.annotations.Type;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+@Entity(name = "speakers")
+public class SpeakerEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long speaker_id;
+
+ private String first_name;
+ private String last_name;
+ private String title;
+ private String company;
+ private String speaker_bio;
+
+ @Lob
+ @Type(type = "org.hibernate.type.BinaryType")
+ private byte[] speaker_photo;
+
+ @JsonIgnore
+ @ManyToMany(mappedBy = "speakerEntities", fetch = FetchType.LAZY)
+ private List sessionEntities;
+
+ public SpeakerEntity() {
+
+ }
+
+ public SpeakerEntity(Speaker speaker) {
+ this.setSpeaker_id(speaker.getSpeakerId());
+ this.setFirst_name(speaker.getFirstName());
+ this.setLast_name(speaker.getLastName());
+ this.setTitle(speaker.getTitle());
+ this.setCompany(speaker.getCompany());
+ this.setSpeaker_bio(speaker.getSpeakerBio());
+ this.setSpeaker_photo(speaker.getSpeakerPhoto());
+ }
+
+ public Speaker toSpeaker() {
+ Speaker speaker = new Speaker();
+ speaker.setSpeakerId(speaker_id);
+ speaker.setFirstName(first_name);
+ speaker.setLastName(last_name);
+ speaker.setTitle(title);
+ speaker.setCompany(company);
+ speaker.setSpeakerBio(speaker_bio);
+ speaker.setSpeakerPhoto(speaker_photo);
+ return speaker;
+ }
+
+ public Long getSpeaker_id() {
+ return speaker_id;
+ }
+
+ public void setSpeaker_id(Long speaker_id) {
+ this.speaker_id = speaker_id;
+ }
+
+ public String getFirst_name() {
+ return first_name;
+ }
+
+ public void setFirst_name(String first_name) {
+ this.first_name = first_name;
+ }
+
+ public String getLast_name() {
+ return last_name;
+ }
+
+ public void setLast_name(String last_name) {
+ this.last_name = last_name;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getCompany() {
+ return company;
+ }
+
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ public String getSpeaker_bio() {
+ return speaker_bio;
+ }
+
+ public void setSpeaker_bio(String speaker_bio) {
+ this.speaker_bio = speaker_bio;
+ }
+
+ public byte[] getSpeaker_photo() {
+ return speaker_photo;
+ }
+
+ public void setSpeaker_photo(byte[] speaker_photo) {
+ this.speaker_photo = speaker_photo;
+ }
+
+ public List getSessionEntities() {
+ return sessionEntities;
+ }
+
+ public void setSessionEntities(List sessionEntities) {
+ this.sessionEntities = sessionEntities;
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
new file mode 100644
index 0000000000..9bbce066fb
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface SpeakerJpaRepository extends JpaRepository {
+
+}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
new file mode 100644
index 0000000000..294bd0a1ff
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
@@ -0,0 +1,42 @@
+package com.baeldung.simplehexagonal.infrastructure.repositories;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
+
+@Component
+public class SpeakerRepositoryImpl implements SpeakerRepository {
+
+ @Autowired
+ private SpeakerJpaRepository speakerJpaRepository;
+
+ @Override
+ public List findAll() {
+ return speakerJpaRepository.findAll()
+ .stream()
+ .map(SpeakerEntity::toSpeaker)
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public Speaker findById(Long id) {
+ SpeakerEntity speakerEntity = speakerJpaRepository.getById(id);
+ return speakerEntity.toSpeaker();
+ }
+
+ @Override
+ public Speaker save(Speaker speaker) {
+ return speakerJpaRepository.saveAndFlush(new SpeakerEntity(speaker))
+ .toSpeaker();
+ }
+
+ public void deleteById(Long id) {
+ speakerJpaRepository.deleteById(id);
+ }
+
+}
diff --git a/ddd/src/main/resources/simple-hexagonal.properties b/ddd/src/main/resources/simple-hexagonal.properties
new file mode 100644
index 0000000000..6277d15543
--- /dev/null
+++ b/ddd/src/main/resources/simple-hexagonal.properties
@@ -0,0 +1,8 @@
+spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration
+spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
+spring.datasource.username=postgres
+spring.datasource.password=admin
+spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.show-sql=true
+spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
\ No newline at end of file
diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
new file mode 100644
index 0000000000..3fdc34e402
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.util.Assert.notNull;
+
+import java.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import com.baeldung.simplehexagonal.domain.Session;
+import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
+import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl;
+
+public class SessionServiceUnitTest {
+
+ private SessionServiceImpl sessionService;
+
+ private SessionRepository sessionRepository;
+
+ Session session;
+
+ @BeforeEach
+ void setUp() {
+ sessionRepository = mock(SessionRepository.class);
+ sessionService = new SessionServiceImpl(sessionRepository);
+
+ session = new Session();
+ session.setSessionId(1L);
+ session.setSessionName("Introduction to Hexagonal Architecture");
+ session.setSessionDescription("A quick and practical eample of Hexagonal Architecture");
+ session.setSessionLength(30);
+
+ when(sessionRepository.save(Mockito.any())).thenReturn(session);
+ when(sessionRepository.findById(1L)).thenReturn(session);
+ }
+
+ @Test
+ void testFindAll() {
+ List list = sessionService.findAll();
+ notNull(list, "should not return null");
+ }
+
+ @Test
+ void testGet() {
+ Session mySession = sessionService.get(1L);
+ notNull(mySession, "should not return null");
+ }
+
+ @Test
+ void testCreate() {
+ session = sessionService.create(new Session());
+ notNull(session.getSessionId(), "Id should be populated");
+ }
+
+ @Test
+ void testDelete() {
+ try {
+ sessionService.delete(1L);
+ } catch (Exception e) {
+ fail("Should not throw error");
+ }
+ }
+
+ @Test
+ void testUpdate() {
+ Session updatedSession = sessionService.update(1L, new Session());
+ notNull(updatedSession, "Id should be populated");
+ }
+
+}
diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
new file mode 100644
index 0000000000..5fd3f9dcab
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.simplehexagonal.domain.services;
+
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.util.Assert.notNull;
+
+import java.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import com.baeldung.simplehexagonal.domain.Speaker;
+import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
+import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl;
+
+public class SpeakerServiceUnitTest {
+
+ private SpeakerServiceImpl speakerService;
+
+ private SpeakerRepository speakerRepository;
+
+ Speaker speaker;
+
+ @BeforeEach
+ void setUp() {
+ speakerRepository = mock(SpeakerRepository.class);
+ speakerService = new SpeakerServiceImpl(speakerRepository);
+
+ speaker = new Speaker();
+ speaker.setSpeakerId(1L);
+ speaker.setTitle("Mr");
+ speaker.setFirstName("Palani");
+ speaker.setLastName("Arun");
+
+ when(speakerRepository.save(Mockito.any())).thenReturn(speaker);
+ when(speakerRepository.findById(1L)).thenReturn(speaker);
+ }
+
+ @Test
+ void testFindAll() {
+ List list = speakerService.findAll();
+ notNull(list, "should not return null");
+ }
+
+ @Test
+ void testGet() {
+ Speaker mySpeaker = speakerService.get(1L);
+ notNull(mySpeaker, "should not return null");
+ }
+
+ @Test
+ void testCreate() {
+ speaker = speakerService.save(new Speaker());
+ notNull(speaker.getSpeakerId(), "Id should be populated");
+ }
+
+ @Test
+ void testDelete() {
+ try {
+ speakerService.delete(1L);
+ } catch (Exception e) {
+ fail("Should not throw error");
+ }
+ }
+
+ @Test
+ void testUpdate() {
+ Speaker updatedSpeaker = speakerService.update(1L, new Speaker());
+ notNull(updatedSpeaker, "Id should be populated");
+ }
+
+}
From 94a58e4d52d07dad1c341e9fb931fbf2b92b6a06 Mon Sep 17 00:00:00 2001
From: konanaw
Date: Mon, 31 Jan 2022 01:11:43 +0300
Subject: [PATCH 041/235] Problem: file 'sample.txt' has empty content after
downloading from DownloadServlet. Fix: file moved to webapps/WEB-INF
---
javax-servlets/src/main/webapp/{ => WEB-INF}/sample.txt | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename javax-servlets/src/main/webapp/{ => WEB-INF}/sample.txt (100%)
diff --git a/javax-servlets/src/main/webapp/sample.txt b/javax-servlets/src/main/webapp/WEB-INF/sample.txt
similarity index 100%
rename from javax-servlets/src/main/webapp/sample.txt
rename to javax-servlets/src/main/webapp/WEB-INF/sample.txt
From 6f6b8e23e00267cde3b424bcf6923ca4450430d4 Mon Sep 17 00:00:00 2001
From: makapszenna <66560584+makapszenna@users.noreply.github.com>
Date: Mon, 31 Jan 2022 04:40:53 +0100
Subject: [PATCH 042/235] BAEL-5308 An Introduction to Domain Graph Service
(DGS) Framework (#11718)
Co-authored-by: Adrianna Zychewicz
---
graphql/graphql-dgs/pom.xml | 91 +++++++++++++++++++
.../java/com/bealdung/graphqlDGS/Album.java | 25 +++++
.../graphqlDGS/AlbumsDataFetcher.java | 28 ++++++
.../com/bealdung/graphqlDGS/Application.java | 13 +++
.../src/main/resources/application.properties | 1 +
.../src/main/resources/schema/schema.graphqls | 9 ++
pom.xml | 1 +
7 files changed, 168 insertions(+)
create mode 100644 graphql/graphql-dgs/pom.xml
create mode 100644 graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Album.java
create mode 100644 graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/AlbumsDataFetcher.java
create mode 100644 graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Application.java
create mode 100644 graphql/graphql-dgs/src/main/resources/application.properties
create mode 100644 graphql/graphql-dgs/src/main/resources/schema/schema.graphqls
diff --git a/graphql/graphql-dgs/pom.xml b/graphql/graphql-dgs/pom.xml
new file mode 100644
index 0000000000..1dc3630276
--- /dev/null
+++ b/graphql/graphql-dgs/pom.xml
@@ -0,0 +1,91 @@
+
+
+ 4.0.0
+ com.baeldung.graphql-dgs
+ graphql-dgs
+ 1.0
+ graphql-dgs
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ../..
+
+
+
+
+
+ com.netflix.graphql.dgs
+ graphql-dgs-platform-dependencies
+ 4.1.0
+ pom
+ import
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter
+ 2.6.2
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ 2.6.2
+ test
+
+
+
+ com.netflix.graphql.dgs.codegen
+ graphql-dgs-codegen-client-core
+ 5.1.14
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+ 2.6.2
+
+
+
+ com.netflix.graphql.dgs
+ graphql-dgs-spring-boot-starter
+ 4.9.15
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ 2.6.2
+
+
+ io.github.deweyjose
+ graphqlcodegen-maven-plugin
+ 1.14
+
+
+
+ generate
+
+
+
+
+
+ src/main/resources/schema/schema.graphqls
+
+ com.bealdung.graphqldgs.generated
+
+
+
+
+
+
diff --git a/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Album.java b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Album.java
new file mode 100644
index 0000000000..7e53eb08fe
--- /dev/null
+++ b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Album.java
@@ -0,0 +1,25 @@
+package com.bealdung.graphqlDGS;
+
+public class Album {
+ private final String title;
+ private final String artist;
+ private final Integer recordNo;
+
+ public Album(String title, String artist, Integer recordNo) {
+ this.title = title;
+ this.recordNo = recordNo;
+ this.artist = artist;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getArtist() {
+ return artist;
+ }
+
+ public Integer getRecordNo() {
+ return recordNo;
+ }
+}
diff --git a/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/AlbumsDataFetcher.java b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/AlbumsDataFetcher.java
new file mode 100644
index 0000000000..8fda98b941
--- /dev/null
+++ b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/AlbumsDataFetcher.java
@@ -0,0 +1,28 @@
+package com.bealdung.graphqlDGS;
+
+import com.netflix.graphql.dgs.DgsComponent;
+import com.netflix.graphql.dgs.DgsQuery;
+import com.netflix.graphql.dgs.InputArgument;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@DgsComponent
+public class AlbumsDataFetcher {
+
+ private final List albums = Arrays.asList(
+ new Album("Rumours", "Fleetwood Mac", 20),
+ new Album("What's Going On", "Marvin Gaye", 10),
+ new Album("Pet Sounds", "The Beach Boys", 12)
+ );
+
+ @DgsQuery
+ public List albums(@InputArgument String titleFilter) {
+ if(titleFilter == null) {
+ return albums;
+ }
+ return albums.stream()
+ .filter(s -> s.getTitle().contains(titleFilter))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Application.java b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Application.java
new file mode 100644
index 0000000000..ffe8cb2a4e
--- /dev/null
+++ b/graphql/graphql-dgs/src/main/java/com/bealdung/graphqlDGS/Application.java
@@ -0,0 +1,13 @@
+package com.bealdung.graphqlDGS;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+}
diff --git a/graphql/graphql-dgs/src/main/resources/application.properties b/graphql/graphql-dgs/src/main/resources/application.properties
new file mode 100644
index 0000000000..8693adcbd6
--- /dev/null
+++ b/graphql/graphql-dgs/src/main/resources/application.properties
@@ -0,0 +1 @@
+server.servlet.context-path=
diff --git a/graphql/graphql-dgs/src/main/resources/schema/schema.graphqls b/graphql/graphql-dgs/src/main/resources/schema/schema.graphqls
new file mode 100644
index 0000000000..90691a7204
--- /dev/null
+++ b/graphql/graphql-dgs/src/main/resources/schema/schema.graphqls
@@ -0,0 +1,9 @@
+type Query {
+ albums(titleFilter: String): [Album]
+}
+
+type Album {
+ title: String
+ artist: String
+ recordNo: Int
+}
diff --git a/pom.xml b/pom.xml
index 6219bbc692..a5b6b31022 100644
--- a/pom.xml
+++ b/pom.xml
@@ -422,6 +422,7 @@
graphql/graphql-java
+ graphql/graphql-dgs
grpc
gson
guava-modules
From 69e04d5ac0ebe9cff0d102fe74305100975aaedc Mon Sep 17 00:00:00 2001
From: ashleyfrieze
Date: Mon, 31 Jan 2022 03:49:04 +0000
Subject: [PATCH 043/235] BAEL-5354 Add improvement to cover JDK11 solution to
the repeated string problem (#11756)
---
.../core-java-string-algorithms-3/pom.xml | 3 ++-
.../RepeatedCharacterStringUnitTest.java | 12 ++++++++++++
core-java-modules/pom.xml | 1 -
pom.xml | 1 +
4 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml
index c140fce584..dc8ad3851d 100644
--- a/core-java-modules/core-java-string-algorithms-3/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-3/pom.xml
@@ -49,8 +49,9 @@
+ 11
+ 11
1.7
3.12.0
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/repeatedcharstring/RepeatedCharacterStringUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/repeatedcharstring/RepeatedCharacterStringUnitTest.java
index 42697c781e..81e78e8fd0 100644
--- a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/repeatedcharstring/RepeatedCharacterStringUnitTest.java
+++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/repeatedcharstring/RepeatedCharacterStringUnitTest.java
@@ -19,6 +19,18 @@ class RepeatedCharacterStringUnitTest {
private static final String EXPECTED_STRING = "aaaaaaa";
private static final int N = 7;
+ @Test
+ void givenSingleCharacterString_whenRepeat_thenStringCreated() {
+ String newString = "a".repeat(N);
+ assertEquals(EXPECTED_STRING, newString);
+ }
+
+ @Test
+ void givenMultiCharacterString_whenRepeat_thenStringCreated() {
+ String newString = "-->".repeat(5);
+ assertEquals("-->-->-->-->-->", newString);
+ }
+
@Test
void givenString_whenStringBuilderUsed_thenStringCreated() {
StringBuilder builder = new StringBuilder(N);
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index d9da5a845b..809aa72966 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -107,7 +107,6 @@
core-java-streams-4
core-java-string-algorithms
core-java-string-algorithms-2
- core-java-string-algorithms-3
core-java-string-apis
core-java-string-conversions
core-java-string-conversions-2
diff --git a/pom.xml b/pom.xml
index a5b6b31022..f2a230357c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1333,6 +1333,7 @@
core-java-modules/core-java-io-conversions-2
core-java-modules/core-java-jpms
core-java-modules/core-java-os
+ core-java-modules/core-java-string-algorithms-3
core-java-modules/core-java-string-operations-3
core-java-modules/core-java-string-operations-4
core-java-modules/core-java-time-measurements
From 295bf661f31b0f6450a183472c9cda812e6c47c6 Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:48:53 +0330
Subject: [PATCH 044/235] BAEL-5300: add required dependency
---
spring-cloud/spring-cloud-openfeign/pom.xml | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml
index 3e59f512db..480663eb1c 100644
--- a/spring-cloud/spring-cloud-openfeign/pom.xml
+++ b/spring-cloud/spring-cloud-openfeign/pom.xml
@@ -48,7 +48,15 @@
io.github.openfeign.form
feign-form-spring
-
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.security
+ spring-security-oauth2-client
+
org.springframework.boot
spring-boot-starter-test
From d1ef70e63dde6b85494d455d5d40c520361a336b Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:49:16 +0330
Subject: [PATCH 045/235] BAEL-5300: add oauth2 client info
---
.../src/main/resources/application.properties | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties
index 41bbbde2c3..7188b74c9b 100644
--- a/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties
+++ b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties
@@ -1,3 +1,10 @@
+server.port=8085
+spring.main.allow-bean-definition-overriding=true
spring.application.name= openfeign
logging.level.com.baeldung.cloud.openfeign.client: DEBUG
feign.hystrix.enabled=true
+
+spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials
+spring.security.oauth2.client.registration.keycloak.client-id=payment-app
+spring.security.oauth2.client.registration.keycloak.client-secret=863e9de4-33d4-4471-b35e-f8d2434385bb
+spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8083/auth/realms/master/protocol/openid-connect/token
From e459737a66622ae0242e7d4b8f356ad46acefe18 Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:49:51 +0330
Subject: [PATCH 046/235] BAEL-5300: add payment resources code
---
.../cloud/openfeign/client/PaymentClient.java | 16 +++++++++++++
.../controller/PaymentController.java | 24 +++++++++++++++++++
.../cloud/openfeign/model/Payment.java | 23 ++++++++++++++++++
3 files changed, 63 insertions(+)
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java
new file mode 100644
index 0000000000..91932fb7d8
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java
@@ -0,0 +1,16 @@
+package com.baeldung.cloud.openfeign.client;
+
+import com.baeldung.cloud.openfeign.model.Payment;
+import com.baeldung.cloud.openfeign.oauthfeign.OAuthFeignConfig;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import java.util.List;
+
+@FeignClient(name = "payment-client", url = "http://localhost:8081/resource-server-jwt", configuration = OAuthFeignConfig.class)
+public interface PaymentClient {
+
+ @RequestMapping(value = "/payments", method = RequestMethod.GET)
+ List getPayments();
+}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java
new file mode 100644
index 0000000000..97c9437ce1
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java
@@ -0,0 +1,24 @@
+package com.baeldung.cloud.openfeign.controller;
+
+import com.baeldung.cloud.openfeign.client.PaymentClient;
+import com.baeldung.cloud.openfeign.model.Payment;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+
+@RestController
+public class PaymentController {
+
+ private final PaymentClient paymentClient;
+
+ public PaymentController(PaymentClient paymentClient) {
+ this.paymentClient = paymentClient;
+ }
+
+ @GetMapping("/payments")
+ public List getPayments() {
+ List payments = paymentClient.getPayments();
+ return payments;
+ }
+}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java
new file mode 100644
index 0000000000..c6d45bedbd
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java
@@ -0,0 +1,23 @@
+package com.baeldung.cloud.openfeign.model;
+
+public class Payment {
+
+ private String id;
+ private double amount;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public double getAmount() {
+ return amount;
+ }
+
+ public void setAmount(double amount) {
+ this.amount = amount;
+ }
+}
From 10dd6acd33f6bd2db32ef22387f18e0f21fa9f39 Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:50:19 +0330
Subject: [PATCH 047/235] BAEL-5300: add openfeign config
---
.../OAuthClientCredentialsFeignManager.java | 85 +++++++++++++++++++
.../oauthfeign/OAuthFeignConfig.java | 46 ++++++++++
2 files changed, 131 insertions(+)
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java
new file mode 100644
index 0000000000..5e958a93de
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java
@@ -0,0 +1,85 @@
+package com.baeldung.cloud.openfeign.oauthfeign;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
+import org.springframework.security.oauth2.client.registration.ClientRegistration;
+
+import java.util.Collection;
+import java.util.Collections;
+
+import static java.util.Objects.isNull;
+
+public class OAuthClientCredentialsFeignManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(OAuthClientCredentialsFeignManager.class);
+
+ private final OAuth2AuthorizedClientManager manager;
+ private final Authentication principal;
+ private final ClientRegistration clientRegistration;
+
+ public OAuthClientCredentialsFeignManager(OAuth2AuthorizedClientManager manager, ClientRegistration clientRegistration) {
+ this.manager = manager;
+ this.clientRegistration = clientRegistration;
+ this.principal = createPrincipal();
+ }
+
+ private Authentication createPrincipal() {
+ return new Authentication() {
+ @Override
+ public Collection extends GrantedAuthority> getAuthorities() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Object getCredentials() {
+ return null;
+ }
+
+ @Override
+ public Object getDetails() {
+ return null;
+ }
+
+ @Override
+ public Object getPrincipal() {
+ return this;
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return false;
+ }
+
+ @Override
+ public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
+ }
+
+ @Override
+ public String getName() {
+ return clientRegistration.getClientId();
+ }
+ };
+ }
+
+ public String getAccessToken() {
+ try {
+ OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest
+ .withClientRegistrationId(clientRegistration.getRegistrationId())
+ .principal(principal)
+ .build();
+ OAuth2AuthorizedClient client = manager.authorize(oAuth2AuthorizeRequest);
+ if (isNull(client)) {
+ throw new IllegalStateException("client credentials flow on " + clientRegistration.getRegistrationId() + " failed, client is null");
+ }
+ return client.getAccessToken().getTokenValue();
+ } catch (Exception exp) {
+ logger.error("client credentials error " + exp.getMessage());
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java
new file mode 100644
index 0000000000..70ca45d86e
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java
@@ -0,0 +1,46 @@
+package com.baeldung.cloud.openfeign.oauthfeign;
+
+import feign.RequestInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.oauth2.client.*;
+import org.springframework.security.oauth2.client.registration.ClientRegistration;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+
+@Configuration
+public class OAuthFeignConfig {
+
+ public static final String CLIENT_REGISTRATION_ID = "keycloak";
+
+ private final OAuth2AuthorizedClientService oAuth2AuthorizedClientService;
+ private final ClientRegistrationRepository clientRegistrationRepository;
+
+ public OAuthFeignConfig(OAuth2AuthorizedClientService oAuth2AuthorizedClientService,
+ ClientRegistrationRepository clientRegistrationRepository) {
+ this.oAuth2AuthorizedClientService = oAuth2AuthorizedClientService;
+ this.clientRegistrationRepository = clientRegistrationRepository;
+ }
+
+ @Bean
+ public RequestInterceptor requestInterceptor() {
+ ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
+ OAuthClientCredentialsFeignManager clientCredentialsFeignManager =
+ new OAuthClientCredentialsFeignManager(authorizedClientManager(), clientRegistration);
+ return requestTemplate -> {
+ requestTemplate.header("Authorization", "Bearer " + clientCredentialsFeignManager.getAccessToken());
+ };
+ }
+
+ @Bean
+ OAuth2AuthorizedClientManager authorizedClientManager() {
+ OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
+ .clientCredentials()
+ .build();
+
+ AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
+ new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, oAuth2AuthorizedClientService);
+ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
+ return authorizedClientManager;
+ }
+
+}
\ No newline at end of file
From 1a70e89e1edb6244aae122148cedba9d132bcbca Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:50:37 +0330
Subject: [PATCH 048/235] BAEL-5300: add security config
---
.../OAuth2WebSecurityConfigurerAdapter.java | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java
new file mode 100644
index 0000000000..af60c3849b
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java
@@ -0,0 +1,19 @@
+package com.baeldung.cloud.openfeign.oauthfeign;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+public class OAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .csrf()
+ .disable()
+ .oauth2Client();
+ http
+ .authorizeRequests().anyRequest().permitAll();
+ }
+}
From 6c2d5a66d92e5ed2c5d36310dad3ce2d72f9d0d8 Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:50:50 +0330
Subject: [PATCH 049/235] BAEL-5300: add test class
---
.../openfeign/PaymentClientUnitTest.java | 32 +++++++++++++++++++
1 file changed, 32 insertions(+)
create mode 100644 spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
new file mode 100644
index 0000000000..3e53ba0d97
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
@@ -0,0 +1,32 @@
+package com.baeldung.cloud.openfeign;
+
+import com.baeldung.cloud.openfeign.client.PaymentClient;
+import com.baeldung.cloud.openfeign.model.Payment;
+import com.baeldung.cloud.openfeign.model.Post;
+import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class PaymentClientUnitTest {
+
+ @Autowired
+ private PaymentClient paymentClient;
+
+ @Test
+ public void whenGetPayment_thenListPayments() {
+
+ List payments = paymentClient.getPayments();
+
+ assertFalse(payments.isEmpty());
+ }
+
+}
From ff2fe54750cd024c36cd5fe8282378ff2edef830 Mon Sep 17 00:00:00 2001
From: sharifi
Date: Mon, 31 Jan 2022 10:53:06 +0330
Subject: [PATCH 050/235] BAEL-5300: improve test class
---
.../com/baeldung/cloud/openfeign/PaymentClientUnitTest.java | 2 --
1 file changed, 2 deletions(-)
diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
index 3e53ba0d97..0372728515 100644
--- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
+++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java
@@ -2,8 +2,6 @@ package com.baeldung.cloud.openfeign;
import com.baeldung.cloud.openfeign.client.PaymentClient;
import com.baeldung.cloud.openfeign.model.Payment;
-import com.baeldung.cloud.openfeign.model.Post;
-import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
From 01ca4575ba28529baaad915528f45d014d534a96 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Mon, 31 Jan 2022 12:45:28 +0000
Subject: [PATCH 051/235] [JAVA-9604] Refactor and code clean-up for Metrics
article
---
.../spring-boot-actuator/README.md | 1 +
.../spring-boot-actuator/pom.xml | 18 +++
.../baeldung/metrics/MetricsApplication.java | 42 ++++++
.../java/com/baeldung/metrics}/WebConfig.java | 13 +-
.../metrics/controller/MetricsController.java | 41 ++++++
.../metrics/filter}/MetricFilter.java | 30 +++--
.../service}/ActuatorMetricService.java | 67 +++++-----
.../service}/CustomActuatorMetricService.java | 54 ++++----
.../service/InMemoryMetricService.java | 112 ++++++++++++++++
.../metrics/service/MetricService.java | 7 +
.../resources/application-metrics.properties | 9 ++
.../src/main/webapp/WEB-INF/api-servlet.xml | 0
.../webapp/WEB-INF/view/metrics}/graph.jsp | 2 +-
.../webapp/WEB-INF/view/metrics}/homepage.jsp | 0
.../src/main/webapp/WEB-INF/web.xml | 4 +-
.../MetricsApplicationIntegrationTest.java | 64 +++++++++
.../spring-rest-testing/README.md | 1 -
.../spring-rest-testing/pom.xml | 28 ----
.../java/com/baeldung/spring/Application.java | 21 +--
.../web/controller/RootController.java | 52 --------
.../web/metric/IActuatorMetricService.java | 5 -
.../metric/ICustomActuatorMetricService.java | 8 --
.../baeldung/web/metric/IMetricService.java | 14 --
.../baeldung/web/metric/MetricService.java | 122 ------------------
.../src/main/resources/application.properties | 1 -
25 files changed, 373 insertions(+), 343 deletions(-)
create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/MetricsApplication.java
rename {spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring => spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics}/WebConfig.java (81%)
create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/controller/MetricsController.java
rename {spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric => spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/filter}/MetricFilter.java (64%)
rename {spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric => spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service}/ActuatorMetricService.java (61%)
rename {spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric => spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service}/CustomActuatorMetricService.java (68%)
create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/InMemoryMetricService.java
create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/MetricService.java
create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/resources/application-metrics.properties
rename {spring-web-modules/spring-rest-testing => spring-boot-modules/spring-boot-actuator}/src/main/webapp/WEB-INF/api-servlet.xml (100%)
rename {spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view => spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics}/graph.jsp (94%)
rename {spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view => spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics}/homepage.jsp (100%)
rename {spring-web-modules/spring-rest-testing => spring-boot-modules/spring-boot-actuator}/src/main/webapp/WEB-INF/web.xml (92%)
create mode 100644 spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/metrics/MetricsApplicationIntegrationTest.java
delete mode 100644 spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java
delete mode 100644 spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java
delete mode 100644 spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java
delete mode 100644 spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java
delete mode 100644 spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java
diff --git a/spring-boot-modules/spring-boot-actuator/README.md b/spring-boot-modules/spring-boot-actuator/README.md
index 59f7e929da..ea43377ed2 100644
--- a/spring-boot-modules/spring-boot-actuator/README.md
+++ b/spring-boot-modules/spring-boot-actuator/README.md
@@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Health Indicators in Spring Boot](https://www.baeldung.com/spring-boot-health-indicators)
- [How to Enable All Endpoints in Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuator-enable-endpoints)
- [Spring Boot Startup Actuator Endpoint](https://www.baeldung.com/spring-boot-actuator-startup)
+- [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics)
diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml
index b2c7a4d28e..1ccf436bbf 100644
--- a/spring-boot-modules/spring-boot-actuator/pom.xml
+++ b/spring-boot-modules/spring-boot-actuator/pom.xml
@@ -23,6 +23,10 @@
org.springframework.boot
spring-boot-starter-web
+
+ org.apache.tomcat.embed
+ tomcat-embed-jasper
+
org.springframework.boot
spring-boot-starter-data-jpa
@@ -35,6 +39,16 @@
com.h2database
h2
+
+ javax.servlet
+ javax.servlet-api
+ provided
+
+
+ javax.servlet
+ jstl
+ runtime
+
org.springframework.boot
spring-boot-starter-test
@@ -51,6 +65,10 @@
spring-security-test
test
+
+ org.awaitility
+ awaitility
+
diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/MetricsApplication.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/MetricsApplication.java
new file mode 100644
index 0000000000..729b3c0b96
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/MetricsApplication.java
@@ -0,0 +1,42 @@
+package com.baeldung.metrics;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
+import org.springframework.boot.actuate.autoconfigure.security.servlet.SecurityRequestMatchersManagementContextConfiguration;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
+import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
+import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
+import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.web.context.request.RequestContextListener;
+
+import javax.servlet.ServletContext;
+
+@EnableScheduling
+@ComponentScan("com.baeldung.metrics")
+@SpringBootApplication
+public class MetricsApplication extends SpringBootServletInitializer {
+
+ @Override
+ protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
+ return application.sources(MetricsApplication.class);
+ }
+
+ @Override
+ public void onStartup(ServletContext sc) {
+ // Manages the lifecycle of the root application context
+ sc.addListener(new RequestContextListener());
+ }
+
+ public static void main(final String[] args) {
+ // only load properties for this application
+ System.setProperty("spring.config.location", "classpath:application-metrics.properties");
+ SpringApplication.run(MetricsApplication.class, args);
+ }
+
+}
\ No newline at end of file
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/WebConfig.java
similarity index 81%
rename from spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java
rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/WebConfig.java
index e35acb0bf0..4c38e4dbad 100644
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/WebConfig.java
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/WebConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.spring;
+package com.baeldung.metrics;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -10,14 +10,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
-@ComponentScan("com.baeldung.web")
+@ComponentScan("com.baeldung.metrics")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
- public WebConfig() {
- super();
- }
-
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
@@ -26,11 +22,10 @@ public class WebConfig implements WebMvcConfigurer {
return viewResolver;
}
- // API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
- registry.addViewController("/graph.html");
- registry.addViewController("/homepage.html");
+ registry.addViewController("/metrics/graph.html");
+ registry.addViewController("/metrics/homepage.html");
}
}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/controller/MetricsController.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/controller/MetricsController.java
new file mode 100644
index 0000000000..e52ddd70f1
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/controller/MetricsController.java
@@ -0,0 +1,41 @@
+package com.baeldung.metrics.controller;
+
+import com.baeldung.metrics.service.InMemoryMetricService;
+import com.baeldung.metrics.service.MetricService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import java.util.Map;
+
+@Controller
+@RequestMapping(value = "/metrics")
+@ResponseBody
+public class MetricsController {
+
+ @Autowired
+ private InMemoryMetricService metricService;
+
+ // change the qualifier to use the in-memory implementation
+ @Autowired
+ @Qualifier("customActuatorMetricService")
+ private MetricService graphMetricService;
+
+ @GetMapping(value = "/metric")
+ public Map> getMetric() {
+ return metricService.getFullMetric();
+ }
+
+ @GetMapping(value = "/status-metric")
+ public Map getStatusMetric() {
+ return metricService.getStatusMetric();
+ }
+
+ @GetMapping(value = "/metric-graph-data")
+ public Object[][] getMetricData() {
+ return graphMetricService.getGraphData();
+ }
+}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/filter/MetricFilter.java
similarity index 64%
rename from spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java
rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/filter/MetricFilter.java
index dee63b226f..0f7579f060 100644
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricFilter.java
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/filter/MetricFilter.java
@@ -1,4 +1,11 @@
-package com.baeldung.web.metric;
+package com.baeldung.metrics.filter;
+
+import com.baeldung.metrics.service.CustomActuatorMetricService;
+import com.baeldung.metrics.service.InMemoryMetricService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@@ -9,24 +16,23 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.web.context.support.WebApplicationContextUtils;
-
@Component
public class MetricFilter implements Filter {
@Autowired
- private IMetricService metricService;
+ private InMemoryMetricService metricService;
@Autowired
- private ICustomActuatorMetricService actMetricService;
+ private CustomActuatorMetricService actMetricService;
@Override
- public void init(final FilterConfig config) throws ServletException {
+ public void init(final FilterConfig config) {
if (metricService == null || actMetricService == null) {
- metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService");
- actMetricService = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(CustomActuatorMetricService.class);
+ WebApplicationContext appContext = WebApplicationContextUtils
+ .getRequiredWebApplicationContext(config.getServletContext());
+
+ metricService = appContext.getBean(InMemoryMetricService.class);
+ actMetricService = appContext.getBean(CustomActuatorMetricService.class);
}
}
@@ -42,8 +48,4 @@ public class MetricFilter implements Filter {
actMetricService.increaseCount(status);
}
- @Override
- public void destroy() {
-
- }
}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/ActuatorMetricService.java
similarity index 61%
rename from spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java
rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/ActuatorMetricService.java
index 8c26fa04a0..3eef265c02 100644
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ActuatorMetricService.java
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/ActuatorMetricService.java
@@ -1,32 +1,31 @@
-package com.baeldung.web.metric;
+package com.baeldung.metrics.service;
+
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.Meter;
+import io.micrometer.core.instrument.MeterRegistry;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-
-import io.micrometer.core.instrument.Counter;
-import io.micrometer.core.instrument.Meter;
-import io.micrometer.core.instrument.MeterRegistry;
-
@Service
-public class ActuatorMetricService implements IActuatorMetricService {
+public class ActuatorMetricService implements MetricService {
+
+ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Autowired
private MeterRegistry publicMetrics;
- private final List> statusMetricsByMinute;
+ private final List> statusMetricsByMinute;
private final List statusList;
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public ActuatorMetricService() {
- super();
- statusMetricsByMinute = new ArrayList>();
- statusList = new ArrayList();
+ statusMetricsByMinute = new ArrayList<>();
+ statusList = new ArrayList<>();
}
@Override
@@ -36,19 +35,19 @@ public class ActuatorMetricService implements IActuatorMetricService {
final int rowCount = statusMetricsByMinute.size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
- int j = 1;
+ int j = 1;
for (final String status : statusList) {
result[0][j] = status;
j++;
}
for (int i = 1; i < rowCount; i++) {
- result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i))));
+ result[i][0] = DATE_FORMAT.format(new Date(current.getTime() - (60000L * (rowCount - i))));
}
List minuteOfStatuses;
- List last = new ArrayList();
+ List last = new ArrayList<>();
for (int i = 1; i < rowCount; i++) {
minuteOfStatuses = statusMetricsByMinute.get(i - 1);
@@ -64,11 +63,9 @@ public class ActuatorMetricService implements IActuatorMetricService {
return result;
}
- // Non - API
-
- @Scheduled(fixedDelay = 60000)
+ @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:60000}")
private void exportMetrics() {
- final ArrayList lastMinuteStatuses = initializeStatuses(statusList.size());
+ final List lastMinuteStatuses = initializeStatuses(statusList.size());
for (final Meter counterMetric : publicMetrics.getMeters()) {
updateMetrics(counterMetric, lastMinuteStatuses);
@@ -77,34 +74,32 @@ public class ActuatorMetricService implements IActuatorMetricService {
statusMetricsByMinute.add(lastMinuteStatuses);
}
- private ArrayList initializeStatuses(final int size) {
- final ArrayList counterList = new ArrayList();
+ private List initializeStatuses(int size) {
+ List counterList = new ArrayList<>();
for (int i = 0; i < size; i++) {
counterList.add(0);
}
return counterList;
}
- private void updateMetrics(final Meter counterMetric, final ArrayList statusCount) {
- String status = "";
- int index = -1;
- int oldCount = 0;
+ private void updateMetrics(Meter counterMetric, List statusCount) {
- if (counterMetric.getId().getName().contains("counter.status.")) {
- status = counterMetric.getId().getName().substring(15, 18); // example 404, 200
+ String metricName = counterMetric.getId().getName();
+
+ if (metricName.contains("counter.status.")) {
+ // example 404, 200
+ String status = metricName.substring(15, 18);
appendStatusIfNotExist(status, statusCount);
- index = statusList.indexOf(status);
- oldCount = statusCount.get(index) == null ? 0 : statusCount.get(index);
+ int index = statusList.indexOf(status);
+ int oldCount = statusCount.get(index) == null ? 0 : statusCount.get(index);
statusCount.set(index, (int)((Counter) counterMetric).count() + oldCount);
}
}
- private void appendStatusIfNotExist(final String status, final ArrayList statusCount) {
+ private void appendStatusIfNotExist(String status, List statusCount) {
if (!statusList.contains(status)) {
statusList.add(status);
statusCount.add(0);
}
}
-
- //
-}
\ No newline at end of file
+}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/CustomActuatorMetricService.java
similarity index 68%
rename from spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java
rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/CustomActuatorMetricService.java
index ee17825b7c..9b4ccaa875 100644
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/CustomActuatorMetricService.java
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/CustomActuatorMetricService.java
@@ -1,40 +1,36 @@
-package com.baeldung.web.metric;
+package com.baeldung.metrics.service;
+
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.MeterRegistry;
+import io.micrometer.core.instrument.search.Search;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-
-import io.micrometer.core.instrument.Counter;
-import io.micrometer.core.instrument.MeterRegistry;
-import io.micrometer.core.instrument.search.Search;
-
@Service
-public class CustomActuatorMetricService implements ICustomActuatorMetricService {
+public class CustomActuatorMetricService implements MetricService {
+
+ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Autowired
private MeterRegistry registry;
- private final List> statusMetricsByMinute;
+ private final List> statusMetricsByMinute;
private final List statusList;
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public CustomActuatorMetricService() {
- super();
- statusMetricsByMinute = new ArrayList>();
- statusList = new ArrayList();
+ statusMetricsByMinute = new ArrayList<>();
+ statusList = new ArrayList<>();
}
- // API
-
- @Override
- public void increaseCount(final int status) {
+ public void increaseCount(int status) {
String counterName = "counter.status." + status;
- registry.counter(counterName).increment(1);
+ registry.counter(counterName).increment();
if (!statusList.contains(counterName)) {
statusList.add(counterName);
}
@@ -55,7 +51,7 @@ public class CustomActuatorMetricService implements ICustomActuatorMetricService
}
for (int i = 1; i < rowCount; i++) {
- result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i))));
+ result[i][0] = DATE_FORMAT.format(new Date(current.getTime() - (60000L * (rowCount - i))));
}
List minuteOfStatuses;
@@ -72,19 +68,17 @@ public class CustomActuatorMetricService implements ICustomActuatorMetricService
return result;
}
- // Non - API
-
- @Scheduled(fixedDelay = 60000)
+ @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:60000}")
private void exportMetrics() {
- final ArrayList statusCount = new ArrayList();
+ List statusCount = new ArrayList<>();
for (final String status : statusList) {
Search search = registry.find(status);
- if (search != null) {
- Counter counter = search.counter();
- statusCount.add(counter != null ? ((int) counter.count()) : 0);
- registry.remove(counter);
- } else {
+ Counter counter = search.counter();
+ if (counter == null) {
statusCount.add(0);
+ } else {
+ statusCount.add((int) counter.count());
+ registry.remove(counter);
}
}
statusMetricsByMinute.add(statusCount);
diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/InMemoryMetricService.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/InMemoryMetricService.java
new file mode 100644
index 0000000000..0be5c21727
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/InMemoryMetricService.java
@@ -0,0 +1,112 @@
+package com.baeldung.metrics.service;
+
+import org.springframework.stereotype.Service;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Service
+public class InMemoryMetricService implements MetricService {
+
+ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+
+ private final Map> metricMap;
+ private final Map statusMetric;
+ private final Map> timeMap;
+
+ public InMemoryMetricService() {
+ metricMap = new ConcurrentHashMap<>();
+ statusMetric = new ConcurrentHashMap<>();
+ timeMap = new ConcurrentHashMap<>();
+ }
+
+ public void increaseCount(String request, int status) {
+ increaseMainMetric(request, status);
+ increaseStatusMetric(status);
+ updateTimeMap(status);
+ }
+
+ public Map> getFullMetric() {
+ return metricMap;
+ }
+
+ public Map getStatusMetric() {
+ return statusMetric;
+ }
+
+ public Object[][] getGraphData() {
+ final int colCount = statusMetric.keySet().size() + 1;
+ final Set allStatus = statusMetric.keySet();
+ final int rowCount = timeMap.keySet().size() + 1;
+
+ final Object[][] result = new Object[rowCount][colCount];
+ result[0][0] = "Time";
+
+ int j = 1;
+ for (final int status : allStatus) {
+ result[0][j] = status;
+ j++;
+ }
+ int i = 1;
+ Map tempMap;
+ for (final Entry> entry : timeMap.entrySet()) {
+ result[i][0] = entry.getKey();
+ tempMap = entry.getValue();
+ for (j = 1; j < colCount; j++) {
+ result[i][j] = tempMap.get((Integer) result[0][j]);
+ if (result[i][j] == null) {
+ result[i][j] = 0;
+ }
+ }
+ i++;
+ }
+
+ for (int k = 1; k < result[0].length; k++) {
+ result[0][k] = result[0][k].toString();
+ }
+
+ return result;
+ }
+
+ private void increaseMainMetric(String request, int status) {
+ Map statusMap = metricMap.get(request);
+ if (statusMap == null) {
+ statusMap = new ConcurrentHashMap<>();
+ }
+
+ Integer count = statusMap.get(status);
+ if (count == null) {
+ count = 1;
+ } else {
+ count++;
+ }
+ statusMap.put(status, count);
+ metricMap.put(request, statusMap);
+ }
+
+ private void increaseStatusMetric(int status) {
+ statusMetric.merge(status, 1, Integer::sum);
+ }
+
+ private void updateTimeMap(int status) {
+ final String time = DATE_FORMAT.format(new Date());
+ Map statusMap = timeMap.get(time);
+ if (statusMap == null) {
+ statusMap = new ConcurrentHashMap<>();
+ }
+
+ Integer count = statusMap.get(status);
+ if (count == null) {
+ count = 1;
+ } else {
+ count++;
+ }
+ statusMap.put(status, count);
+ timeMap.put(time, statusMap);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/MetricService.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/MetricService.java
new file mode 100644
index 0000000000..3642102b67
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/metrics/service/MetricService.java
@@ -0,0 +1,7 @@
+package com.baeldung.metrics.service;
+
+public interface MetricService {
+
+ Object[][] getGraphData();
+
+}
diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application-metrics.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application-metrics.properties
new file mode 100644
index 0000000000..5f753a0c62
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application-metrics.properties
@@ -0,0 +1,9 @@
+management.endpoints.web.exposure.include=info,health,metrics
+
+# JPA and Security is not required for Metrics application
+spring.autoconfigure.exclude= org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \
+ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \
+ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, \
+ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, \
+ org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration, \
+ org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration
diff --git a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/api-servlet.xml b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/api-servlet.xml
similarity index 100%
rename from spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/api-servlet.xml
rename to spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/api-servlet.xml
diff --git a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view/graph.jsp b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics/graph.jsp
similarity index 94%
rename from spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view/graph.jsp
rename to spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics/graph.jsp
index e1d5fdc987..75976557a0 100644
--- a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view/graph.jsp
+++ b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics/graph.jsp
@@ -11,7 +11,7 @@
});
function drawChart() {
- $.get(" ",
+ $.get(" ",
function(mydata) {
var data = google.visualization.arrayToDataTable(mydata);
diff --git a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics/homepage.jsp
similarity index 100%
rename from spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/view/homepage.jsp
rename to spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/view/metrics/homepage.jsp
diff --git a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/web.xml b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/web.xml
similarity index 92%
rename from spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/web.xml
rename to spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/web.xml
index 7129b6b4af..84566ba93d 100644
--- a/spring-web-modules/spring-rest-testing/src/main/webapp/WEB-INF/web.xml
+++ b/spring-boot-modules/spring-boot-actuator/src/main/webapp/WEB-INF/web.xml
@@ -16,7 +16,7 @@
contextConfigLocation
- com.baeldung.spring
+ com.baeldung.metrics
@@ -37,7 +37,7 @@
metricFilter
- com.baeldung.web.metric.MetricFilter
+ com.baeldung.metrics.filter.MetricFilter
diff --git a/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/metrics/MetricsApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/metrics/MetricsApplicationIntegrationTest.java
new file mode 100644
index 0000000000..c83d4625dc
--- /dev/null
+++ b/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/metrics/MetricsApplicationIntegrationTest.java
@@ -0,0 +1,64 @@
+package com.baeldung.metrics;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
+
+@SpringBootTest(
+ classes = MetricsApplication.class,
+ webEnvironment = RANDOM_PORT,
+ properties = {"fixedDelay.in.milliseconds=2000"}
+)
+@ActiveProfiles("metrics")
+class MetricsApplicationIntegrationTest {
+
+ @Autowired
+ private TestRestTemplate restTemplate;
+
+ @Test
+ void givenStatuses_WhenScheduledMethodExecuted_ExpectCountsAreAggregated() {
+ restTemplate.getForObject("/metrics/metric/notFound", String.class);
+ restTemplate.getForObject("/metrics/metric", String.class);
+
+ await().untilAsserted(() -> {
+ Object[][] statusCounts = restTemplate.getForObject("/metrics/metric-graph-data", Object[][].class);
+
+ assertThat(statusCounts[0]).contains("counter.status.200", "counter.status.404");
+
+ List requestCounts = getRequestCounts(statusCounts);
+ verify404RequestFrom(requestCounts);
+ verify200RequestsFrom(requestCounts);
+ });
+ }
+
+ private static void verify200RequestsFrom(List requestCounts) {
+ assertThat(requestCounts.size()).isGreaterThan(1);
+ }
+
+ private static void verify404RequestFrom(List requestCounts) {
+ assertThat(requestCounts).contains(1);
+ }
+
+ private static List getRequestCounts(Object[][] statusCounts) {
+ List requestCounts = new ArrayList<>();
+ for (int i = 1; i < statusCounts.length; i++) {
+ for (int j = 1; j < statusCounts[i].length; j++) {
+ Integer count = (Integer) statusCounts[i][j];
+ if (count >= 1) {
+ requestCounts.add(count);
+ }
+ }
+ }
+ return requestCounts;
+ }
+
+}
diff --git a/spring-web-modules/spring-rest-testing/README.md b/spring-web-modules/spring-rest-testing/README.md
index 2a77b5dded..806e67b7ec 100644
--- a/spring-web-modules/spring-rest-testing/README.md
+++ b/spring-web-modules/spring-rest-testing/README.md
@@ -11,7 +11,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles:
- [Integration Testing with the Maven Cargo plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin)
-- [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics)
- [Testing Exceptions with Spring MockMvc](https://www.baeldung.com/spring-mvc-test-exceptions)
### Build the Project
diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml
index 52c1f6418e..1390898bf9 100644
--- a/spring-web-modules/spring-rest-testing/pom.xml
+++ b/spring-web-modules/spring-rest-testing/pom.xml
@@ -21,19 +21,10 @@
org.springframework.boot
spring-boot-starter-web
-
- org.springframework.boot
- spring-boot-starter-actuator
-
org.aspectj
aspectjweaver
-
- org.apache.tomcat.embed
- tomcat-embed-jasper
- provided
-
org.springframework
@@ -69,14 +60,6 @@
org.springframework
spring-expression
-
- org.springframework
- spring-web
-
-
- org.springframework
- spring-webmvc
-
org.springframework.data
spring-data-commons
@@ -137,17 +120,6 @@
net.bytebuddy
byte-buddy
-
-
- javax.servlet
- javax.servlet-api
- provided
-
-
- javax.servlet
- jstl
- runtime
-
com.fasterxml.jackson.core
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java
index c35c4d7e5e..78c9b88ddb 100644
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java
+++ b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/spring/Application.java
@@ -1,38 +1,19 @@
package com.baeldung.spring;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.boot.builder.SpringApplicationBuilder;
-import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.web.context.request.RequestContextListener;
/**
* Main Application Class - uses Spring Boot. Just run this as a normal Java
* class to run up a Jetty Server (on http://localhost:8082/spring-rest-full)
*
*/
-@EnableScheduling
@EnableAutoConfiguration
@ComponentScan("com.baeldung")
@SpringBootApplication
-public class Application extends SpringBootServletInitializer {
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(Application.class);
- }
-
- @Override
- public void onStartup(ServletContext sc) throws ServletException {
- // Manages the lifecycle of the root application context
- sc.addListener(new RequestContextListener());
- }
+public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java
deleted file mode 100644
index 005f6f023b..0000000000
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/controller/RootController.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.baeldung.web.controller;
-
-import java.util.Map;
-
-import com.baeldung.web.metric.IActuatorMetricService;
-import com.baeldung.web.metric.IMetricService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-@Controller
-@RequestMapping(value = "/auth/")
-public class RootController {
-
- @Autowired
- private IMetricService metricService;
-
- @Autowired
- private IActuatorMetricService actMetricService;
-
- public RootController() {
- super();
- }
-
- // API
-
- @RequestMapping(value = "/metric", method = RequestMethod.GET)
- @ResponseBody
- public Map getMetric() {
- return metricService.getFullMetric();
- }
-
- @RequestMapping(value = "/status-metric", method = RequestMethod.GET)
- @ResponseBody
- public Map getStatusMetric() {
- return metricService.getStatusMetric();
- }
-
- @RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
- @ResponseBody
- public Object[][] drawMetric() {
- final Object[][] result = metricService.getGraphData();
- for (int i = 1; i < result[0].length; i++) {
- result[0][i] = result[0][i].toString();
- }
- return result;
- }
-
-
-}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java
deleted file mode 100644
index 60bb43ee00..0000000000
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IActuatorMetricService.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.baeldung.web.metric;
-
-public interface IActuatorMetricService {
- Object[][] getGraphData();
-}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java
deleted file mode 100644
index 5126252e27..0000000000
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/ICustomActuatorMetricService.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.web.metric;
-
-public interface ICustomActuatorMetricService {
-
- void increaseCount(final int status);
-
- Object[][] getGraphData();
-}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java
deleted file mode 100644
index b8dfa60215..0000000000
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/IMetricService.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.baeldung.web.metric;
-
-import java.util.Map;
-
-public interface IMetricService {
-
- void increaseCount(final String request, final int status);
-
- Map getFullMetric();
-
- Map getStatusMetric();
-
- Object[][] getGraphData();
-}
diff --git a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java b/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java
deleted file mode 100644
index fd3cccab3e..0000000000
--- a/spring-web-modules/spring-rest-testing/src/main/java/com/baeldung/web/metric/MetricService.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package com.baeldung.web.metric;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.springframework.stereotype.Service;
-
-@Service
-public class MetricService implements IMetricService {
-
- private ConcurrentMap> metricMap;
- private ConcurrentMap statusMetric;
- private ConcurrentMap> timeMap;
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
-
- public MetricService() {
- super();
- metricMap = new ConcurrentHashMap>();
- statusMetric = new ConcurrentHashMap();
- timeMap = new ConcurrentHashMap>();
- }
-
- // API
-
- @Override
- public void increaseCount(final String request, final int status) {
- increaseMainMetric(request, status);
- increaseStatusMetric(status);
- updateTimeMap(status);
- }
-
- @Override
- public Map getFullMetric() {
- return metricMap;
- }
-
- @Override
- public Map getStatusMetric() {
- return statusMetric;
- }
-
- @Override
- public Object[][] getGraphData() {
- final int colCount = statusMetric.keySet().size() + 1;
- final Set allStatus = statusMetric.keySet();
- final int rowCount = timeMap.keySet().size() + 1;
-
- final Object[][] result = new Object[rowCount][colCount];
- result[0][0] = "Time";
-
- int j = 1;
- for (final int status : allStatus) {
- result[0][j] = status;
- j++;
- }
- int i = 1;
- ConcurrentMap tempMap;
- for (final Entry> entry : timeMap.entrySet()) {
- result[i][0] = entry.getKey();
- tempMap = entry.getValue();
- for (j = 1; j < colCount; j++) {
- result[i][j] = tempMap.get(result[0][j]);
- if (result[i][j] == null) {
- result[i][j] = 0;
- }
- }
- i++;
- }
-
- return result;
- }
-
- // NON-API
-
- private void increaseMainMetric(final String request, final int status) {
- ConcurrentHashMap statusMap = metricMap.get(request);
- if (statusMap == null) {
- statusMap = new ConcurrentHashMap();
- }
-
- Integer count = statusMap.get(status);
- if (count == null) {
- count = 1;
- } else {
- count++;
- }
- statusMap.put(status, count);
- metricMap.put(request, statusMap);
- }
-
- private void increaseStatusMetric(final int status) {
- final Integer statusCount = statusMetric.get(status);
- if (statusCount == null) {
- statusMetric.put(status, 1);
- } else {
- statusMetric.put(status, statusCount + 1);
- }
- }
-
- private void updateTimeMap(final int status) {
- final String time = dateFormat.format(new Date());
- ConcurrentHashMap statusMap = timeMap.get(time);
- if (statusMap == null) {
- statusMap = new ConcurrentHashMap();
- }
-
- Integer count = statusMap.get(status);
- if (count == null) {
- count = 1;
- } else {
- count++;
- }
- statusMap.put(status, count);
- timeMap.put(time, statusMap);
- }
-
-}
diff --git a/spring-web-modules/spring-rest-testing/src/main/resources/application.properties b/spring-web-modules/spring-rest-testing/src/main/resources/application.properties
index 52d93b4cff..cb9d72e41f 100644
--- a/spring-web-modules/spring-rest-testing/src/main/resources/application.properties
+++ b/spring-web-modules/spring-rest-testing/src/main/resources/application.properties
@@ -1,3 +1,2 @@
server.port=8082
server.servlet.context-path=/spring-rest-full
-endpoints.metrics.enabled=true
\ No newline at end of file
From ef127cbdfbf77969468df8a597df3a27f285fa79 Mon Sep 17 00:00:00 2001
From: freelansam <79205526+freelansam@users.noreply.github.com>
Date: Mon, 31 Jan 2022 21:48:39 +0530
Subject: [PATCH 052/235] JAVA-9566: Update apache-poi version and articles
(#11748)
* JAVA-9566: Update apache-poi version and articles
* JAVA-9566: Update apache-poi version and articles
---
apache-poi/pom.xml | 2 +-
.../baeldung/poi/excel/ExcelPOIHelper.java | 27 +++++++++----------
.../com/baeldung/poi/excel/ExcelUtility.java | 1 +
.../poi/excel/cellstyle/CellStyler.java | 1 -
.../jexcel/JExcelIntegrationTest.java | 27 +++++++------------
.../poi/excel/ExcelIntegrationTest.java | 21 +++++----------
.../cellstyle/CellStyleHandlerUnitTest.java | 16 ++++++-----
7 files changed, 41 insertions(+), 54 deletions(-)
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index 5471c77961..1a0f77b025 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -33,7 +33,7 @@
- 4.1.1
+ 5.2.0
1.0.6
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java
index b6b0cbef20..6c2a8c68f7 100644
--- a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java
+++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java
@@ -1,25 +1,24 @@
package com.baeldung.poi.excel;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.DateUtil;
+import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.ArrayList;
-import java.util.List;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPOIHelper {
@@ -33,7 +32,7 @@ public class ExcelPOIHelper {
for (Row row : sheet) {
data.put(i, new ArrayList());
for (Cell cell : row) {
- switch (cell.getCellTypeEnum()) {
+ switch (cell.getCellType()) {
case STRING:
data.get(i)
.add(cell.getRichStringCellValue()
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java
index 50bbfbbe3c..f22b0f094f 100644
--- a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java
+++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java
@@ -44,6 +44,7 @@ public class ExcelUtility {
}
}
inputStream.close();
+ baeuldungWorkBook.close();
} catch (IOException e) {
throw e;
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java b/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
index 6d8b303fd3..0f8f8b6cd9 100644
--- a/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
+++ b/apache-poi/src/main/java/com/baeldung/poi/excel/cellstyle/CellStyler.java
@@ -1,7 +1,6 @@
package com.baeldung.poi.excel.cellstyle;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
-import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
index 41efd9d9ba..abf3d3d50c 100644
--- a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
+++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
@@ -1,25 +1,18 @@
package com.baeldung.jexcel;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import jxl.read.biff.BiffException;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.jexcel.JExcelHelper;
-
-import jxl.write.WriteException;
-import jxl.read.biff.BiffException;
-
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-import org.junit.Before;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import jxl.read.biff.BiffException;
+import jxl.write.WriteException;
public class JExcelIntegrationTest {
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
index 5d7ccb9b94..d2fa08e9ea 100644
--- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
+++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
@@ -1,22 +1,15 @@
package com.baeldung.poi.excel;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import jxl.read.biff.BiffException;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.poi.excel.ExcelPOIHelper;
-
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-import org.junit.Before;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class ExcelIntegrationTest {
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStyleHandlerUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStyleHandlerUnitTest.java
index e131db8e56..1aa6445511 100644
--- a/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStyleHandlerUnitTest.java
+++ b/apache-poi/src/test/java/com/baeldung/poi/excel/cellstyle/CellStyleHandlerUnitTest.java
@@ -1,17 +1,19 @@
package com.baeldung.poi.excel.cellstyle;
-import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.file.Paths;
-import static org.junit.Assert.assertEquals;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.junit.Before;
+import org.junit.Test;
public class CellStyleHandlerUnitTest {
private static final String FILE_NAME = "cellstyle/CellStyleHandlerTest.xlsx";
From fc36443ae2742d2f4565c1ebdff609b2a4c44900 Mon Sep 17 00:00:00 2001
From: Attila Uhrin
Date: Sun, 30 Jan 2022 10:58:44 +0100
Subject: [PATCH 053/235] Add implementation for BAEL-5317.
---
spring-sleuth/pom.xml | 2 +-
.../traceid/SleuthCurrentTraceIdApp.java | 11 +++++++
.../traceid/SleuthTraceIdController.java | 32 +++++++++++++++++++
.../CurrentTraceIdAppSpringContextTest.java | 15 +++++++++
.../session}/SpringContextTest.java | 4 +--
5 files changed, 60 insertions(+), 4 deletions(-)
create mode 100644 spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthCurrentTraceIdApp.java
create mode 100644 spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
create mode 100644 spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
rename spring-sleuth/src/test/java/com/baeldung/{ => spring/session}/SpringContextTest.java (83%)
diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml
index 5fd109e968..a6fba5ea56 100644
--- a/spring-sleuth/pom.xml
+++ b/spring-sleuth/pom.xml
@@ -39,7 +39,7 @@
- 2.0.2.RELEASE
+ 3.1.0
\ No newline at end of file
diff --git a/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthCurrentTraceIdApp.java b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthCurrentTraceIdApp.java
new file mode 100644
index 0000000000..bae1d310a2
--- /dev/null
+++ b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthCurrentTraceIdApp.java
@@ -0,0 +1,11 @@
+package com.baeldung.sleuth.traceid;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SleuthCurrentTraceIdApp {
+ public static void main(String[] args) {
+ SpringApplication.run(SleuthCurrentTraceIdApp.class, args);
+ }
+}
diff --git a/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
new file mode 100644
index 0000000000..fb4bf2bb1a
--- /dev/null
+++ b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
@@ -0,0 +1,32 @@
+package com.baeldung.sleuth.traceid;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import brave.Span;
+import brave.Tracer;
+
+@RestController
+public class SleuthTraceIdController {
+
+ private static final Logger logger = LoggerFactory.getLogger(SleuthTraceIdController.class);
+
+ @Autowired
+ private Tracer tracer;
+
+ @GetMapping("/hello")
+ public String hello() {
+ logger.info("Hello with Sleuth");
+ Span span = tracer.currentSpan();
+ if (span != null) {
+ logger.info("Span ID hex {}", span.context().spanIdString());
+ logger.info("Span ID decimal {}", span.context().spanId());
+ logger.info("Trace ID hex {}", span.context().traceIdString());
+ logger.info("Trace ID decimal {}", span.context().traceId());
+ }
+ return "hello";
+ }
+}
diff --git a/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
new file mode 100644
index 0000000000..ba181d730b
--- /dev/null
+++ b/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.sleuth.traceid;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = SleuthCurrentTraceIdApp.class)
+public class CurrentTraceIdAppSpringContextTest {
+
+ @Test
+ public void whenSpringContextIsBootstrapped_thenNoExceptions() {
+ }
+}
diff --git a/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java
similarity index 83%
rename from spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java
rename to spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java
index 8dc2455e63..7ddd194632 100644
--- a/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java
+++ b/spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java
@@ -1,12 +1,10 @@
-package com.baeldung;
+package com.baeldung.spring.session;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
-import com.baeldung.spring.session.SleuthWebApp;
-
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SleuthWebApp.class)
public class SpringContextTest {
From e8d5b236cca677853a34425d8e940e1863aa96fb Mon Sep 17 00:00:00 2001
From: Attila Uhrin
Date: Sun, 30 Jan 2022 11:04:38 +0100
Subject: [PATCH 054/235] Rename API endpoint.
---
.../baeldung/sleuth/traceid/SleuthTraceIdController.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
index fb4bf2bb1a..07dca487d0 100644
--- a/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
+++ b/spring-sleuth/src/main/java/com/baeldung/sleuth/traceid/SleuthTraceIdController.java
@@ -17,8 +17,8 @@ public class SleuthTraceIdController {
@Autowired
private Tracer tracer;
- @GetMapping("/hello")
- public String hello() {
+ @GetMapping("/traceid")
+ public String getSleuthTraceId() {
logger.info("Hello with Sleuth");
Span span = tracer.currentSpan();
if (span != null) {
@@ -27,6 +27,6 @@ public class SleuthTraceIdController {
logger.info("Trace ID hex {}", span.context().traceIdString());
logger.info("Trace ID decimal {}", span.context().traceId());
}
- return "hello";
+ return "Hello from Sleuth";
}
}
From 6147f0b70cc105bf16b53e7a6a6accef153b374d Mon Sep 17 00:00:00 2001
From: Attila Uhrin
Date: Mon, 31 Jan 2022 22:10:09 +0100
Subject: [PATCH 055/235] Remove empty test case.
---
.../{spring/session => }/SpringContextTest.java | 4 +++-
.../CurrentTraceIdAppSpringContextTest.java | 15 ---------------
2 files changed, 3 insertions(+), 16 deletions(-)
rename spring-sleuth/src/test/java/com/baeldung/{spring/session => }/SpringContextTest.java (83%)
delete mode 100644 spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
diff --git a/spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java
similarity index 83%
rename from spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java
rename to spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java
index 7ddd194632..8dc2455e63 100644
--- a/spring-sleuth/src/test/java/com/baeldung/spring/session/SpringContextTest.java
+++ b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java
@@ -1,10 +1,12 @@
-package com.baeldung.spring.session;
+package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
+import com.baeldung.spring.session.SleuthWebApp;
+
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SleuthWebApp.class)
public class SpringContextTest {
diff --git a/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
deleted file mode 100644
index ba181d730b..0000000000
--- a/spring-sleuth/src/test/java/com/baeldung/sleuth/traceid/CurrentTraceIdAppSpringContextTest.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.baeldung.sleuth.traceid;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringRunner;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = SleuthCurrentTraceIdApp.class)
-public class CurrentTraceIdAppSpringContextTest {
-
- @Test
- public void whenSpringContextIsBootstrapped_thenNoExceptions() {
- }
-}
From a7980094d19e9e90f1c8e948ce42d792b27d3592 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Tue, 1 Feb 2022 14:08:56 +0000
Subject: [PATCH 056/235] [JAVA-9021] Clean up uncommitted artifacts (#11754)
---
apache-poi/.gitignore | 2 +
.../core-java-lang-math-2/.gitignore | 4 +-
.../ExternalizableUnitTest.java | 31 +-
.../serialization/PersonUnitTest.java | 34 +-
.../serialization/SerializationUnitTest.java | 22 +-
.../com/baeldung/jaxb/gen/ObjectFactory.java | 96 +++---
.../com/baeldung/jaxb/gen/UserRequest.java | 174 +++++-----
.../com/baeldung/jaxb/gen/UserResponse.java | 298 +++++++++---------
.../com/baeldung/jaxb/gen/package-info.java | 4 +-
.../java/org/w3/_2001/xmlschema/Adapter1.java | 46 +--
10 files changed, 382 insertions(+), 329 deletions(-)
diff --git a/apache-poi/.gitignore b/apache-poi/.gitignore
index 9552c1e63d..ac62b36227 100644
--- a/apache-poi/.gitignore
+++ b/apache-poi/.gitignore
@@ -1,3 +1,5 @@
*.docx
temp.xls
temp.xlsx
+
+CellStyleTest_output.xlsx
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-math-2/.gitignore b/core-java-modules/core-java-lang-math-2/.gitignore
index 30b2b7442c..e4c6fe9355 100644
--- a/core-java-modules/core-java-lang-math-2/.gitignore
+++ b/core-java-modules/core-java-lang-math-2/.gitignore
@@ -1,4 +1,6 @@
/target/
.settings/
.classpath
-.project
\ No newline at end of file
+.project
+
+*.log
diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/externalizable/ExternalizableUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/externalizable/ExternalizableUnitTest.java
index 651364fb13..9012928d92 100644
--- a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/externalizable/ExternalizableUnitTest.java
+++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/externalizable/ExternalizableUnitTest.java
@@ -1,14 +1,29 @@
package com.baeldung.externalizable;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import java.io.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ExternalizableUnitTest {
- private final static String OUTPUT_FILE = "externalizable.txt";
+ private final static String OUTPUT_FILE_NAME = "externalizable.txt";
+
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+
+ private File outputFile;
+
+ @Before
+ public void setUp() throws Exception {
+ outputFile = tempFolder.newFile(OUTPUT_FILE_NAME);
+ }
@Test
public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException {
@@ -18,7 +33,7 @@ public class ExternalizableUnitTest {
c.setCode(374);
c.setName("Armenia");
- FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
c.writeExternal(objectOutputStream);
@@ -26,7 +41,7 @@ public class ExternalizableUnitTest {
objectOutputStream.close();
fileOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
+ FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Country c2 = new Country();
@@ -35,8 +50,8 @@ public class ExternalizableUnitTest {
objectInputStream.close();
fileInputStream.close();
- assertTrue(c2.getCode() == c.getCode());
- assertTrue(c2.getName().equals(c.getName()));
+ assertEquals(c2.getCode(), c.getCode());
+ assertEquals(c2.getName(), c.getName());
}
@Test
@@ -49,7 +64,7 @@ public class ExternalizableUnitTest {
r.setClimate("Mediterranean");
r.setPopulation(120.000);
- FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
r.writeExternal(objectOutputStream);
@@ -57,7 +72,7 @@ public class ExternalizableUnitTest {
objectOutputStream.close();
fileOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
+ FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Region r2 = new Region();
@@ -66,6 +81,6 @@ public class ExternalizableUnitTest {
objectInputStream.close();
fileInputStream.close();
- assertTrue(r2.getPopulation() == null);
+ assertNull(r2.getPopulation());
}
}
diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/PersonUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/PersonUnitTest.java
index dbcdf0ec9d..47dc0b9293 100644
--- a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/PersonUnitTest.java
+++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/PersonUnitTest.java
@@ -1,36 +1,54 @@
package com.baeldung.serialization;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PersonUnitTest {
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+
+ private File outputFile;
+
+ private File outputFile2;
+
+ @Before
+ public void setUp() throws Exception {
+ outputFile = tempFolder.newFile("yourfile.txt");
+ outputFile2 = tempFolder.newFile("yourfile2.txt");
+ }
+
@Test
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
Person p = new Person();
p.setAge(20);
p.setName("Joe");
- FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(p);
objectOutputStream.flush();
objectOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream("yofile.txt");
+ FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Person p2 = (Person) objectInputStream.readObject();
objectInputStream.close();
- assertTrue(p2.getAge() == p.getAge());
- assertTrue(p2.getName().equals(p.getName()));
+ assertEquals(p2.getAge(), p.getAge());
+ assertEquals(p2.getName(), p.getName());
}
@Test
@@ -46,19 +64,19 @@ public class PersonUnitTest {
e.setPerson(p);
e.setAddress(a);
- FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile2);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(e);
objectOutputStream.flush();
objectOutputStream.close();
- FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
+ FileInputStream fileInputStream = new FileInputStream(outputFile2);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Employee e2 = (Employee) objectInputStream.readObject();
objectInputStream.close();
- assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
- assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
+ assertEquals(e2.getPerson().getAge(), e.getPerson().getAge());
+ assertEquals(e2.getAddress().getHouseNumber(), (e.getAddress().getHouseNumber()));
}
}
diff --git a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java
index dde9beb2bb..a7cbc0599b 100644
--- a/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java
+++ b/core-java-modules/core-java-serialization/src/test/java/com/baeldung/serialization/SerializationUnitTest.java
@@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -13,17 +14,32 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import com.baeldung.util.MySerializationUtils;
+import org.junit.rules.TemporaryFolder;
public class SerializationUnitTest {
+ private final static String OUTPUT_FILE_NAME = "yourfile.txt";
+
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+
+ private File outputFile;
+
+ @Before
+ public void setUp() throws Exception {
+ outputFile = tempFolder.newFile(OUTPUT_FILE_NAME);
+ }
+
@Test(expected = NotSerializableException.class)
public void whenSerializing_ThenThrowsError() throws IOException {
Address address = new Address();
address.setHouseNumber(10);
- FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(address);
}
@@ -35,12 +51,12 @@ public class SerializationUnitTest {
p.setAge(20);
p.setName("Joe");
- FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
+ FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(p);
}
- FileInputStream fileInputStream = new FileInputStream("yofile.txt");
+ FileInputStream fileInputStream = new FileInputStream(outputFile);
try (ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
Person p2 = (Person) objectInputStream.readObject();
assertEquals(p2.getAge(), p.getAge());
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
index 26cd5814ac..0a3da677ce 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
@@ -1,48 +1,48 @@
-
-package com.baeldung.jaxb.gen;
-
-import javax.xml.bind.annotation.XmlRegistry;
-
-
-/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the com.baeldung.jaxb.gen package.
- * An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
- *
- */
-@XmlRegistry
-public class ObjectFactory {
-
-
- /**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
- *
- */
- public ObjectFactory() {
- }
-
- /**
- * Create an instance of {@link UserRequest }
- *
- */
- public UserRequest createUserRequest() {
- return new UserRequest();
- }
-
- /**
- * Create an instance of {@link UserResponse }
- *
- */
- public UserResponse createUserResponse() {
- return new UserResponse();
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import javax.xml.bind.annotation.XmlRegistry;
+
+
+/**
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the com.baeldung.jaxb.gen package.
+ *
An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
+ * provided in this class.
+ *
+ */
+@XmlRegistry
+public class ObjectFactory {
+
+
+ /**
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
+ *
+ */
+ public ObjectFactory() {
+ }
+
+ /**
+ * Create an instance of {@link UserRequest }
+ *
+ */
+ public UserRequest createUserRequest() {
+ return new UserRequest();
+ }
+
+ /**
+ * Create an instance of {@link UserResponse }
+ *
+ */
+ public UserResponse createUserResponse() {
+ return new UserResponse();
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
index 4cfbeb8d46..1c1abc61a6 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
@@ -1,87 +1,87 @@
-
-package com.baeldung.jaxb.gen;
-
-import java.io.Serializable;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- *
Java class for UserRequest complex type.
- *
- *
The following schema fragment specifies the expected content contained within this class.
- *
- *
- * <complexType name="UserRequest">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- *
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "UserRequest", propOrder = {
- "id",
- "name"
-})
-@XmlRootElement(name = "userRequest")
-public class UserRequest
- implements Serializable
-{
-
- private final static long serialVersionUID = -1L;
- protected int id;
- @XmlElement(required = true)
- protected String name;
-
- /**
- * Gets the value of the id property.
- *
- */
- public int getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- */
- public void setId(int value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the name property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getName() {
- return name;
- }
-
- /**
- * Sets the value of the name property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setName(String value) {
- this.name = value;
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import java.io.Serializable;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * Java class for UserRequest complex type.
+ *
+ *
The following schema fragment specifies the expected content contained within this class.
+ *
+ *
+ * <complexType name="UserRequest">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ *
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "UserRequest", propOrder = {
+ "id",
+ "name"
+})
+@XmlRootElement(name = "userRequest")
+public class UserRequest
+ implements Serializable
+{
+
+ private final static long serialVersionUID = -1L;
+ protected int id;
+ @XmlElement(required = true)
+ protected String name;
+
+ /**
+ * Gets the value of the id property.
+ *
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the value of the id property.
+ *
+ */
+ public void setId(int value) {
+ this.id = value;
+ }
+
+ /**
+ * Gets the value of the name property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the value of the name property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setName(String value) {
+ this.name = value;
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
index d86778403a..b80405e4a9 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
@@ -1,149 +1,149 @@
-
-package com.baeldung.jaxb.gen;
-
-import java.io.Serializable;
-import java.util.Calendar;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlSchemaType;
-import javax.xml.bind.annotation.XmlType;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-import org.w3._2001.xmlschema.Adapter1;
-
-
-/**
- * Java class for UserResponse complex type.
- *
- *
The following schema fragment specifies the expected content contained within this class.
- *
- *
- * <complexType name="UserResponse">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- *
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "UserResponse", propOrder = {
- "id",
- "name",
- "gender",
- "created"
-})
-@XmlRootElement(name = "userResponse")
-public class UserResponse
- implements Serializable
-{
-
- private final static long serialVersionUID = -1L;
- protected int id;
- @XmlElement(required = true)
- protected String name;
- @XmlElement(required = true)
- protected String gender;
- @XmlElement(required = true, type = String.class)
- @XmlJavaTypeAdapter(Adapter1 .class)
- @XmlSchemaType(name = "dateTime")
- protected Calendar created;
-
- /**
- * Gets the value of the id property.
- *
- */
- public int getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- */
- public void setId(int value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the name property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getName() {
- return name;
- }
-
- /**
- * Sets the value of the name property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setName(String value) {
- this.name = value;
- }
-
- /**
- * Gets the value of the gender property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getGender() {
- return gender;
- }
-
- /**
- * Sets the value of the gender property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setGender(String value) {
- this.gender = value;
- }
-
- /**
- * Gets the value of the created property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public Calendar getCreated() {
- return created;
- }
-
- /**
- * Sets the value of the created property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCreated(Calendar value) {
- this.created = value;
- }
-
-}
+
+package com.baeldung.jaxb.gen;
+
+import java.io.Serializable;
+import java.util.Calendar;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlSchemaType;
+import javax.xml.bind.annotation.XmlType;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import org.w3._2001.xmlschema.Adapter1;
+
+
+/**
+ * Java class for UserResponse complex type.
+ *
+ *
The following schema fragment specifies the expected content contained within this class.
+ *
+ *
+ * <complexType name="UserResponse">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ *
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "UserResponse", propOrder = {
+ "id",
+ "name",
+ "gender",
+ "created"
+})
+@XmlRootElement(name = "userResponse")
+public class UserResponse
+ implements Serializable
+{
+
+ private final static long serialVersionUID = -1L;
+ protected int id;
+ @XmlElement(required = true)
+ protected String name;
+ @XmlElement(required = true)
+ protected String gender;
+ @XmlElement(required = true, type = String.class)
+ @XmlJavaTypeAdapter(Adapter1 .class)
+ @XmlSchemaType(name = "dateTime")
+ protected Calendar created;
+
+ /**
+ * Gets the value of the id property.
+ *
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the value of the id property.
+ *
+ */
+ public void setId(int value) {
+ this.id = value;
+ }
+
+ /**
+ * Gets the value of the name property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the value of the name property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setName(String value) {
+ this.name = value;
+ }
+
+ /**
+ * Gets the value of the gender property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getGender() {
+ return gender;
+ }
+
+ /**
+ * Sets the value of the gender property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setGender(String value) {
+ this.gender = value;
+ }
+
+ /**
+ * Gets the value of the created property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public Calendar getCreated() {
+ return created;
+ }
+
+ /**
+ * Sets the value of the created property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCreated(Calendar value) {
+ this.created = value;
+ }
+
+}
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
index 6384eab27f..639d00179c 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
@@ -1,2 +1,2 @@
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
-package com.baeldung.jaxb.gen;
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+package com.baeldung.jaxb.gen;
diff --git a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
index b4865b5510..54b3c360dc 100644
--- a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
+++ b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
@@ -1,23 +1,23 @@
-
-package org.w3._2001.xmlschema;
-
-import java.util.Calendar;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
-
-public class Adapter1
- extends XmlAdapter
-{
-
-
- public Calendar unmarshal(String value) {
- return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
- }
-
- public String marshal(Calendar value) {
- if (value == null) {
- return null;
- }
- return (javax.xml.bind.DatatypeConverter.printDateTime(value));
- }
-
-}
+
+package org.w3._2001.xmlschema;
+
+import java.util.Calendar;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+
+public class Adapter1
+ extends XmlAdapter
+{
+
+
+ public Calendar unmarshal(String value) {
+ return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
+ }
+
+ public String marshal(Calendar value) {
+ if (value == null) {
+ return null;
+ }
+ return (javax.xml.bind.DatatypeConverter.printDateTime(value));
+ }
+
+}
From 5290d7ab8733331674029cfb3337707960864461 Mon Sep 17 00:00:00 2001
From: KevinGilmore
Date: Tue, 1 Feb 2022 21:52:22 -0600
Subject: [PATCH 057/235] BAEL-5308: add link back to article (#11764)
---
graphql/graphql-dgs/README.md | 7 +++++++
1 file changed, 7 insertions(+)
create mode 100644 graphql/graphql-dgs/README.md
diff --git a/graphql/graphql-dgs/README.md b/graphql/graphql-dgs/README.md
new file mode 100644
index 0000000000..6614891b31
--- /dev/null
+++ b/graphql/graphql-dgs/README.md
@@ -0,0 +1,7 @@
+## GraphQL Domain Graph Service (DGS)
+
+This module contains articles about GraphQL using the Netflix Domain Graph Service (DGS).
+
+## Relevant articles:
+
+- [An Introduction to Domain Graph Service (DGS) Framework](https://www.baeldung.com/spring-boot-domain-graph-service)
From fe6b84fd5f8307c6811d8ec40d6cc32c84d7f4f1 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 2 Feb 2022 17:44:32 +0800
Subject: [PATCH 058/235] Update README.md
---
persistence-modules/java-mongodb/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md
index 34acd60c57..fe30c2999e 100644
--- a/persistence-modules/java-mongodb/README.md
+++ b/persistence-modules/java-mongodb/README.md
@@ -12,3 +12,4 @@ This module contains articles about MongoDB in Java.
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
+- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
From 44d4ca1278bd349e4844a290515f95852bc060c6 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 2 Feb 2022 17:48:53 +0800
Subject: [PATCH 059/235] Update README.md
---
feign/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/feign/README.md b/feign/README.md
index 03051671d5..eeff55a4d4 100644
--- a/feign/README.md
+++ b/feign/README.md
@@ -5,4 +5,5 @@ This module contains articles about Feign
### Relevant Articles:
- [Intro to Feign](https://www.baeldung.com/intro-to-feign)
+- [Retrying Feign Calls](https://www.baeldung.com/feign-retry)
From 17f39de3ab5f307483c09e24016e3f2ca67a2ec2 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Wed, 2 Feb 2022 20:28:21 +0000
Subject: [PATCH 060/235] [JAVA-9839] Cleanup test files
---
.../rdd/TransformationsUnitTest.java | 22 ++++++++++++-------
1 file changed, 14 insertions(+), 8 deletions(-)
diff --git a/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java b/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java
index 4b2d9e1127..01e7d3adfc 100644
--- a/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java
+++ b/apache-spark/src/test/java/com/baeldung/differences/rdd/TransformationsUnitTest.java
@@ -1,9 +1,9 @@
package com.baeldung.differences.rdd;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
@@ -12,12 +12,15 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
+import java.io.File;
+
public class TransformationsUnitTest {
-
+
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
+
private static JavaSparkContext sc;
private static JavaRDD tourists;
-
+
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
@@ -25,8 +28,11 @@ public class TransformationsUnitTest {
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
+
+ // delete previous output dir and files
+ FileUtils.deleteQuietly(new File("data/output"));
}
-
+
@AfterClass
public static void cleanup() {
sc.close();
@@ -39,9 +45,9 @@ public class TransformationsUnitTest {
return columns[1].toUpperCase();
})
.distinct();
-
+
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
-
+
upperCaseCountries.foreach(country -> {
//replace non alphanumerical characters
country = country.replaceAll("[^a-zA-Z]", "");
@@ -52,9 +58,9 @@ public class TransformationsUnitTest {
@Test
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
JavaRDD touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
-
+
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
-
+
touristsInMexico.foreach(record -> {
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
});
From 9cb6ff1227750aeb25db44183ce945f6bcf9835e Mon Sep 17 00:00:00 2001
From: Graham Cox
Date: Thu, 3 Feb 2022 07:47:26 +0000
Subject: [PATCH 061/235] BAEL-5229: Code for Fauna article
---
persistence-modules/fauna/.gitignore | 1 +
persistence-modules/fauna/pom.xml | 56 ++++++++
.../faunablog/FaunaBlogApplication.java | 13 ++
.../faunablog/FaunaConfiguration.java | 25 ++++
.../faunablog/WebSecurityConfiguration.java | 35 +++++
.../com/baeldung/faunablog/posts/Author.java | 3 +
.../com/baeldung/faunablog/posts/Post.java | 5 +
.../faunablog/posts/PostsController.java | 50 +++++++
.../faunablog/posts/PostsService.java | 124 ++++++++++++++++++
.../baeldung/faunablog/posts/UpdatedPost.java | 3 +
.../users/FaunaUserDetailsService.java | 44 +++++++
.../src/main/resources/application.properties | 0
12 files changed, 359 insertions(+)
create mode 100644 persistence-modules/fauna/.gitignore
create mode 100644 persistence-modules/fauna/pom.xml
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaConfiguration.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Author.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Post.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/UpdatedPost.java
create mode 100644 persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java
create mode 100644 persistence-modules/fauna/src/main/resources/application.properties
diff --git a/persistence-modules/fauna/.gitignore b/persistence-modules/fauna/.gitignore
new file mode 100644
index 0000000000..c37fa0c4b3
--- /dev/null
+++ b/persistence-modules/fauna/.gitignore
@@ -0,0 +1 @@
+/application.properties
diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml
new file mode 100644
index 0000000000..72c0f0a751
--- /dev/null
+++ b/persistence-modules/fauna/pom.xml
@@ -0,0 +1,56 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.6.2
+
+
+ com.baeldung
+ fauna-blog
+ 0.0.1-SNAPSHOT
+ fauna-blog
+ Blogging Service built with FaunaDB
+
+ 17
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ com.faunadb
+ faunadb-java
+ 4.2.0
+ compile
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
new file mode 100644
index 0000000000..f0ca6881b7
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.faunablog;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class FaunaBlogApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(FaunaBlogApplication.class, args);
+ }
+
+}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaConfiguration.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaConfiguration.java
new file mode 100644
index 0000000000..9964431475
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaConfiguration.java
@@ -0,0 +1,25 @@
+package com.baeldung.faunablog;
+
+import com.faunadb.client.FaunaClient;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.net.MalformedURLException;
+
+@Configuration
+class FaunaConfiguration {
+ @Value("https://db.${fauna.region}.fauna.com/")
+ private String faunaUrl;
+
+ @Value("${fauna.secret}")
+ private String faunaSecret;
+
+ @Bean
+ FaunaClient getFaunaClient() throws MalformedURLException {
+ return FaunaClient.builder()
+ .withEndpoint(faunaUrl)
+ .withSecret(faunaSecret)
+ .build();
+ }
+}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java
new file mode 100644
index 0000000000..da99b7578e
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java
@@ -0,0 +1,35 @@
+package com.baeldung.faunablog;
+
+import com.baeldung.faunablog.users.FaunaUserDetailsService;
+import com.faunadb.client.FaunaClient;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.core.userdetails.UserDetailsService;
+
+@Configuration
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+ @Autowired
+ private FaunaClient faunaClient;
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable();
+ http.authorizeRequests()
+ .antMatchers("/**").permitAll()
+ .and().httpBasic();
+ }
+
+ @Bean
+ @Override
+ public UserDetailsService userDetailsService() {
+ return new FaunaUserDetailsService(faunaClient);
+ }
+}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Author.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Author.java
new file mode 100644
index 0000000000..ec4854621d
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Author.java
@@ -0,0 +1,3 @@
+package com.baeldung.faunablog.posts;
+
+public record Author(String username, String name) {}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Post.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Post.java
new file mode 100644
index 0000000000..62b6558a37
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/Post.java
@@ -0,0 +1,5 @@
+package com.baeldung.faunablog.posts;
+
+import java.time.Instant;
+
+public record Post(String id, String title, String content, Author author, Instant created, Long version) {}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java
new file mode 100644
index 0000000000..e8e6316ea8
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java
@@ -0,0 +1,50 @@
+package com.baeldung.faunablog.posts;
+
+import com.faunadb.client.errors.NotFoundException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.server.ResponseStatusException;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+@RestController
+@RequestMapping("/posts")
+public class PostsController {
+ @Autowired
+ private PostsService postsService;
+
+ @GetMapping
+ public List listPosts(@RequestParam(value = "author", required = false) String author) throws ExecutionException, InterruptedException {
+ return author == null ? postsService.getAllPosts() : postsService.getAuthorPosts("graham");
+ }
+
+ @GetMapping("/{id}")
+ public Post getPost(@PathVariable("id") String id, @RequestParam(value = "before", required = false) Long before)
+ throws ExecutionException, InterruptedException {
+ return postsService.getPost(id, before);
+ }
+
+ @PostMapping
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ @PreAuthorize("isAuthenticated()")
+ public void createPost(@RequestBody UpdatedPost post) throws ExecutionException, InterruptedException {
+ String name = SecurityContextHolder.getContext().getAuthentication().getName();
+ postsService.createPost(name, post.title(), post.content());
+ }
+
+ @PutMapping("/{id}")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ @PreAuthorize("isAuthenticated()")
+ public void updatePost(@PathVariable("id") String id, @RequestBody UpdatedPost post)
+ throws ExecutionException, InterruptedException {
+ postsService.updatePost(id, post.title(), post.content());
+ }
+
+ @ExceptionHandler(NotFoundException.class)
+ @ResponseStatus(HttpStatus.NOT_FOUND)
+ public void postNotFound() {}
+}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java
new file mode 100644
index 0000000000..5143a24b28
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java
@@ -0,0 +1,124 @@
+package com.baeldung.faunablog.posts;
+
+import com.faunadb.client.FaunaClient;
+import com.faunadb.client.types.Value;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+
+import static com.faunadb.client.query.Language.*;
+
+@Component
+public class PostsService {
+ @Autowired
+ private FaunaClient faunaClient;
+
+ Post getPost(String id, Long before) throws ExecutionException, InterruptedException {
+ var query = Get(Ref(Collection("posts"), id));
+ if (before != null) {
+ query = At(Value(before - 1), query);
+ }
+
+ var postResult= faunaClient.query(
+ Let(
+ "post", query
+ ).in(
+ Obj(
+ "post", Var("post"),
+ "author", Get(Select(Arr(Value("data"), Value("authorRef")), Var("post")))
+ )
+ )).get();
+
+ return parsePost(postResult);
+ }
+
+ List getAllPosts() throws ExecutionException, InterruptedException {
+ var postsResult = faunaClient.query(Map(
+ Paginate(
+ Join(
+ Documents(Collection("posts")),
+ Index("posts_sort_by_created_desc")
+ )
+ ),
+ Lambda(
+ Arr(Value("extra"), Value("ref")),
+ Obj(
+ "post", Get(Var("ref")),
+ "author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
+ )
+ )
+ )).get();
+
+ var posts = postsResult.at("data").asCollectionOf(Value.class).get();
+ return posts.stream().map(this::parsePost).collect(Collectors.toList());
+ }
+
+ List getAuthorPosts(String author) throws ExecutionException, InterruptedException {
+ var postsResult = faunaClient.query(Map(
+ Paginate(
+ Join(
+ Match(Index("posts_by_author"), Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author))))),
+ Index("posts_sort_by_created_desc")
+ )
+ ),
+ Lambda(
+ Arr(Value("extra"), Value("ref")),
+ Obj(
+ "post", Get(Var("ref")),
+ "author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
+ )
+ )
+ )).get();
+
+ var posts = postsResult.at("data").asCollectionOf(Value.class).get();
+ return posts.stream().map(this::parsePost).collect(Collectors.toList());
+ }
+
+ public void createPost(String author, String title, String contents) throws ExecutionException, InterruptedException {
+ faunaClient.query(
+ Create(Collection("posts"),
+ Obj(
+ "data", Obj(
+ "title", Value(title),
+ "contents", Value(contents),
+ "created", Now(),
+ "authorRef", Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author)))))
+ )
+ )
+ ).get();
+ }
+
+ public void updatePost(String id, String title, String contents) throws ExecutionException, InterruptedException {
+ faunaClient.query(
+ Update(Ref(Collection("posts"), id),
+ Obj(
+ "data", Obj(
+ "title", Value(title),
+ "contents", Value(contents))
+ )
+ )
+ ).get();
+ }
+
+ private Post parsePost(Value entry) {
+ var author = entry.at("author");
+ var post = entry.at("post");
+
+ return new Post(
+ post.at("ref").to(Value.RefV.class).get().getId(),
+ post.at("data", "title").to(String.class).get(),
+ post.at("data", "contents").to(String.class).get(),
+ new Author(
+ author.at("data", "username").to(String.class).get(),
+ author.at("data", "name").to(String.class).get()
+ ),
+ post.at("data", "created").to(Instant.class).get(),
+ post.at("ts").to(Long.class).get()
+ );
+ }
+}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/UpdatedPost.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/UpdatedPost.java
new file mode 100644
index 0000000000..9850cd5927
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/UpdatedPost.java
@@ -0,0 +1,3 @@
+package com.baeldung.faunablog.posts;
+
+public record UpdatedPost(String title, String content) {}
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java
new file mode 100644
index 0000000000..2e88aaa477
--- /dev/null
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java
@@ -0,0 +1,44 @@
+package com.baeldung.faunablog.users;
+
+import com.faunadb.client.FaunaClient;
+import com.faunadb.client.types.Value;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+
+import java.util.concurrent.ExecutionException;
+
+import static com.faunadb.client.query.Language.*;
+
+public class FaunaUserDetailsService implements UserDetailsService {
+ private FaunaClient faunaClient;
+
+ public FaunaUserDetailsService(FaunaClient faunaClient) {
+ this.faunaClient = faunaClient;
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ try {
+ Value user = faunaClient.query(Map(
+ Paginate(Match(Index("users_by_username"), Value(username))),
+ Lambda(Value("user"), Get(Var("user")))))
+ .get();
+
+ Value userData = user.at("data").at(0).orNull();
+ if (userData == null) {
+ throw new UsernameNotFoundException("User not found");
+ }
+
+ return User.withDefaultPasswordEncoder()
+ .username(userData.at("data", "username").to(String.class).orNull())
+ .password(userData.at("data", "password").to(String.class).orNull())
+ .roles("USER")
+ .build();
+ } catch (ExecutionException | InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
+
diff --git a/persistence-modules/fauna/src/main/resources/application.properties b/persistence-modules/fauna/src/main/resources/application.properties
new file mode 100644
index 0000000000..e69de29bb2
From 7274b31c4414f7229f653c1c23f6458919ed647f Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Thu, 3 Feb 2022 10:21:00 +0100
Subject: [PATCH 062/235] JAVA-9840: Upgrade parent-boot-2 to 2.6.3
---
parent-boot-2/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml
index 109bf3b64f..b7f33de237 100644
--- a/parent-boot-2/pom.xml
+++ b/parent-boot-2/pom.xml
@@ -88,7 +88,7 @@
3.3.0
1.0.22.RELEASE
- 2.6.1
+ 2.6.3
1.9.1
From 533f2014a84d6c517e368f62d8b0cf162a7d43f1 Mon Sep 17 00:00:00 2001
From: Gaetano Piazzolla
Date: Thu, 3 Feb 2022 11:17:55 +0100
Subject: [PATCH 063/235] BAEL-5319 - Remove Basic Error Controller in Swagger
(#11743)
* BAEL-5319 - Remove Basic Error Controller in Swagger
* BAEL-5319 - fixed style
* BAEL-5319 - removed comments and private info
* BAEL-5319 - removed private info
* two space indent for line continuation, optimized import.
Co-authored-by: gpiazzolla
---
.../SpringBootSwaggerConfApplication.java | 13 +++++++
.../configuration/SwaggerConfiguration.java | 37 +++++++++++++++++++
.../ErrorControllerExcludedForAnnotation.java | 17 +++++++++
.../ErrorControllerExcludedForApiIgnore.java | 21 +++++++++++
.../ErrorControllerExcludedForPath.java | 19 ++++++++++
.../controller/RegularRestController.java | 33 +++++++++++++++++
.../ErrorControllerExcludedForPackage.java | 17 +++++++++
.../src/main/resources/application.properties | 1 +
...ExcludeErrorControllerIntegrationTest.java | 33 +++++++++++++++++
9 files changed, 191 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/SpringBootSwaggerConfApplication.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/configuration/SwaggerConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForAnnotation.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForApiIgnore.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForPath.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/RegularRestController.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/excluded/ErrorControllerExcludedForPackage.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerconf/SwaggerConfExcludeErrorControllerIntegrationTest.java
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/SpringBootSwaggerConfApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/SpringBootSwaggerConfApplication.java
new file mode 100644
index 0000000000..1d2e129f26
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/SpringBootSwaggerConfApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerconf;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SpringBootSwaggerConfApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringBootSwaggerConfApplication.class, args);
+ }
+
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/configuration/SwaggerConfiguration.java
new file mode 100644
index 0000000000..a78335a2fe
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/configuration/SwaggerConfiguration.java
@@ -0,0 +1,37 @@
+package com.baeldung.swaggerconf.configuration;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.bind.annotation.RestController;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+import java.util.Collections;
+
+import static springfox.documentation.builders.PathSelectors.regex;
+
+@Configuration
+@EnableSwagger2
+public class SwaggerConfiguration {
+
+ private ApiInfo apiInfo() {
+ return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service",
+ new Contact("General UserName", "www.baeldung.com", "user-name@gmail.com"),
+ "License of API", "API license URL", Collections.emptyList());
+ }
+
+ @Bean
+ public Docket api() {
+ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("com.baeldung.swaggerconf.controller"))
+ .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
+ .paths(regex("/good-path/.*"))
+ .build();
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForAnnotation.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForAnnotation.java
new file mode 100644
index 0000000000..65059bf446
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForAnnotation.java
@@ -0,0 +1,17 @@
+package com.baeldung.swaggerconf.controller;
+
+import org.springframework.boot.autoconfigure.web.ServerProperties;
+import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
+import org.springframework.boot.web.servlet.error.ErrorAttributes;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Component
+@RequestMapping("good-path/error-excluded-annotation")
+public class ErrorControllerExcludedForAnnotation extends BasicErrorController {
+
+ public ErrorControllerExcludedForAnnotation(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
+ super(errorAttributes, serverProperties.getError());
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForApiIgnore.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForApiIgnore.java
new file mode 100644
index 0000000000..88208d8446
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForApiIgnore.java
@@ -0,0 +1,21 @@
+package com.baeldung.swaggerconf.controller;
+
+import org.springframework.boot.autoconfigure.web.ServerProperties;
+import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
+import org.springframework.boot.web.servlet.error.ErrorAttributes;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import springfox.documentation.annotations.ApiIgnore;
+
+@Component
+@RequestMapping("good-path/error-excluded-apiignore")
+@RestController
+@ApiIgnore
+public class ErrorControllerExcludedForApiIgnore extends BasicErrorController {
+
+ public ErrorControllerExcludedForApiIgnore(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
+ super(errorAttributes, serverProperties.getError());
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForPath.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForPath.java
new file mode 100644
index 0000000000..5cea4f5ef9
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/ErrorControllerExcludedForPath.java
@@ -0,0 +1,19 @@
+package com.baeldung.swaggerconf.controller;
+
+import org.springframework.boot.autoconfigure.web.ServerProperties;
+import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
+import org.springframework.boot.web.servlet.error.ErrorAttributes;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@Component
+@RequestMapping("wrong-path/error-excluded-path")
+@RestController
+public class ErrorControllerExcludedForPath extends BasicErrorController {
+
+ public ErrorControllerExcludedForPath(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
+ super(errorAttributes, serverProperties.getError());
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/RegularRestController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/RegularRestController.java
new file mode 100644
index 0000000000..163826e626
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/controller/RegularRestController.java
@@ -0,0 +1,33 @@
+package com.baeldung.swaggerconf.controller;
+
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+
+@RestController
+@RequestMapping("good-path")
+public class RegularRestController {
+
+ @ApiOperation(value = "This method is used to get the author name.")
+ @GetMapping("/getAuthor")
+ public String getAuthor() {
+ return "Name Surname";
+ }
+
+ @ApiOperation(value = "This method is used to get the current date.")
+ @GetMapping("/getDate")
+ public LocalDate getDate() {
+ return LocalDate.now();
+ }
+
+ @ApiOperation(value = "This method is used to get the current time.")
+ @GetMapping("/getTime")
+ public LocalTime getTime() {
+ return LocalTime.now();
+ }
+
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/excluded/ErrorControllerExcludedForPackage.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/excluded/ErrorControllerExcludedForPackage.java
new file mode 100644
index 0000000000..a3b5a3fe63
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerconf/excluded/ErrorControllerExcludedForPackage.java
@@ -0,0 +1,17 @@
+package com.baeldung.swaggerconf.excluded;
+
+import org.springframework.boot.autoconfigure.web.ServerProperties;
+import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
+import org.springframework.boot.web.servlet.error.ErrorAttributes;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Component
+@RequestMapping("good-path/error-excluded-package")
+public class ErrorControllerExcludedForPackage extends BasicErrorController {
+
+ public ErrorControllerExcludedForPackage(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
+ super(errorAttributes, serverProperties.getError());
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties b/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties
index e69de29bb2..a4e98652bc 100644
--- a/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties
+++ b/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties
@@ -0,0 +1 @@
+spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerconf/SwaggerConfExcludeErrorControllerIntegrationTest.java b/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerconf/SwaggerConfExcludeErrorControllerIntegrationTest.java
new file mode 100644
index 0000000000..c0a5c54d69
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerconf/SwaggerConfExcludeErrorControllerIntegrationTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.swaggerconf;
+
+import org.junit.Assert;
+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.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.ResultActions;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@AutoConfigureMockMvc
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class SwaggerConfExcludeErrorControllerIntegrationTest {
+
+ @Autowired
+ private MockMvc mvc;
+
+ @Test
+ public void whenCallingSwaggerJSON_stringObjectDoesNotContainAnyErrorControllers() throws Exception {
+ ResultActions resultActions = mvc.perform(get("/v2/api-docs")).andExpect(status().isOk());
+ MvcResult result = resultActions.andReturn();
+ String content = result.getResponse().getContentAsString();
+ Assert.assertNotNull(content);
+ Assert.assertFalse(content.contains("error-controller"));
+ }
+}
\ No newline at end of file
From 15bd0c096653d431ab79772e7276806504b52723 Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Thu, 3 Feb 2022 11:23:05 +0100
Subject: [PATCH 064/235] JAVA-9840: Upgrade spring-core version to 5.3.15
---
persistence-modules/spring-data-mongodb-reactive/pom.xml | 2 +-
persistence-modules/spring-mybatis/pom.xml | 2 +-
spring-boot-modules/spring-boot-2/pom.xml | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml
index 0e4efed6e6..ac2bf14635 100644
--- a/persistence-modules/spring-data-mongodb-reactive/pom.xml
+++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml
@@ -124,7 +124,7 @@
- 5.3.13
+ 5.3.15
4.5.2
3.3.1.RELEASE
3.2.6
diff --git a/persistence-modules/spring-mybatis/pom.xml b/persistence-modules/spring-mybatis/pom.xml
index eb0ebd723d..65a8581f97 100644
--- a/persistence-modules/spring-mybatis/pom.xml
+++ b/persistence-modules/spring-mybatis/pom.xml
@@ -78,7 +78,7 @@
- 5.3.13
+ 5.3.15
2.0.6
3.5.2
diff --git a/spring-boot-modules/spring-boot-2/pom.xml b/spring-boot-modules/spring-boot-2/pom.xml
index 65bacb7c47..08dc517fa0 100644
--- a/spring-boot-modules/spring-boot-2/pom.xml
+++ b/spring-boot-modules/spring-boot-2/pom.xml
@@ -63,7 +63,7 @@
2.14.1
- 5.3.13
+ 5.3.15
11
11
From 7728df176e1a15512f59ef37f580eea9011cbfe8 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Thu, 3 Feb 2022 10:37:47 +0000
Subject: [PATCH 065/235] [JAVA-9616] Add simple demo application for mvn
wrapper
---
spring-boot-modules/spring-boot-artifacts/pom.xml | 8 ++++----
.../com/baeldung/wrapper/DemoApplication.java | 12 ++++++++++++
.../java/com/baeldung/wrapper/DemoController.java | 15 +++++++++++++++
3 files changed, 31 insertions(+), 4 deletions(-)
create mode 100644 spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoApplication.java
create mode 100644 spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoController.java
diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml
index 6bf75491eb..0292dc95cf 100644
--- a/spring-boot-modules/spring-boot-artifacts/pom.xml
+++ b/spring-boot-modules/spring-boot-artifacts/pom.xml
@@ -101,7 +101,7 @@
maven-failsafe-plugin
2.18
-
integration-tests
@@ -110,7 +110,7 @@
verify
-
**/ExternalPropertyFileLoaderIntegrationTest.java
@@ -186,7 +186,7 @@
- com.baeldung.boot.Application
+ com.baeldung.wrapper.DemoApplication
3.1.1
3.3.7-1
2.2
@@ -195,4 +195,4 @@
4.5.8
-
\ No newline at end of file
+
diff --git a/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoApplication.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoApplication.java
new file mode 100644
index 0000000000..d0a7e96bec
--- /dev/null
+++ b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoApplication.java
@@ -0,0 +1,12 @@
+package com.baeldung.wrapper;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication(scanBasePackages = { "com.baeldung" })
+public class DemoApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(DemoApplication.class, args);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoController.java b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoController.java
new file mode 100644
index 0000000000..530a1d584e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-artifacts/src/main/java/com/baeldung/wrapper/DemoController.java
@@ -0,0 +1,15 @@
+package com.baeldung.wrapper;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+
+@Controller
+public class DemoController {
+
+ @GetMapping(value = "/demo")
+ public String demo(Model model) {
+ return "index";
+ }
+
+}
From 27143e9157f0da61db584cbb8fe0d9cb84fd8b5a Mon Sep 17 00:00:00 2001
From: kwoyke
Date: Thu, 3 Feb 2022 13:52:37 +0100
Subject: [PATCH 066/235] JAVA-9512: Delete garbage file (#11766)
---
book | 0
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 book
diff --git a/book b/book
deleted file mode 100644
index e69de29bb2..0000000000
From b15df898347e1c8f8e508e7d1c5b66d21dd44f01 Mon Sep 17 00:00:00 2001
From: Andres Luzuriaga
Date: Fri, 7 Jan 2022 23:56:49 -0500
Subject: [PATCH 067/235] BAEL-4498 JDBC Connection Status
---
.../ConnectionValidation.java | 65 +++++++++++++++++++
.../ConnectionValidationUnitTest.java | 38 +++++++++++
2 files changed, 103 insertions(+)
create mode 100644 persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/connectionstatus/ConnectionValidation.java
create mode 100644 persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/connectionstatus/ConnectionValidationUnitTest.java
diff --git a/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/connectionstatus/ConnectionValidation.java b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/connectionstatus/ConnectionValidation.java
new file mode 100644
index 0000000000..b6818d25c2
--- /dev/null
+++ b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/connectionstatus/ConnectionValidation.java
@@ -0,0 +1,65 @@
+package com.baeldung.connectionstatus;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+public class ConnectionValidation
+{
+
+ public static Connection getConnection()
+ throws Exception
+ {
+ Class.forName("org.h2.Driver");
+ String url = "jdbc:h2:mem:testdb";
+ return DriverManager.getConnection(url, "user", "password");
+ }
+
+ public static void runIfOpened(Connection connection)
+ throws SQLException
+ {
+ if (connection != null && !connection.isClosed()) {
+ // run sql statements
+ }
+ else {
+ // handle closed connection
+ }
+ }
+
+ public static void runIfValid(Connection connection)
+ throws SQLException
+ {
+ // Try to validate connection with a 5 seconds timeout
+ if (connection.isValid(5)) {
+ // run sql statements
+ }
+ else {
+ // handle invalid connection
+ }
+ }
+
+ public static void runIfConnectionValid(Connection connection)
+ {
+ if (isConnectionValid(connection)) {
+ // run sql statements
+ }
+ else {
+ // handle invalid connection
+ }
+ }
+
+ public static boolean isConnectionValid(Connection connection)
+ {
+ try {
+ if (connection != null && !connection.isClosed()) {
+ // Running a simple validation query
+ connection.prepareStatement("SELECT 1");
+ return true;
+ }
+ }
+ catch (SQLException e) {
+ // log some useful data here
+ }
+ return false;
+ }
+}
diff --git a/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/connectionstatus/ConnectionValidationUnitTest.java b/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/connectionstatus/ConnectionValidationUnitTest.java
new file mode 100644
index 0000000000..26356931cc
--- /dev/null
+++ b/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/connectionstatus/ConnectionValidationUnitTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.connectionstatus;
+
+import org.junit.jupiter.api.Test;
+
+import java.sql.Connection;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConnectionValidationUnitTest
+{
+ @Test
+ void givenConnectionObject_whenCreated_thenIsNotClosed()
+ throws Exception
+ {
+ Connection connection = ConnectionValidation.getConnection();
+ assertNotNull(connection);
+ assertFalse(connection.isClosed());
+ }
+
+ @Test
+ void givenConnectionObject_whenCreated_thenIsValid()
+ throws Exception
+ {
+ Connection connection = ConnectionValidation.getConnection();
+ assertTrue(connection.isValid(0));
+ }
+
+ @Test
+ void givenConnectionObject_whenValidated_thenIsValid()
+ throws Exception
+ {
+ Connection connection = ConnectionValidation.getConnection();
+ assertTrue(ConnectionValidation.isConnectionValid(connection));
+ }
+
+}
From 7a7fe1100280cc5c3311fe6dddf2b215d6059c64 Mon Sep 17 00:00:00 2001
From: Graham Cox
Date: Fri, 4 Feb 2022 07:38:45 +0000
Subject: [PATCH 068/235] Added to the '*-jdk9-and-above' profiles
---
pom.xml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/pom.xml b/pom.xml
index f2a230357c..c2979b9ed1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1345,6 +1345,7 @@
quarkus-jandex
spring-boot-modules/spring-boot-cassandre
testing-modules/testing-assertions
+ persistence-modules/fauna
@@ -1402,6 +1403,7 @@
quarkus-jandex
spring-boot-modules/spring-boot-cassandre
testing-modules/testing-assertions
+ persistence-modules/fauna
From 694041bc875d10fc4e1f143987e70a505331ba7e Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Thu, 3 Feb 2022 21:32:04 +0000
Subject: [PATCH 069/235] [JAVA-9814] Cleanup apache-olingo module
---
apache-olingo/{olingo2 => }/.gitignore | 1 +
apache-olingo/Samples.md | 18 ++++----
apache-olingo/{olingo2 => }/pom.xml | 20 ++++-----
.../olingo2/CarsODataJPAServiceFactory.java | 13 ++----
.../examples/olingo2/JerseyConfig.java | 43 ++++++++-----------
.../olingo2/Olingo2SampleApplication.java | 2 +-
.../examples/olingo2/domain/CarMaker.java | 0
.../examples/olingo2/domain/CarModel.java | 0
.../src/main/resources/application.yml | 0
.../{olingo2 => }/src/main/resources/data.sql | 0
.../src/main/resources/logback.xml | 0
...ngo2SampleApplicationIntegrationTest.java} | 2 +-
.../src/test/resources/logback-test.xml | 0
.../src/test/resources/olingo2-queries.json | 0
pom.xml | 4 +-
15 files changed, 46 insertions(+), 57 deletions(-)
rename apache-olingo/{olingo2 => }/.gitignore (99%)
rename apache-olingo/{olingo2 => }/pom.xml (85%)
rename apache-olingo/{olingo2 => }/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java (97%)
rename apache-olingo/{olingo2 => }/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java (89%)
rename apache-olingo/{olingo2 => }/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java (88%)
rename apache-olingo/{olingo2 => }/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java (100%)
rename apache-olingo/{olingo2 => }/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java (100%)
rename apache-olingo/{olingo2 => }/src/main/resources/application.yml (100%)
rename apache-olingo/{olingo2 => }/src/main/resources/data.sql (100%)
rename apache-olingo/{olingo2 => }/src/main/resources/logback.xml (100%)
rename apache-olingo/{olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java => src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationIntegrationTest.java} (84%)
rename apache-olingo/{olingo2 => }/src/test/resources/logback-test.xml (100%)
rename apache-olingo/{olingo2 => }/src/test/resources/olingo2-queries.json (100%)
diff --git a/apache-olingo/olingo2/.gitignore b/apache-olingo/.gitignore
similarity index 99%
rename from apache-olingo/olingo2/.gitignore
rename to apache-olingo/.gitignore
index 153c9335eb..b85b366850 100644
--- a/apache-olingo/olingo2/.gitignore
+++ b/apache-olingo/.gitignore
@@ -27,3 +27,4 @@ HELP.md
### VS Code ###
.vscode/
+
diff --git a/apache-olingo/Samples.md b/apache-olingo/Samples.md
index def8971d64..66f514b4d9 100644
--- a/apache-olingo/Samples.md
+++ b/apache-olingo/Samples.md
@@ -4,15 +4,15 @@ This following table contains test URLs that can be used with the Olingo V2 demo
| URL | Description |
|------------------------------------------|-------------------------------------------------|
-| `http://localhost:8180/odata/$metadata` | fetch OData metadata document |
-| `http://localhost:8180/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
-| `http://localhost:8180/odata/CarMakers?$count` | Return total count of entities in this set |
-| `http://localhost:8180/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
-| `http://localhost:8180/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
-| `http://localhost:8180/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
-| `http://localhost:8180/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
-| `http://localhost:8180/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
-| `http://localhost:8180/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|
+| `http://localhost:8080/odata/$metadata` | fetch OData metadata document |
+| `http://localhost:8080/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
+| `http://localhost:8080/odata/CarMakers?$count` | Return total count of entities in this set |
+| `http://localhost:8080/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
+| `http://localhost:8080/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
+| `http://localhost:8080/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
+| `http://localhost:8080/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
+| `http://localhost:8080/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
+| `http://localhost:8080/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|
diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/pom.xml
similarity index 85%
rename from apache-olingo/olingo2/pom.xml
rename to apache-olingo/pom.xml
index c86428d054..5de0dfd511 100644
--- a/apache-olingo/olingo2/pom.xml
+++ b/apache-olingo/pom.xml
@@ -3,16 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung.examples.olingo2
- olingo2
- olingo2
- Sample Olingo 2 Project
+ com.baeldung.examples.olingo
+ apache-olingo
+ apache-olingo
+ Sample Apache Olingo Project
com.baeldung
parent-boot-2
0.0.1-SNAPSHOT
- ../../parent-boot-2
+ ../parent-boot-2
@@ -43,7 +43,7 @@
org.apache.olingo
olingo-odata2-core
- ${olingo2.version}
+ ${olingo.version}
@@ -55,12 +55,12 @@
org.apache.olingo
olingo-odata2-jpa-processor-core
- ${olingo2.version}
+ ${olingo.version}
org.apache.olingo
olingo-odata2-jpa-processor-ref
- ${olingo2.version}
+ ${olingo.version}
org.eclipse.persistence
@@ -80,7 +80,7 @@
- 2.0.11
+ 2.0.11
-
\ No newline at end of file
+
diff --git a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
similarity index 97%
rename from apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
rename to apache-olingo/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
index 55155732c8..343af93de9 100644
--- a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
+++ b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
@@ -27,11 +27,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-/**
- * ODataJPAServiceFactory implementation for our sample domain
- * @author Philippe
- *
- */
@Component
public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
@@ -44,7 +39,7 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
/**
* This method will be called by Olingo on every request to
- * initialize the ODataJPAContext that will be used.
+ * initialize the ODataJPAContext that will be used.
*/
@Override
public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
@@ -54,14 +49,14 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
ODataContext octx = ctx.getODataContext();
HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
EntityManager em = (EntityManager)request.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
-
+
// Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig)
ctx.setEntityManager(new EntityManagerWrapper(em));
ctx.setPersistenceUnitName("default");
-
+
// We're managing the EM's lifecycle, so we must inform Olingo that it should not
// try to manage transactions and/or persistence sessions
- ctx.setContainerManaged(true);
+ ctx.setContainerManaged(true);
return ctx;
}
diff --git a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java
similarity index 89%
rename from apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java
rename to apache-olingo/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java
index 02e5ce5adf..f300f552fe 100644
--- a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java
+++ b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/JerseyConfig.java
@@ -1,6 +1,12 @@
- package com.baeldung.examples.olingo2;
+package com.baeldung.examples.olingo2;
-import java.io.IOException;
+import org.apache.olingo.odata2.api.ODataServiceFactory;
+import org.apache.olingo.odata2.core.rest.ODataRootLocator;
+import org.apache.olingo.odata2.core.rest.app.ODataApplication;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
@@ -15,28 +21,15 @@ import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
-import org.apache.olingo.odata2.api.ODataServiceFactory;
-import org.apache.olingo.odata2.core.rest.ODataRootLocator;
-import org.apache.olingo.odata2.core.rest.app.ODataApplication;
-import org.glassfish.jersey.server.ResourceConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
-/**
- * Jersey JAX-RS configuration
- * @author Philippe
- *
- */
@Component
@ApplicationPath("/odata")
public class JerseyConfig extends ResourceConfig {
-
-
- public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
-
+
+
+ public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
+
ODataApplication app = new ODataApplication();
-
+
app
.getClasses()
.forEach( c -> {
@@ -46,11 +39,11 @@ public class JerseyConfig extends ResourceConfig {
register(c);
}
});
-
- register(new CarsRootLocator(serviceFactory));
+
+ register(new CarsRootLocator(serviceFactory));
register( new EntityManagerFilter(emf));
}
-
+
/**
* This filter handles the EntityManager transaction lifecycle.
* @author Philippe
@@ -72,7 +65,7 @@ public class JerseyConfig extends ResourceConfig {
}
@Override
- public void filter(ContainerRequestContext ctx) throws IOException {
+ public void filter(ContainerRequestContext ctx) {
log.info("[I60] >>> filter");
EntityManager em = this.emf.createEntityManager();
httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em);
@@ -85,7 +78,7 @@ public class JerseyConfig extends ResourceConfig {
}
@Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
log.info("[I68] <<< filter");
EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);
diff --git a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java
similarity index 88%
rename from apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java
rename to apache-olingo/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java
index f76e0e00e3..7210f4c812 100644
--- a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java
+++ b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/Olingo2SampleApplication.java
@@ -7,7 +7,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
@SpringBootApplication
public class Olingo2SampleApplication extends SpringBootServletInitializer {
- public static void main(String[] args) {
+ public static void main(String[] args) {
SpringApplication.run(Olingo2SampleApplication.class);
}
}
diff --git a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java
similarity index 100%
rename from apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java
rename to apache-olingo/src/main/java/com/baeldung/examples/olingo2/domain/CarMaker.java
diff --git a/apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java
similarity index 100%
rename from apache-olingo/olingo2/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java
rename to apache-olingo/src/main/java/com/baeldung/examples/olingo2/domain/CarModel.java
diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/src/main/resources/application.yml
similarity index 100%
rename from apache-olingo/olingo2/src/main/resources/application.yml
rename to apache-olingo/src/main/resources/application.yml
diff --git a/apache-olingo/olingo2/src/main/resources/data.sql b/apache-olingo/src/main/resources/data.sql
similarity index 100%
rename from apache-olingo/olingo2/src/main/resources/data.sql
rename to apache-olingo/src/main/resources/data.sql
diff --git a/apache-olingo/olingo2/src/main/resources/logback.xml b/apache-olingo/src/main/resources/logback.xml
similarity index 100%
rename from apache-olingo/olingo2/src/main/resources/logback.xml
rename to apache-olingo/src/main/resources/logback.xml
diff --git a/apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java b/apache-olingo/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationIntegrationTest.java
similarity index 84%
rename from apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java
rename to apache-olingo/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationIntegrationTest.java
index 74033a49cd..402c288673 100644
--- a/apache-olingo/olingo2/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java
+++ b/apache-olingo/src/test/java/com/baeldung/examples/olingo2/Olingo2SampleApplicationIntegrationTest.java
@@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
-public class Olingo2SampleApplicationUnitTest {
+public class Olingo2SampleApplicationIntegrationTest {
@Test
public void contextLoads() {
diff --git a/apache-olingo/olingo2/src/test/resources/logback-test.xml b/apache-olingo/src/test/resources/logback-test.xml
similarity index 100%
rename from apache-olingo/olingo2/src/test/resources/logback-test.xml
rename to apache-olingo/src/test/resources/logback-test.xml
diff --git a/apache-olingo/olingo2/src/test/resources/olingo2-queries.json b/apache-olingo/src/test/resources/olingo2-queries.json
similarity index 100%
rename from apache-olingo/olingo2/src/test/resources/olingo2-queries.json
rename to apache-olingo/src/test/resources/olingo2-queries.json
diff --git a/pom.xml b/pom.xml
index f2a230357c..f5378f9961 100644
--- a/pom.xml
+++ b/pom.xml
@@ -353,7 +353,7 @@
apache-cxf
apache-kafka
apache-libraries
- apache-olingo/olingo2
+ apache-olingo
apache-poi
apache-rocketmq
apache-shiro
@@ -839,7 +839,7 @@
apache-cxf
apache-kafka
apache-libraries
- apache-olingo/olingo2
+ apache-olingo
apache-poi
apache-rocketmq
apache-shiro
From a61eb46b22847c6ea65d710bf38b2d8d158d08b1 Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Fri, 4 Feb 2022 11:46:52 +0100
Subject: [PATCH 070/235] JAVA-9840: Keep spring-data-jpa-filtering on Spring
Boot 2.6.1
---
persistence-modules/spring-data-jpa-filtering/pom.xml | 1 +
1 file changed, 1 insertion(+)
diff --git a/persistence-modules/spring-data-jpa-filtering/pom.xml b/persistence-modules/spring-data-jpa-filtering/pom.xml
index 287a3136fd..9c10f4a997 100644
--- a/persistence-modules/spring-data-jpa-filtering/pom.xml
+++ b/persistence-modules/spring-data-jpa-filtering/pom.xml
@@ -67,6 +67,7 @@
com.baeldung.boot.Application
1.10.6
42.2.5
+ 2.6.1
\ No newline at end of file
From aa92bde665516985e29f9ee7d96d9855f55827ce Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Fri, 4 Feb 2022 19:08:59 +0530
Subject: [PATCH 071/235] JAVA-7535 Moved ebook specific code snippets to
maven-simple module
---
maven-modules/maven-dependency/pom.xml | 38 --------
maven-modules/maven-profiles/pom.xml | 96 -------------------
.../maven-dependency/README.md | 0
.../maven-simple/maven-dependency/pom.xml | 37 +++++++
.../src/main/java/com/baeldung/Main.java | 0
.../maven-profiles/README.md | 0
.../maven-simple/maven-profiles/pom.xml | 96 +++++++++++++++++++
.../plugin-management/README.md | 0
.../maven-simple/plugin-management/pom.xml | 63 ++++++++++++
.../plugin-management/submodule-1/pom.xml | 0
.../submodule-1/src/resources/include.json | 0
.../CopiesAdditionalResourcesUnitTest.java | 0
.../plugin-management/submodule-2/pom.xml | 0
maven-modules/maven-simple/pom.xml | 22 +++++
maven-modules/plugin-management/pom.xml | 64 -------------
maven-modules/pom.xml | 4 +-
16 files changed, 219 insertions(+), 201 deletions(-)
delete mode 100644 maven-modules/maven-dependency/pom.xml
delete mode 100644 maven-modules/maven-profiles/pom.xml
rename maven-modules/{ => maven-simple}/maven-dependency/README.md (100%)
create mode 100644 maven-modules/maven-simple/maven-dependency/pom.xml
rename maven-modules/{ => maven-simple}/maven-dependency/src/main/java/com/baeldung/Main.java (100%)
rename maven-modules/{ => maven-simple}/maven-profiles/README.md (100%)
create mode 100644 maven-modules/maven-simple/maven-profiles/pom.xml
rename maven-modules/{ => maven-simple}/plugin-management/README.md (100%)
create mode 100644 maven-modules/maven-simple/plugin-management/pom.xml
rename maven-modules/{ => maven-simple}/plugin-management/submodule-1/pom.xml (100%)
rename maven-modules/{ => maven-simple}/plugin-management/submodule-1/src/resources/include.json (100%)
rename maven-modules/{ => maven-simple}/plugin-management/submodule-1/src/test/java/com/baeldung/CopiesAdditionalResourcesUnitTest.java (100%)
rename maven-modules/{ => maven-simple}/plugin-management/submodule-2/pom.xml (100%)
create mode 100644 maven-modules/maven-simple/pom.xml
delete mode 100644 maven-modules/plugin-management/pom.xml
diff --git a/maven-modules/maven-dependency/pom.xml b/maven-modules/maven-dependency/pom.xml
deleted file mode 100644
index f17998c327..0000000000
--- a/maven-modules/maven-dependency/pom.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-
-
- 4.0.0
- com.baeldung
- maven-dependency
- 1.0.0-SNAPSHOT
- pom
-
-
- com.baeldung
- maven-modules
- 0.0.1-SNAPSHOT
-
-
-
-
-
- org.apache.commons
- commons-lang3
- 3.12.0
-
-
-
-
-
-
- org.junit.vintage
- junit-vintage-engine
-
-
- org.apache.commons
- commons-lang3
-
-
-
-
\ No newline at end of file
diff --git a/maven-modules/maven-profiles/pom.xml b/maven-modules/maven-profiles/pom.xml
deleted file mode 100644
index 322dada104..0000000000
--- a/maven-modules/maven-profiles/pom.xml
+++ /dev/null
@@ -1,96 +0,0 @@
-
-
- 4.0.0
- com.baeldung
- maven-profiles
- 0.0.1-SNAPSHOT
- maven-profiles
-
-
-
- no-tests
-
- true
-
-
-
- integration-tests
-
- true
-
-
-
- mutation-tests
-
-
- active-on-jdk-11
-
- 11
-
-
-
- active-on-windows-10
-
-
- windows 10
- Windows
- amd64
- 10.0
-
-
-
-
- active-on-property-environment
-
-
- environment
- !test
-
-
-
-
- active-on-missing-file
-
-
- target/testreport.html
-
-
-
-
- active-on-present-file
-
-
- target/artifact.jar
-
-
-
-
- show-active-profiles
-
-
-
- org.apache.maven.plugins
- maven-help-plugin
- ${help.plugin.version}
-
-
- show-profiles
- compile
-
- active-profiles
-
-
-
-
-
-
-
-
-
-
- 3.2.0
-
-
-
\ No newline at end of file
diff --git a/maven-modules/maven-dependency/README.md b/maven-modules/maven-simple/maven-dependency/README.md
similarity index 100%
rename from maven-modules/maven-dependency/README.md
rename to maven-modules/maven-simple/maven-dependency/README.md
diff --git a/maven-modules/maven-simple/maven-dependency/pom.xml b/maven-modules/maven-simple/maven-dependency/pom.xml
new file mode 100644
index 0000000000..46c59409ef
--- /dev/null
+++ b/maven-modules/maven-simple/maven-dependency/pom.xml
@@ -0,0 +1,37 @@
+
+
+ 4.0.0
+ maven-dependency
+ 1.0.0-SNAPSHOT
+ pom
+
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ 3.12.0
+
+
+
+
+
+
+ org.junit.vintage
+ junit-vintage-engine
+
+
+ org.apache.commons
+ commons-lang3
+
+
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-dependency/src/main/java/com/baeldung/Main.java b/maven-modules/maven-simple/maven-dependency/src/main/java/com/baeldung/Main.java
similarity index 100%
rename from maven-modules/maven-dependency/src/main/java/com/baeldung/Main.java
rename to maven-modules/maven-simple/maven-dependency/src/main/java/com/baeldung/Main.java
diff --git a/maven-modules/maven-profiles/README.md b/maven-modules/maven-simple/maven-profiles/README.md
similarity index 100%
rename from maven-modules/maven-profiles/README.md
rename to maven-modules/maven-simple/maven-profiles/README.md
diff --git a/maven-modules/maven-simple/maven-profiles/pom.xml b/maven-modules/maven-simple/maven-profiles/pom.xml
new file mode 100644
index 0000000000..1168350de9
--- /dev/null
+++ b/maven-modules/maven-simple/maven-profiles/pom.xml
@@ -0,0 +1,96 @@
+
+
+ 4.0.0
+ com.baeldung
+ maven-profiles
+ 0.0.1-SNAPSHOT
+ maven-profiles
+
+
+
+ no-tests
+
+ true
+
+
+
+ integration-tests
+
+ true
+
+
+
+ mutation-tests
+
+
+ active-on-jdk-11
+
+ 11
+
+
+
+ active-on-windows-10
+
+
+ windows 10
+ Windows
+ amd64
+ 10.0
+
+
+
+
+ active-on-property-environment
+
+
+ environment
+ !test
+
+
+
+
+ active-on-missing-file
+
+
+ target/testreport.html
+
+
+
+
+ active-on-present-file
+
+
+ target/artifact.jar
+
+
+
+
+ show-active-profiles
+
+
+
+ org.apache.maven.plugins
+ maven-help-plugin
+ ${help.plugin.version}
+
+
+ show-profiles
+ compile
+
+ active-profiles
+
+
+
+
+
+
+
+
+
+
+ 3.2.0
+
+
+
\ No newline at end of file
diff --git a/maven-modules/plugin-management/README.md b/maven-modules/maven-simple/plugin-management/README.md
similarity index 100%
rename from maven-modules/plugin-management/README.md
rename to maven-modules/maven-simple/plugin-management/README.md
diff --git a/maven-modules/maven-simple/plugin-management/pom.xml b/maven-modules/maven-simple/plugin-management/pom.xml
new file mode 100644
index 0000000000..b680d1d39b
--- /dev/null
+++ b/maven-modules/maven-simple/plugin-management/pom.xml
@@ -0,0 +1,63 @@
+
+
+ 4.0.0
+ plugin-management
+ pom
+
+
+ maven-modules
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+
+
+ submodule-1
+ submodule-2
+
+
+
+
+
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ ${maven.bulid.helper.plugin}
+
+
+ add-resource
+ generate-resources
+
+ add-resource
+
+
+
+
+ src/resources
+ json
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.plugin}
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+ 3.8.1
+ 3.2.0
+
+
+
\ No newline at end of file
diff --git a/maven-modules/plugin-management/submodule-1/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-1/pom.xml
similarity index 100%
rename from maven-modules/plugin-management/submodule-1/pom.xml
rename to maven-modules/maven-simple/plugin-management/submodule-1/pom.xml
diff --git a/maven-modules/plugin-management/submodule-1/src/resources/include.json b/maven-modules/maven-simple/plugin-management/submodule-1/src/resources/include.json
similarity index 100%
rename from maven-modules/plugin-management/submodule-1/src/resources/include.json
rename to maven-modules/maven-simple/plugin-management/submodule-1/src/resources/include.json
diff --git a/maven-modules/plugin-management/submodule-1/src/test/java/com/baeldung/CopiesAdditionalResourcesUnitTest.java b/maven-modules/maven-simple/plugin-management/submodule-1/src/test/java/com/baeldung/CopiesAdditionalResourcesUnitTest.java
similarity index 100%
rename from maven-modules/plugin-management/submodule-1/src/test/java/com/baeldung/CopiesAdditionalResourcesUnitTest.java
rename to maven-modules/maven-simple/plugin-management/submodule-1/src/test/java/com/baeldung/CopiesAdditionalResourcesUnitTest.java
diff --git a/maven-modules/plugin-management/submodule-2/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
similarity index 100%
rename from maven-modules/plugin-management/submodule-2/pom.xml
rename to maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml
new file mode 100644
index 0000000000..87df6a9bca
--- /dev/null
+++ b/maven-modules/maven-simple/pom.xml
@@ -0,0 +1,22 @@
+
+
+ 4.0.0
+ maven-simple
+ maven-simple
+ pom
+
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ maven-profiles
+ plugin-management
+ maven-dependency
+
+
+
diff --git a/maven-modules/plugin-management/pom.xml b/maven-modules/plugin-management/pom.xml
deleted file mode 100644
index cd75e5dbd0..0000000000
--- a/maven-modules/plugin-management/pom.xml
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
- 4.0.0
- plugin-management
- 0.0.1-SNAPSHOT
- pom
-
-
- maven-modules
- com.baeldung
- 0.0.1-SNAPSHOT
-
-
-
- submodule-1
- submodule-2
-
-
-
-
-
-
- org.codehaus.mojo
- build-helper-maven-plugin
- ${maven.bulid.helper.plugin}
-
-
- add-resource
- generate-resources
-
- add-resource
-
-
-
-
- src/resources
- json
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven.compiler.plugin}
-
- 1.8
- 1.8
-
-
-
-
-
-
-
- 3.8.1
- 3.2.0
-
-
-
\ No newline at end of file
diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml
index e09283efb4..21bc0e72e1 100644
--- a/maven-modules/pom.xml
+++ b/maven-modules/pom.xml
@@ -22,7 +22,6 @@
maven-integration-test
maven-multi-source
maven-plugins
- maven-profiles
maven-properties
maven-unused-dependencies
@@ -34,10 +33,9 @@
maven-printing-plugins
maven-builder-plugin
host-maven-repo-example
- plugin-management
maven-surefire-plugin
maven-parent-pom-resolution
- maven-dependency
+ maven-simple
From 9a8d9227b752dc5ea2e182d6eafc2f0f5f52c9c2 Mon Sep 17 00:00:00 2001
From: Ralf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com>
Date: Fri, 4 Feb 2022 17:58:16 +0100
Subject: [PATCH 072/235] BAEL-5323: Spring Boot with multiple data sources
(#11741)
* BAEL-5323: Spring Boot with multiple data sources
* BAEL-5323: small fixes
* BAEL-5323: fix test class
* BAEL-5323: Refactor configuration classes
* BAEL-5323: Set proeprty to private
* BAEL-5323: rename test class to follow naming conventions
---
spring-boot-modules/pom.xml | 1 +
.../.gitignore | 1 +
.../spring-boot-multiple-datasources/pom.xml | 58 +++++++++++++++++++
.../MultipleDatasourcesApplication.java | 13 +++++
.../spring/datasources/todos/Todo.java | 48 +++++++++++++++
.../todos/TodoDatasourceConfiguration.java | 28 +++++++++
.../todos/TodoJpaConfiguration.java | 40 +++++++++++++
.../datasources/todos/TodoRepository.java | 6 ++
.../spring/datasources/topics/Topic.java | 39 +++++++++++++
.../topics/TopicDatasourceConfiguration.java | 26 +++++++++
.../topics/TopicJpaConfiguration.java | 41 +++++++++++++
.../datasources/topics/TopicRepository.java | 6 ++
.../src/main/resources/application.yml | 23 ++++++++
.../MultipleDatasourcesIntegrationTest.java | 39 +++++++++++++
14 files changed, 369 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/.gitignore
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/pom.xml
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/MultipleDatasourcesApplication.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/Todo.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoDatasourceConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoJpaConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoRepository.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/Topic.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicDatasourceConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicJpaConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicRepository.java
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/main/resources/application.yml
create mode 100644 spring-boot-modules/spring-boot-multiple-datasources/src/test/java/com/baeldung/spring/datasources/MultipleDatasourcesIntegrationTest.java
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index ac0deaa9e5..4925530a35 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -52,6 +52,7 @@
spring-boot-libraries
spring-boot-libraries-2
spring-boot-logging-log4j2
+ spring-boot-multiple-datasources
spring-boot-mvc
spring-boot-mvc-2
spring-boot-mvc-3
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/.gitignore b/spring-boot-modules/spring-boot-multiple-datasources/.gitignore
new file mode 100644
index 0000000000..87a3fce287
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/.gitignore
@@ -0,0 +1 @@
+.local-db
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/pom.xml b/spring-boot-modules/spring-boot-multiple-datasources/pom.xml
new file mode 100644
index 0000000000..d66095bc2c
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/pom.xml
@@ -0,0 +1,58 @@
+
+
+ 4.0.0
+ spring-boot-multiple-datasources
+ 0.1.0-SNAPSHOT
+ spring-boot-multiple-datasources
+ jar
+ Module For Spring Boot With Multiple Datasources
+
+
+ com.baeldung.spring-boot-modules
+ spring-boot-modules
+ 1.0.0-SNAPSHOT
+ ../pom.xml
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ com.h2database
+ h2
+ provided
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ runtime
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+ 2.6.3
+
+
+
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/MultipleDatasourcesApplication.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/MultipleDatasourcesApplication.java
new file mode 100644
index 0000000000..efdff387df
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/MultipleDatasourcesApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.spring.datasources;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class MultipleDatasourcesApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(MultipleDatasourcesApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/Todo.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/Todo.java
new file mode 100644
index 0000000000..6f8557e258
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/Todo.java
@@ -0,0 +1,48 @@
+package com.baeldung.spring.datasources.todos;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Todo {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ private String title;
+ private boolean completed;
+
+ public Todo() {
+ }
+
+ public Todo(String title) {
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public boolean isCompleted() {
+ return completed;
+ }
+
+ public void setCompleted(boolean completed) {
+ this.completed = completed;
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoDatasourceConfiguration.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoDatasourceConfiguration.java
new file mode 100644
index 0000000000..3bfc8e2855
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoDatasourceConfiguration.java
@@ -0,0 +1,28 @@
+package com.baeldung.spring.datasources.todos;
+
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class TodoDatasourceConfiguration {
+
+ @Bean
+ @ConfigurationProperties("spring.datasource.todos")
+ public DataSourceProperties todosDataSourceProperties() {
+ return new DataSourceProperties();
+ }
+
+ @Bean
+ @Primary
+ public DataSource todosDataSource() {
+ return todosDataSourceProperties()
+ .initializeDataSourceBuilder()
+ .build();
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoJpaConfiguration.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoJpaConfiguration.java
new file mode 100644
index 0000000000..655a3a55c2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoJpaConfiguration.java
@@ -0,0 +1,40 @@
+package com.baeldung.spring.datasources.todos;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Objects;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(
+ basePackageClasses = Todo.class,
+ entityManagerFactoryRef = "todosEntityManagerFactory",
+ transactionManagerRef = "todosTransactionManager"
+)
+public class TodoJpaConfiguration {
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean todosEntityManagerFactory(
+ @Qualifier("todosDataSource") DataSource dataSource,
+ EntityManagerFactoryBuilder builder) {
+ return builder
+ .dataSource(dataSource)
+ .packages(Todo.class)
+ .build();
+ }
+
+ @Bean
+ public PlatformTransactionManager todosTransactionManager(
+ @Qualifier("todosEntityManagerFactory") LocalContainerEntityManagerFactoryBean todosEntityManagerFactory) {
+ return new JpaTransactionManager(Objects.requireNonNull(todosEntityManagerFactory.getObject()));
+ }
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoRepository.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoRepository.java
new file mode 100644
index 0000000000..09fb8c6500
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/todos/TodoRepository.java
@@ -0,0 +1,6 @@
+package com.baeldung.spring.datasources.todos;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface TodoRepository extends JpaRepository {
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/Topic.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/Topic.java
new file mode 100644
index 0000000000..1d1f20f111
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/Topic.java
@@ -0,0 +1,39 @@
+package com.baeldung.spring.datasources.topics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Topic {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ private String title;
+
+ public Topic() {
+ }
+
+ public Topic(String title) {
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicDatasourceConfiguration.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicDatasourceConfiguration.java
new file mode 100644
index 0000000000..a06983d681
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicDatasourceConfiguration.java
@@ -0,0 +1,26 @@
+package com.baeldung.spring.datasources.topics;
+
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class TopicDatasourceConfiguration {
+
+ @Bean
+ @ConfigurationProperties("spring.datasource.topics")
+ public DataSourceProperties topicsDataSourceProperties() {
+ return new DataSourceProperties();
+ }
+
+ @Bean
+ public DataSource topicsDataSource() {
+ return topicsDataSourceProperties()
+ .initializeDataSourceBuilder()
+ .build();
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicJpaConfiguration.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicJpaConfiguration.java
new file mode 100644
index 0000000000..d800813b8c
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicJpaConfiguration.java
@@ -0,0 +1,41 @@
+package com.baeldung.spring.datasources.topics;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Objects;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(
+ basePackageClasses = Topic.class,
+ entityManagerFactoryRef = "topicsEntityManagerFactory",
+ transactionManagerRef = "topicsTransactionManager"
+)
+public class TopicJpaConfiguration {
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory(
+ @Qualifier("topicsDataSource") DataSource dataSource,
+ EntityManagerFactoryBuilder builder
+ ) {
+ return builder
+ .dataSource(dataSource)
+ .packages(Topic.class)
+ .build();
+ }
+
+ @Bean
+ public PlatformTransactionManager topicsTransactionManager(
+ @Qualifier("topicsEntityManagerFactory") LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory) {
+ return new JpaTransactionManager(Objects.requireNonNull(topicsEntityManagerFactory.getObject()));
+ }
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicRepository.java b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicRepository.java
new file mode 100644
index 0000000000..499b72650a
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/java/com/baeldung/spring/datasources/topics/TopicRepository.java
@@ -0,0 +1,6 @@
+package com.baeldung.spring.datasources.topics;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface TopicRepository extends JpaRepository {
+}
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/main/resources/application.yml b/spring-boot-modules/spring-boot-multiple-datasources/src/main/resources/application.yml
new file mode 100644
index 0000000000..4754acfc0f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/main/resources/application.yml
@@ -0,0 +1,23 @@
+spring:
+ datasource:
+ todos:
+ url: jdbc:h2:./.local-db/todos;DB_CLOSE_DELAY=-1;MODE=DB2;AUTO_SERVER=TRUE
+ username: sa
+ password: null
+ driverClassName: org.h2.Driver
+ topics:
+ url: jdbc:h2:./.local-db/topics;DB_CLOSE_DELAY=-1;MODE=DB2;AUTO_SERVER=TRUE
+ username: sa
+ password: null
+ driverClassName: org.h2.Driver
+ h2:
+ console:
+ enabled: true
+ path: /h2-console
+ jpa:
+ generate-ddl: true
+ hibernate:
+ ddl-auto: update
+ properties:
+ hibernate:
+ dialect: org.hibernate.dialect.H2Dialect
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/src/test/java/com/baeldung/spring/datasources/MultipleDatasourcesIntegrationTest.java b/spring-boot-modules/spring-boot-multiple-datasources/src/test/java/com/baeldung/spring/datasources/MultipleDatasourcesIntegrationTest.java
new file mode 100644
index 0000000000..397992f6c8
--- /dev/null
+++ b/spring-boot-modules/spring-boot-multiple-datasources/src/test/java/com/baeldung/spring/datasources/MultipleDatasourcesIntegrationTest.java
@@ -0,0 +1,39 @@
+package com.baeldung.spring.datasources;
+
+import com.baeldung.spring.datasources.todos.Todo;
+import com.baeldung.spring.datasources.todos.TodoRepository;
+import com.baeldung.spring.datasources.topics.Topic;
+import com.baeldung.spring.datasources.topics.TopicRepository;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DataJpaTest // no test database!
+class MultipleDatasourcesIntegrationTest {
+
+ @Autowired
+ TodoRepository todoRepo;
+ @Autowired
+ TopicRepository topicRepo;
+
+ @Test
+ void shouldSaveTodoToTodoDB() {
+ Todo todo = new Todo("test");
+ Todo saved =todoRepo.save(todo);
+ Optional result= todoRepo.findById(saved.getId());
+ assertThat(result).isPresent();
+ }
+
+ @Test
+ void shouldSaveTopicToTopicDB() {
+ Topic todo = new Topic("test");
+ Topic saved =topicRepo.save(todo);
+ Optional result= topicRepo.findById(saved.getId());
+ assertThat(result).isPresent();
+ }
+
+}
From d70d23f8e1ce9d04dd858092f08580b842e852f6 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 4 Feb 2022 11:19:43 +0000
Subject: [PATCH 073/235] [JAVA-9585] Convert Cassandra integration tests to
Live tests
---
.../java/com/baeldung/SpringContextTest.java | 12 ++---
...nTest.java => BookRepositoryLiveTest.java} | 39 ++++++++------
...st.java => CassandraTemplateLiveTest.java} | 51 ++++++++++--------
...ationTest.java => CqlQueriesLiveTest.java} | 54 ++++++++++---------
4 files changed, 84 insertions(+), 72 deletions(-)
rename persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/{BookRepositoryIntegrationTest.java => BookRepositoryLiveTest.java} (92%)
rename persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/{CassandraTemplateIntegrationTest.java => CassandraTemplateLiveTest.java} (93%)
rename persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/{CqlQueriesIntegrationTest.java => CqlQueriesLiveTest.java} (90%)
diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java
index 22bd5c6551..83b7b227b3 100644
--- a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java
+++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/SpringContextTest.java
@@ -32,10 +32,10 @@ public class SpringContextTest {
public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;";
public static final String DATA_TABLE_NAME = "book";
-
+
@Autowired
private CassandraAdminOperations adminTemplate;
-
+
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
@@ -47,14 +47,14 @@ public class SpringContextTest {
}
@Before
- public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
- adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap());
+ public void createTable() {
+ adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
}
-
+
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
-
+
@After
public void dropTable() {
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryLiveTest.java
similarity index 92%
rename from persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java
rename to persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryLiveTest.java
index 55e968d6f2..d5758c3574 100644
--- a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/BookRepositoryLiveTest.java
@@ -1,17 +1,15 @@
package com.baeldung.spring.data.cassandra.repository;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.io.IOException;
-import java.util.HashMap;
-
+import com.baeldung.spring.data.cassandra.config.CassandraConfig;
import com.baeldung.spring.data.cassandra.model.Book;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.utils.UUIDs;
+import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.transport.TTransportException;
-import com.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.After;
import org.junit.AfterClass;
@@ -25,15 +23,24 @@ import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.utils.UUIDs;
-import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.util.HashMap;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+/**
+ * Live test for Cassandra testing.
+ *
+ * This can be converted to IntegrationTest once cassandra-unit tests can be executed in parallel and
+ * multiple test servers started as part of test suite.
+ *
+ * Open cassandra-unit issue for parallel execution: https://github.com/jsevellec/cassandra-unit/issues/155
+ */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
-public class BookRepositoryIntegrationTest {
- private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class);
+public class BookRepositoryLiveTest {
+ private static final Log LOGGER = LogFactory.getLog(BookRepositoryLiveTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@@ -47,8 +54,6 @@ public class BookRepositoryIntegrationTest {
@Autowired
private CassandraAdminOperations adminTemplate;
- //
-
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
@@ -62,8 +67,8 @@ public class BookRepositoryIntegrationTest {
}
@Before
- public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
- adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap());
+ public void createTable() {
+ adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
}
@Test
diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateLiveTest.java
similarity index 93%
rename from persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java
rename to persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateLiveTest.java
index 90ae68ba98..bc05302d13 100644
--- a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java
+++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CassandraTemplateLiveTest.java
@@ -1,17 +1,13 @@
package com.baeldung.spring.data.cassandra.repository;
-import static junit.framework.TestCase.assertNull;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
import com.baeldung.spring.data.cassandra.config.CassandraConfig;
import com.baeldung.spring.data.cassandra.model.Book;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.utils.UUIDs;
+import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -30,17 +26,28 @@ import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.utils.UUIDs;
-import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import static junit.framework.TestCase.assertNull;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Live test for Cassandra testing.
+ *
+ * This can be converted to IntegrationTest once cassandra-unit tests can be executed in parallel and
+ * multiple test servers started as part of test suite.
+ *
+ * Open cassandra-unit issue for parallel execution: https://github.com/jsevellec/cassandra-unit/issues/155
+ */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
-public class CassandraTemplateIntegrationTest {
- private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class);
+public class CassandraTemplateLiveTest {
+ private static final Log LOGGER = LogFactory.getLog(CassandraTemplateLiveTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@@ -54,8 +61,6 @@ public class CassandraTemplateIntegrationTest {
@Autowired
private CassandraOperations cassandraTemplate;
- //
-
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
@@ -69,8 +74,8 @@ public class CassandraTemplateIntegrationTest {
}
@Before
- public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
- adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap());
+ public void createTable() {
+ adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
}
@Test
@@ -111,7 +116,7 @@ public class CassandraTemplateIntegrationTest {
}
@Test
- public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException {
+ public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() {
final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook);
cassandraTemplate.delete(javaBook);
diff --git a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesLiveTest.java
similarity index 90%
rename from persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java
rename to persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesLiveTest.java
index f948218807..e1c67a1724 100644
--- a/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java
+++ b/persistence-modules/spring-data-cassandra/src/test/java/com/baeldung/spring/data/cassandra/repository/CqlQueriesLiveTest.java
@@ -1,19 +1,16 @@
package com.baeldung.spring.data.cassandra.repository;
-import static junit.framework.TestCase.assertEquals;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.cassandra.exceptions.ConfigurationException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.thrift.transport.TTransportException;
import com.baeldung.spring.data.cassandra.config.CassandraConfig;
import com.baeldung.spring.data.cassandra.model.Book;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.querybuilder.Insert;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.utils.UUIDs;
+import com.google.common.collect.ImmutableSet;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.After;
import org.junit.AfterClass;
@@ -28,18 +25,25 @@ import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.querybuilder.Insert;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.utils.UUIDs;
-import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.UUID;
+import static junit.framework.TestCase.assertEquals;
+
+/**
+ * Live test for Cassandra testing.
+ *
+ * This can be converted to IntegrationTest once cassandra-unit tests can be executed in parallel and
+ * multiple test servers started as part of test suite.
+ *
+ * Open cassandra-unit issue for parallel execution: https://github.com/jsevellec/cassandra-unit/issues/155
+ */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
-public class CqlQueriesIntegrationTest {
- private static final Log LOGGER = LogFactory.getLog(CqlQueriesIntegrationTest.class);
+public class CqlQueriesLiveTest {
+ private static final Log LOGGER = LogFactory.getLog(CqlQueriesLiveTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@@ -53,10 +57,8 @@ public class CqlQueriesIntegrationTest {
@Autowired
private CassandraOperations cassandraTemplate;
- //
-
@BeforeClass
- public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
+ public static void startCassandraEmbedded() throws Exception {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000);
final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
LOGGER.info("Server Started at 127.0.0.1:9142... ");
@@ -68,8 +70,8 @@ public class CqlQueriesIntegrationTest {
}
@Before
- public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
- adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap());
+ public void createTable() {
+ adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
}
@Test
From d2332a5c1096d0fcfd0c853c59cc58f5389ad4a5 Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Sat, 5 Feb 2022 11:52:40 +0530
Subject: [PATCH 074/235] BAEL-5351: Added empty map initialization methods in
Java
---
.../map/initialize/EmptyMapInitializer.java | 49 +++++++++++++++++++
1 file changed, 49 insertions(+)
create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
new file mode 100644
index 0000000000..bef6fa5374
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
@@ -0,0 +1,49 @@
+package com.baeldung.map.initialize;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+public class EmptyMapInitializer {
+
+ public static Map articleMap;
+ static {
+ articleMap = new HashMap<>();
+ }
+
+ public static Map createEmptyMap() {
+ return Collections.emptyMap();
+ }
+
+ public void createMapUsingConstructors() {
+ Map hashMap = new HashMap();
+ Map linkedHashMap = new LinkedHashMap();
+ Map treeMap = new TreeMap();
+ }
+
+ public Map createEmptyMapUsingMapsObject() {
+ Map emptyMap = Maps.newHashMap();
+ return emptyMap;
+ }
+
+ public Map createGenericEmptyMapUsingMapsObject() {
+ return Maps.newHashMap();
+ }
+
+ public static Map createMapUsingGuava() {
+ Map emptyMapUsingGuava =
+ Maps.newHashMap(ImmutableMap.of());
+ return emptyMapUsingGuava;
+ }
+
+ public NavigableMap createEmptyNavigableMap() {
+ NavigableMap navigableMap = Collections.emptyNavigableMap();
+ return navigableMap;
+ }
+
+}
From 2e8381fbd7be33938bf2b0f4c14aee8bd232524e Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Sat, 5 Feb 2022 11:53:37 +0530
Subject: [PATCH 075/235] BAEL-5351: Added unit tests for empty map methods
---
.../initialize/EmptyMapInitializerTest.java | 30 +++++++++++++++++++
1 file changed, 30 insertions(+)
create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java
diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java
new file mode 100644
index 0000000000..07605cdd45
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.map.initialize;
+
+import java.util.Map;
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class EmptyMapInitializerTest {
+
+ @Test(expected=UnsupportedOperationException.class)
+ public void givenEmptyMap_whenAddingEntries_throwsException() {
+ Map map = EmptyMapInitializer.createEmptyMap();
+ map.put("key", "value");
+ }
+
+ @Test
+ public void checkStaticMap_isEmpty() {
+ assertTrue(EmptyMapInitializer.articleMap.isEmpty());
+ }
+
+ @Test
+ public void emptyMapCreated_usingGuava() {
+ Map emptyMapUsingGuava = EmptyMapInitializer.createMapUsingGuava();
+ assertTrue(emptyMapUsingGuava.isEmpty());
+ emptyMapUsingGuava.put("key", "value");
+ assertFalse(emptyMapUsingGuava.isEmpty());
+ }
+
+}
From 7f88e21e92cb60ff14efc637f14cee0ca06c4ea1 Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Sat, 5 Feb 2022 11:56:54 +0530
Subject: [PATCH 076/235] BAEKL-5351: Added method for empty sorted map
---
.../com/baeldung/map/initialize/EmptyMapInitializer.java | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
index bef6fa5374..06185a0f93 100644
--- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
+++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
@@ -7,6 +7,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NavigableMap;
+import java.util.SortedMap;
import java.util.TreeMap;
public class EmptyMapInitializer {
@@ -41,6 +42,11 @@ public class EmptyMapInitializer {
return emptyMapUsingGuava;
}
+ public SortedMap createEmptySortedMap() {
+ SortedMap sortedMap = Collections.emptySortedMap();
+ return sortedMap;
+ }
+
public NavigableMap createEmptyNavigableMap() {
NavigableMap navigableMap = Collections.emptyNavigableMap();
return navigableMap;
From 54f43a311a223c7e529ad372a2bd4fa9d891d99a Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Sat, 5 Feb 2022 12:03:34 +0530
Subject: [PATCH 077/235] BAEL-5351: Resolved PMD violations by renaming file
---
...MapInitializerTest.java => EmptyMapInitializerUnitTest.java} | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/{EmptyMapInitializerTest.java => EmptyMapInitializerUnitTest.java} (95%)
diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
similarity index 95%
rename from core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java
rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
index 07605cdd45..82225a46ec 100644
--- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java
+++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-public class EmptyMapInitializerTest {
+public class EmptyMapInitializerUnitTest {
@Test(expected=UnsupportedOperationException.class)
public void givenEmptyMap_whenAddingEntries_throwsException() {
From b97323ea902e5cae9360a1b177b921d8084534d9 Mon Sep 17 00:00:00 2001
From: Jose Vinicius <42288345+josephdsbr@users.noreply.github.com>
Date: Sat, 5 Feb 2022 16:22:16 -0300
Subject: [PATCH 078/235] BAEL-5124 - Adding a module with examples of printing
thread info in the log file using log4j (#11704)
* adding a example module for printing thread info in log file using log4j
* - fix: removing submodule
* - fix: Adding submodule
* - fix: Removing `.gitignore`, `README.md`, and `application.properties`.
- fix: Removing Spring boot and adding log4j2 from Maven Central
* - fix: Changing module name as suggested to log4j2-thread-info.
- fix: Fixing log path in log4j2 configuration
* - feat: Removing log4j2-thread-info module
- feat: Adding example code into existing log4j2 module
* - fix: Removing unnecessary logging
* - fix: Separating thread info in the logging pattern
* - fix: package name to lowercase
* lowercasing package name and variable name
* changing package name in configuration
* - fix: formatting
* - fix: formatting imports
---
.../log4j2threadinfo/Log4j2ThreadInfo.java | 18 +++++++++++
.../log4j2/src/main/resources/log4j2.xml | 30 +++++++++++++++++++
2 files changed, 48 insertions(+)
create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2threadinfo/Log4j2ThreadInfo.java
create mode 100644 logging-modules/log4j2/src/main/resources/log4j2.xml
diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2threadinfo/Log4j2ThreadInfo.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2threadinfo/Log4j2ThreadInfo.java
new file mode 100644
index 0000000000..2c9b8870e2
--- /dev/null
+++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2threadinfo/Log4j2ThreadInfo.java
@@ -0,0 +1,18 @@
+package com.baeldung.logging.log4j2threadinfo;
+
+import java.util.stream.IntStream;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+public class Log4j2ThreadInfo {
+ private static final Logger logger = LogManager.getLogger(Log4j2ThreadInfo.class);
+
+ public static void main(String[] args) {
+ IntStream.range(0, 5).forEach(i -> {
+ Runnable runnable = () -> logger.info("Logging info");
+ Thread thread = new Thread(runnable);
+ thread.start();
+ });
+ }
+}
diff --git a/logging-modules/log4j2/src/main/resources/log4j2.xml b/logging-modules/log4j2/src/main/resources/log4j2.xml
new file mode 100644
index 0000000000..6c0bc75a94
--- /dev/null
+++ b/logging-modules/log4j2/src/main/resources/log4j2.xml
@@ -0,0 +1,30 @@
+
+
+
+
+ %d{yyyy-MM-dd HH:mm:ss.SSS} --- thread_id="%tid" thread_name="%tn" thread_priority="%tp" --- [%p] %m%n
+
+
+
+
+
+ ${LOG_PATTERN}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
From 3f46e530e7ff0793a57a67ef6a18753591459d97 Mon Sep 17 00:00:00 2001
From: chrys exaucet
Date: Sat, 5 Feb 2022 21:28:05 +0000
Subject: [PATCH 079/235] BAEL-5123: Annotation Processor for Hibernate
Validator (#11673)
* feat(wip): add Hibernate Validator AP example
* chore: change AP version to 6.2.0.Final
See https://hibernate.atlassian.net/browse/HV-1868
* revert(style): remove unnecessary formatter
See https://github.com/eugenp/tutorials/pull/11673#discussion_r784444016
* fix: remove unauthorised annotation
The AP was triggering a compile time error because the annotation @NotBlank is disallowed for the Profile data type. That's why the CI was failing.
This customer class is unrelated to the article being written.
* fix(style): revert indentation issue
See https://github.com/eugenp/tutorials/pull/11673/files#r788146422
---
javaxval/pom.xml | 35 ++++++-
.../container/validation/Customer.java | 1 -
.../hibernate/validator/ap/Message.java | 95 +++++++++++++++++++
3 files changed, 128 insertions(+), 3 deletions(-)
create mode 100644 javaxval/src/main/java/com/baeldung/javaxval/hibernate/validator/ap/Message.java
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 57369c6f52..7d009f3280 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -15,7 +15,7 @@
- org.hibernate
+ org.hibernate.validator
hibernate-validator
${hibernate-validator.version}
@@ -36,10 +36,41 @@
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+ true
+
+ -Averbose=true
+ -AmethodConstraintsSupported=true
+ -AdiagnosticKind=ERROR
+
+
+
+ org.hibernate.validator
+ hibernate-validator-annotation-processor
+ ${hibernate-validator.ap.version}
+
+
+
+
+
+
+
6.0.13.Final
+ 6.2.0.Final
+ 3.6.1
+ 1.8
+ 1.8
3.0.0
5.0.2.RELEASE
-
\ No newline at end of file
+
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
index 03811635ee..d990647721 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
@@ -20,7 +20,6 @@ public class Customer {
@PositiveOrZero
private OptionalInt numberOfOrders;
- @NotBlank
private Profile profile;
public String getName() {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/hibernate/validator/ap/Message.java b/javaxval/src/main/java/com/baeldung/javaxval/hibernate/validator/ap/Message.java
new file mode 100644
index 0000000000..55d6dafad7
--- /dev/null
+++ b/javaxval/src/main/java/com/baeldung/javaxval/hibernate/validator/ap/Message.java
@@ -0,0 +1,95 @@
+package com.baeldung.javaxval.hibernate.validator.ap;
+
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Past;
+import java.util.List;
+import java.util.Optional;
+
+public class Message {
+
+ @NotNull(message = "Content cannot be null")
+ private String content;
+
+ private boolean isDelivered;
+
+ private List<@NotBlank String> recipients;
+
+ // uncomment in order to trigger AP annotation detection
+ // The annotation @Past is disallowed for this data type.
+ // @Past
+ private String createdAt;
+
+ public String getContent() {
+ return content;
+ }
+
+ public Message(String content, boolean isDelivered, List<@NotBlank String> recipients, String createdAt) {
+ this.content = content;
+ this.isDelivered = isDelivered;
+ this.recipients = recipients;
+ this.createdAt = createdAt;
+ }
+
+ // uncomment in order to trigger AP annotation detection
+ // The annotation @Min is disallowed for the return type of this method.
+ // @Min(3)
+ public boolean broadcast() {
+ // setup a logic
+ // to send to recipients
+ return true;
+ }
+
+ // uncomment in order to trigger AP annotation detection
+ // Void methods may not be annotated with constraint annotations.
+ // @NotNull
+ public void archive() {
+ // archive the message
+ }
+
+ // uncomment in order to trigger AP annotation detection
+ // Constraint annotations must not be specified at methods, which are no valid JavaBeans getter methods.
+ // NOTE: add -AmethodConstraintsSupported=false to compiler args before
+ // @AssertTrue
+ public boolean delete() {
+ // delete the message
+ return false;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public boolean isDelivered() {
+ return isDelivered;
+ }
+
+ public void setDelivered(boolean delivered) {
+ isDelivered = delivered;
+ }
+
+ public List getRecipients() {
+ return recipients;
+ }
+
+ public void setRecipients(List recipients) {
+ this.recipients = recipients;
+ }
+
+ public void setCreatedAt(String createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ public String getName() {
+ return content;
+ }
+
+ public void setName(String content) {
+ this.content = content;
+ }
+
+ public Optional<@Past String> getCreatedAt() {
+ return Optional.ofNullable(createdAt);
+ }
+
+}
From 80c333185156d8138414d3a2910baad11f92acdb Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Sun, 6 Feb 2022 18:31:38 +0000
Subject: [PATCH 080/235] [JAVA-9806] Upgrade Maven Cargo plugin to fix error
---
.../spring-security-web-login/README.md | 11 ++++++++++-
.../spring-security-web-login/pom.xml | 14 +++-----------
.../src/main/java/com/baeldung/AppInitializer.java | 11 +++++------
.../security/CustomAccessDeniedHandler.java | 13 +++++--------
.../CustomAuthenticationFailureHandler.java | 2 +-
.../security/CustomLogoutSuccessHandler.java | 6 ------
.../security/config/SecSecurityConfig.java | 6 +-----
.../baeldung/spring/ChannelSecSecurityConfig.java | 4 ----
.../main/java/com/baeldung/spring/MvcConfig.java | 6 ------
.../baeldung/spring/RedirectionSecurityConfig.java | 4 ----
10 files changed, 25 insertions(+), 52 deletions(-)
diff --git a/spring-security-modules/spring-security-web-login/README.md b/spring-security-modules/spring-security-web-login/README.md
index 9521a430c2..8b9c1583f6 100644
--- a/spring-security-modules/spring-security-web-login/README.md
+++ b/spring-security-modules/spring-security-web-login/README.md
@@ -1,6 +1,6 @@
## Spring Security Login
-This module contains articles about login mechanisms with Spring Security
+This module contains articles about login mechanisms with Spring Security.
### The Course
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
@@ -17,3 +17,12 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
```
mvn clean install
```
+
+### Run the Project
+
+- Run the application using Maven Cargo plugin.
+```
+mvn cargo:run
+```
+- Go to the login page at http://localhost:8082/spring-security-web-login/login.html
+- Login using ```user1/user1Pass``` details.
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-web-login/pom.xml b/spring-security-modules/spring-security-web-login/pom.xml
index ac5393c1a0..3d9947c519 100644
--- a/spring-security-modules/spring-security-web-login/pom.xml
+++ b/spring-security-modules/spring-security-web-login/pom.xml
@@ -137,17 +137,9 @@
org.codehaus.cargo
- cargo-maven2-plugin
- ${cargo-maven2-plugin.version}
+ cargo-maven3-plugin
+ ${cargo-maven3-plugin.version}
- true
-
- jetty8x
- embedded
-
-
-
-
8082
@@ -160,7 +152,7 @@
- 1.6.1
+ 1.9.9
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/AppInitializer.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/AppInitializer.java
index 4f38d190eb..cbdf8dc684 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/AppInitializer.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/AppInitializer.java
@@ -1,9 +1,5 @@
package com.baeldung;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRegistration;
-
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@@ -11,10 +7,13 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletRegistration;
+
public class AppInitializer implements WebApplicationInitializer {
@Override
- public void onStartup(final ServletContext sc) throws ServletException {
+ public void onStartup(final ServletContext sc) {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
@@ -24,7 +23,7 @@ public class AppInitializer implements WebApplicationInitializer {
ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
-
+
sc.addFilter("securityFilter", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, false, "/*");
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAccessDeniedHandler.java
index 9d9fa81dc0..39355202e3 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAccessDeniedHandler.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAccessDeniedHandler.java
@@ -1,25 +1,22 @@
package com.baeldung.security;
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
public static final Logger LOG = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);
@Override
- public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException, ServletException {
+ public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null) {
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAuthenticationFailureHandler.java
index 410d3f1ce9..ce3f299dac 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAuthenticationFailureHandler.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomAuthenticationFailureHandler.java
@@ -13,7 +13,7 @@ import java.util.Calendar;
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
- public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
+ public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
String jsonPayload = "{\"message\" : \"%s\", \"timestamp\" : \"%s\" }";
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomLogoutSuccessHandler.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomLogoutSuccessHandler.java
index 7949eee69a..ee3bd62958 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomLogoutSuccessHandler.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/CustomLogoutSuccessHandler.java
@@ -12,12 +12,6 @@ import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuc
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {
- public CustomLogoutSuccessHandler() {
- super();
- }
-
- // API
-
@Override
public void onLogoutSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException {
final String refererUrl = request.getHeader("Referer");
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java
index 15fa06aa3e..cfdaf7a13e 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java
@@ -23,10 +23,6 @@ import com.baeldung.security.CustomLogoutSuccessHandler;
@Profile("!https")
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
- public SecSecurityConfig() {
- super();
- }
-
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
@@ -81,7 +77,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
-
+
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/ChannelSecSecurityConfig.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/ChannelSecSecurityConfig.java
index e9a6a9e120..151df18d11 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/ChannelSecSecurityConfig.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/ChannelSecSecurityConfig.java
@@ -17,10 +17,6 @@ import com.baeldung.security.CustomLogoutSuccessHandler;
@Profile("https")
public class ChannelSecSecurityConfig extends WebSecurityConfigurerAdapter {
- public ChannelSecSecurityConfig() {
- super();
- }
-
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/MvcConfig.java
index 082477c98c..7b27d637be 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/MvcConfig.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/MvcConfig.java
@@ -13,12 +13,6 @@ import org.springframework.web.servlet.view.JstlView;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
- public MvcConfig() {
- super();
- }
-
- // API
-
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
diff --git a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/RedirectionSecurityConfig.java b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/RedirectionSecurityConfig.java
index 3516438a6e..b27d999d56 100644
--- a/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/RedirectionSecurityConfig.java
+++ b/spring-security-modules/spring-security-web-login/src/main/java/com/baeldung/spring/RedirectionSecurityConfig.java
@@ -11,10 +11,6 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
//@Profile("!https")
public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
- public RedirectionSecurityConfig() {
- super();
- }
-
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
From ed09368f21ea9fac5eea77db3b86f41466552d00 Mon Sep 17 00:00:00 2001
From: Abhinav Pandey
Date: Mon, 7 Feb 2022 11:37:48 +0530
Subject: [PATCH 081/235] BAEL-5327 - Set a description and an example in
Swagger (#11749)
* BAEL-5327 - Set a description and an example in Swagger
* BAEL-5327 - two space indentation for line continuation
Co-authored-by: Abhinav Pandey
---
.../SwaggerExampleApplication.java | 13 ++++++
.../swaggerexample/config/SwaggerConfig.java | 38 +++++++++++++++
.../controller/ProductController.java | 34 ++++++++++++++
.../swaggerexample/entity/Product.java | 46 +++++++++++++++++++
4 files changed, 131 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/SwaggerExampleApplication.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/config/SwaggerConfig.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/controller/ProductController.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/entity/Product.java
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/SwaggerExampleApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/SwaggerExampleApplication.java
new file mode 100644
index 0000000000..4859224bb2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/SwaggerExampleApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerexample;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SwaggerExampleApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SwaggerExampleApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/config/SwaggerConfig.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/config/SwaggerConfig.java
new file mode 100644
index 0000000000..32dbe87bae
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/config/SwaggerConfig.java
@@ -0,0 +1,38 @@
+package com.baeldung.swaggerexample.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+
+import java.util.Collections;
+
+@Configuration
+@EnableWebMvc
+public class SwaggerConfig {
+
+ @Bean
+ public Docket api() {
+ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("com.baeldung.swaggerexample"))
+ .paths(PathSelectors.any())
+ .build();
+ }
+
+ private ApiInfo apiInfo() {
+ return new ApiInfo(
+ "Products API",
+ "API to let you add and view product",
+ "0.0.1",
+ "Terms of service",
+ new Contact("John Doe", "www.example.com", "myemail@company.com"),
+ "License of API", "API license URL", Collections.emptyList());
+ }
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/controller/ProductController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/controller/ProductController.java
new file mode 100644
index 0000000000..7500c01bc0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/controller/ProductController.java
@@ -0,0 +1,34 @@
+package com.baeldung.swaggerexample.controller;
+
+import com.baeldung.swaggerexample.entity.Product;
+import io.swagger.annotations.*;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+@RestController
+@ApiOperation("Products API")
+public class ProductController {
+
+ @ApiOperation(value = "Create a new product", notes = "Creates a new product as per the request body")
+ @ApiResponses(value = {
+ @ApiResponse(code = 201, message = "Successfully created"),
+ @ApiResponse(code = 400, message = "Bad request - The product is not valid"),
+ @ApiResponse(code = 500, message = "Internal server error - Something went wrong")
+ })
+ @PostMapping(value = "/products")
+ public ResponseEntity createProduct(@RequestBody Product product) {
+ return new ResponseEntity<>(HttpStatus.CREATED);
+ }
+
+ @ApiOperation(value = "Get a product by id", notes = "Returns a product as per the id")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Successfully retrieved"),
+ @ApiResponse(code = 404, message = "Not found - The product was not found")
+ })
+ @GetMapping("/products/{id}")
+ public ResponseEntity getProduct(@PathVariable("id") @ApiParam(name = "id", value = "Product id", example = "1") Long id) {
+ //retrieval logic
+ return ResponseEntity.ok(new Product(1, "Product 1", "$21.99"));
+ }
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/entity/Product.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/entity/Product.java
new file mode 100644
index 0000000000..122addadd5
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerexample/entity/Product.java
@@ -0,0 +1,46 @@
+package com.baeldung.swaggerexample.entity;
+
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+
+public class Product implements Serializable {
+ @ApiModelProperty(notes = "Product ID", example = "1", required = true)
+ private Long id;
+ @ApiModelProperty(notes = "Product name", example = "Product 1", required = false)
+ private String name;
+ @ApiModelProperty(notes = "Product price", example = "$100.00", required = true)
+ private String price;
+
+ // constructor and getter/setters
+
+ public Product(long id, String name, String price) {
+ this.id = id;
+ this.name = name;
+ this.price = price;
+ }
+
+ 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 String getPrice() {
+ return price;
+ }
+
+ public void setPrice(String price) {
+ this.price = price;
+ }
+}
From e1212155fe8259d68bb9c12cfa22f466cff5a50c Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Mon, 7 Feb 2022 12:18:51 +0000
Subject: [PATCH 082/235] [JAVA-9895] Split concurrency-basic-2 module
---
.../core-java-concurrency-basic-2/README.md | 3 +--
.../src/main/resources/logback.xml | 6 -----
.../core-java-concurrency-basic-3/README.md | 8 ++++++
.../core-java-concurrency-basic-3/pom.xml | 27 +++++++++++++++++++
.../interrupt/CustomInterruptedException.java | 0
.../interrupt/InterruptExample.java | 0
.../src/main/resources/logback.xml | 13 +++++++++
.../interrupt/InterruptExampleUnitTest.java | 10 +++----
core-java-modules/pom.xml | 1 +
9 files changed, 55 insertions(+), 13 deletions(-)
create mode 100644 core-java-modules/core-java-concurrency-basic-3/README.md
create mode 100644 core-java-modules/core-java-concurrency-basic-3/pom.xml
rename core-java-modules/{core-java-concurrency-basic-2 => core-java-concurrency-basic-3}/src/main/java/com/baeldung/concurrent/interrupt/CustomInterruptedException.java (100%)
rename core-java-modules/{core-java-concurrency-basic-2 => core-java-concurrency-basic-3}/src/main/java/com/baeldung/concurrent/interrupt/InterruptExample.java (100%)
create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/resources/logback.xml
rename core-java-modules/{core-java-concurrency-basic-2 => core-java-concurrency-basic-3}/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java (81%)
diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md
index 1dad941e57..af46046709 100644
--- a/core-java-modules/core-java-concurrency-basic-2/README.md
+++ b/core-java-modules/core-java-concurrency-basic-2/README.md
@@ -12,7 +12,6 @@ This module contains articles about basic Java concurrency
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
-- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
- [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name)
-- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
+- [[<-- Prev]](../core-java-concurrency-basic)[[Next -->]](../core-java-concurrency-basic-3)
diff --git a/core-java-modules/core-java-concurrency-basic-2/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-basic-2/src/main/resources/logback.xml
index 56af2d397e..7d900d8ea8 100644
--- a/core-java-modules/core-java-concurrency-basic-2/src/main/resources/logback.xml
+++ b/core-java-modules/core-java-concurrency-basic-2/src/main/resources/logback.xml
@@ -7,12 +7,6 @@
-
-
-
-
-
-
diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md
new file mode 100644
index 0000000000..477f37e00a
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/README.md
@@ -0,0 +1,8 @@
+## Core Java Concurrency Basic
+
+This module contains articles about basic Java concurrency.
+
+### Relevant Articles:
+
+- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
+- [[<-- Prev]](../core-java-concurrency-basic-2)
diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml
new file mode 100644
index 0000000000..20615e3250
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml
@@ -0,0 +1,27 @@
+
+
+ 4.0.0
+ core-java-concurrency-basic-3
+ 0.1.0-SNAPSHOT
+ core-java-concurrency-basic-3
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ core-java-concurrency-basic-3
+
+
+ src/main/resources
+ true
+
+
+
+
+
diff --git a/core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/interrupt/CustomInterruptedException.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/interrupt/CustomInterruptedException.java
similarity index 100%
rename from core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/interrupt/CustomInterruptedException.java
rename to core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/interrupt/CustomInterruptedException.java
diff --git a/core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/interrupt/InterruptExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/interrupt/InterruptExample.java
similarity index 100%
rename from core-java-modules/core-java-concurrency-basic-2/src/main/java/com/baeldung/concurrent/interrupt/InterruptExample.java
rename to core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/interrupt/InterruptExample.java
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-basic-3/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/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/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java
similarity index 81%
rename from core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java
rename to core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java
index 1ea3f9aa9b..d11ac670f3 100644
--- a/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/interrupt/InterruptExampleUnitTest.java
@@ -1,7 +1,7 @@
package com.baeldung.concurrent.interrupt;
-import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
@@ -9,23 +9,23 @@ public class InterruptExampleUnitTest {
@Test
public void whenPropagateException_thenThrowsInterruptedException() {
- assertThrows(InterruptedException.class, () -> InterruptExample.propagateException());
+ assertThrows(InterruptedException.class, InterruptExample::propagateException);
}
@Test
public void whenRestoreTheState_thenReturnsTrue() {
assertTrue(InterruptExample.restoreTheState());
}
-
+
@Test
public void whenThrowCustomException_thenContainsExpectedMessage() {
- Exception exception = assertThrows(CustomInterruptedException.class, () -> InterruptExample.throwCustomException());
+ Exception exception = assertThrows(CustomInterruptedException.class, InterruptExample::throwCustomException);
String expectedMessage = "This thread was interrupted";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
-
+
@Test
public void whenHandleWithCustomException_thenReturnsTrue() throws CustomInterruptedException{
assertTrue(InterruptExample.handleWithCustomException());
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index 809aa72966..8404d75024 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -46,6 +46,7 @@
core-java-concurrency-advanced-4
core-java-concurrency-basic
core-java-concurrency-basic-2
+ core-java-concurrency-basic-3
core-java-concurrency-collections
core-java-concurrency-collections-2
core-java-console
From 289b9c0fa8dd0f46191036e9e822d8608969a12c Mon Sep 17 00:00:00 2001
From: Sarath Chandra
Date: Mon, 7 Feb 2022 23:00:56 +0530
Subject: [PATCH 083/235] [BAEL-5261] Customizing Zuul Exceptions (#11736)
* [BAEL-5261] Customizing Zuul Exceptions
* [BAEL-5261] Customizing Zuul Exceptions
* [BAEL-5261] Code sanitizing
---
.../filter/CustomZuulErrorApplication.java | 15 +++
.../zuul/filter/CustomZuulErrorFilter.java | 62 ++++++++++++
.../cloud/zuul/filter/ZuulConfiguration.java | 98 +++++++++++++++++++
.../src/main/resources/application.yml | 5 +-
.../filter/CustomZuulErrorFilterLiveTest.java | 24 +++++
5 files changed, 203 insertions(+), 1 deletion(-)
create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorApplication.java
create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilter.java
create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/ZuulConfiguration.java
create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/test/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilterLiveTest.java
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorApplication.java b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorApplication.java
new file mode 100644
index 0000000000..ae8c3040ef
--- /dev/null
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.spring.cloud.zuul.filter;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
+
+@EnableZuulProxy
+@SpringBootApplication
+public class CustomZuulErrorApplication extends SpringBootServletInitializer {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CustomZuulErrorApplication.class, args);
+ }
+}
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilter.java b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilter.java
new file mode 100644
index 0000000000..d3e52843eb
--- /dev/null
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilter.java
@@ -0,0 +1,62 @@
+package com.baeldung.spring.cloud.zuul.filter;
+
+import java.net.ConnectException;
+import java.time.Instant;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.netflix.zuul.ZuulFilter;
+import com.netflix.zuul.context.RequestContext;
+import com.netflix.zuul.exception.ZuulException;
+
+@Component
+public class CustomZuulErrorFilter extends ZuulFilter {
+
+ private static final Logger log = LoggerFactory.getLogger(CustomZuulErrorFilter.class);
+
+ private static final String RESPONSE_BODY = "{\n" + " \"timestamp\": " + "\"" + Instant.now()
+ .toString() + "\"" + ",\n" + " \"status\": 503,\n" + " \"error\": \"Service Unavailable\"\n" + "}";
+
+ @Override
+ public Object run() {
+ RequestContext context = RequestContext.getCurrentContext();
+ Throwable throwable = context.getThrowable();
+
+ if (throwable instanceof ZuulException) {
+ final ZuulException zuulException = (ZuulException) throwable;
+ log.error("Zuul exception: " + zuulException.getMessage());
+
+ if (throwable.getCause().getCause().getCause() instanceof ConnectException) {
+
+ // reset throwable to prevent further error handling in follow up filters
+ context.remove("throwable");
+
+ // set custom response attributes
+ context.setResponseBody(RESPONSE_BODY);
+ context.getResponse()
+ .setContentType("application/json");
+ context.setResponseStatusCode(503);
+ }
+
+ }
+ return null;
+ }
+
+ @Override
+ public boolean shouldFilter() {
+ return true;
+ }
+
+ @Override
+ public int filterOrder() {
+ return -1;
+ }
+
+ @Override
+ public String filterType() {
+ return "error";
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/ZuulConfiguration.java b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/ZuulConfiguration.java
new file mode 100644
index 0000000000..3122862050
--- /dev/null
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/java/com/baeldung/spring/cloud/zuul/filter/ZuulConfiguration.java
@@ -0,0 +1,98 @@
+package com.baeldung.spring.cloud.zuul.filter;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.boot.web.servlet.error.ErrorController;
+import org.springframework.cglib.proxy.Callback;
+import org.springframework.cglib.proxy.CallbackFilter;
+import org.springframework.cglib.proxy.Enhancer;
+import org.springframework.cglib.proxy.MethodInterceptor;
+import org.springframework.cglib.proxy.MethodProxy;
+import org.springframework.cglib.proxy.NoOp;
+import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
+import org.springframework.cloud.netflix.zuul.web.ZuulController;
+import org.springframework.cloud.netflix.zuul.web.ZuulHandlerMapping;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * Fix for Zuul configuration with Spring Boot 2.5.x + Zuul - "NoSuchMethodError: ErrorController.getErrorPath()":
+ */
+@Configuration
+public class ZuulConfiguration {
+ /**
+ * The path returned by ErrorController.getErrorPath() with Spring Boot < 2.5
+ * (and no longer available on Spring Boot >= 2.5).
+ */
+ private static final String ERROR_PATH = "/error";
+ private static final String METHOD = "lookupHandler";
+
+ /**
+ * Constructs a new bean post-processor for Zuul.
+ *
+ * @param routeLocator the route locator.
+ * @param zuulController the Zuul controller.
+ * @param errorController the error controller.
+ * @return the new bean post-processor.
+ */
+ @Bean
+ public ZuulPostProcessor zuulPostProcessor(@Autowired RouteLocator routeLocator, @Autowired ZuulController zuulController, @Autowired(required = false) ErrorController errorController) {
+ return new ZuulPostProcessor(routeLocator, zuulController, errorController);
+ }
+
+ private enum LookupHandlerCallbackFilter implements CallbackFilter {
+ INSTANCE;
+
+ @Override
+ public int accept(Method method) {
+ if (METHOD.equals(method.getName())) {
+ return 0;
+ }
+ return 1;
+ }
+ }
+
+ private enum LookupHandlerMethodInterceptor implements MethodInterceptor {
+ INSTANCE;
+
+ @Override
+ public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
+ if (ERROR_PATH.equals(args[0])) {
+ // by entering this branch we avoid the ZuulHandlerMapping.lookupHandler method to trigger the
+ // NoSuchMethodError
+ return null;
+ }
+ return methodProxy.invokeSuper(target, args);
+ }
+ }
+
+ private static final class ZuulPostProcessor implements BeanPostProcessor {
+
+ private final RouteLocator routeLocator;
+ private final ZuulController zuulController;
+ private final boolean hasErrorController;
+
+ ZuulPostProcessor(RouteLocator routeLocator, ZuulController zuulController, ErrorController errorController) {
+ this.routeLocator = routeLocator;
+ this.zuulController = zuulController;
+ this.hasErrorController = (errorController != null);
+ }
+
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
+ if (hasErrorController && (bean instanceof ZuulHandlerMapping)) {
+ Enhancer enhancer = new Enhancer();
+ enhancer.setSuperclass(ZuulHandlerMapping.class);
+ enhancer.setCallbackFilter(LookupHandlerCallbackFilter.INSTANCE); // only for lookupHandler
+ enhancer.setCallbacks(new Callback[] { LookupHandlerMethodInterceptor.INSTANCE, NoOp.INSTANCE });
+ Constructor> ctor = ZuulHandlerMapping.class.getConstructors()[0];
+ return enhancer.create(ctor.getParameterTypes(), new Object[] { routeLocator, zuulController });
+ }
+ return bean;
+ }
+ }
+}
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/resources/application.yml
index 855020a40e..bd517b8a6b 100644
--- a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/resources/application.yml
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/main/resources/application.yml
@@ -1,5 +1,8 @@
zuul:
+ SendErrorFilter:
+ post:
+ disable: true
routes:
foos:
path: /foos/**
- url: http://localhost:8081/spring-zuul-foos-resource/foos
+ url: http://localhost:8081/spring-zuul-foos-resource/foos
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/test/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilterLiveTest.java b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/test/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilterLiveTest.java
new file mode 100644
index 0000000000..da2588966d
--- /dev/null
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/src/test/java/com/baeldung/spring/cloud/zuul/filter/CustomZuulErrorFilterLiveTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.spring.cloud.zuul.filter;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import io.restassured.RestAssured;
+import io.restassured.response.Response;
+
+public class CustomZuulErrorFilterLiveTest {
+
+ @Test
+ public void whenSendRequestWithoutService_thenCustomError() {
+ final Response response = RestAssured.get("http://localhost:8080/foos/1");
+ assertEquals(503, response.getStatusCode());
+ }
+
+ @Test
+ public void whenSendRequestWithoutCustomErrorFilter_thenError() {
+ final Response response = RestAssured.get("http://localhost:8080/foos/1");
+ assertEquals(500, response.getStatusCode());
+ }
+
+}
From b35d0ea7c4481c5663487bd9e12a3a7eba0eb3ce Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Tue, 8 Feb 2022 00:40:07 +0530
Subject: [PATCH 084/235] BAEL-5351: Unit Tests name as per BBD convention
---
.../map/initialize/EmptyMapInitializerUnitTest.java | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
index 82225a46ec..b40ffed94b 100644
--- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
+++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
@@ -15,13 +15,14 @@ public class EmptyMapInitializerUnitTest {
}
@Test
- public void checkStaticMap_isEmpty() {
+ public void givenEmptyMap_whenChecked_returnsTrue() {
assertTrue(EmptyMapInitializer.articleMap.isEmpty());
}
@Test
- public void emptyMapCreated_usingGuava() {
- Map emptyMapUsingGuava = EmptyMapInitializer.createMapUsingGuava();
+ public void givenEmptyMap_whenCreatedUsingGuava_returnsEmptyOrNot() {
+ Map emptyMapUsingGuava =
+ EmptyMapInitializer.createMapUsingGuava();
assertTrue(emptyMapUsingGuava.isEmpty());
emptyMapUsingGuava.put("key", "value");
assertFalse(emptyMapUsingGuava.isEmpty());
From 616195b6b2a3f7f787884582d2ee3f31d5f70806 Mon Sep 17 00:00:00 2001
From: chrys exaucet
Date: Mon, 7 Feb 2022 20:04:22 +0000
Subject: [PATCH 085/235] Bael 5123: uncomment @NotBlank annotation (#11788)
* revert: comment Hibernate Validator AP dependency
See http://jira.baeldung.com/browse/BAEL-5123
* revert: restore @NotBlank annotation
See http://jira.baeldung.com/browse/BAEL-5123
---
javaxval/pom.xml | 4 ++++
.../com/baeldung/javaxval/container/validation/Customer.java | 1 +
2 files changed, 5 insertions(+)
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 7d009f3280..4131ddeb97 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -36,6 +36,8 @@
+
+
+
6.0.13.Final
6.2.0.Final
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
index d990647721..03811635ee 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
@@ -20,6 +20,7 @@ public class Customer {
@PositiveOrZero
private OptionalInt numberOfOrders;
+ @NotBlank
private Profile profile;
public String getName() {
From a63ea1944df5e66dca00e58d4166d4f9a1309be4 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Tue, 8 Feb 2022 12:11:51 +0800
Subject: [PATCH 086/235] Update README.md
---
core-java-modules/multimodulemavenproject/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/multimodulemavenproject/README.md b/core-java-modules/multimodulemavenproject/README.md
index fc4ca60b6b..13d87c36ec 100644
--- a/core-java-modules/multimodulemavenproject/README.md
+++ b/core-java-modules/multimodulemavenproject/README.md
@@ -1,3 +1,4 @@
## Relevant Articles
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
+- [Importing Maven Project into Eclipse](https://www.baeldung.com/maven-import-eclipse)
From 1bf44ff8ef31887bc85fd77f09ad7b69b0f64216 Mon Sep 17 00:00:00 2001
From: vaibhav007jain <72961247+vaibhav007jain@users.noreply.github.com>
Date: Tue, 8 Feb 2022 13:45:38 +0530
Subject: [PATCH 087/235] BAEL-5280: added code for
ArrayIndexOutOfBoundsException. (#11772)
* commited initial code for hexagonal architecture
* Deleting to check in again
* Deleing to check in again
* Push first code for Hexagonal Architecture
* final code with UT for JSON to Java conversion
* removed hexagonal-architecture code from last commit
* BEL-5071 updated README
* BAEL-5071: Undo README changes and added a nested object in the JSON example.
* BAEL-5071: fixed whitespace/indentation in JsonToJavaClassConversion.java
* BAEL-5151: Added code for getting the first of a String
* BAEL-5151: Renamed Unit Test
* BAEL-5151: Moved the files from core-java-string-operations to core-java-string-operations-3
* BAEL-5151: Replaced tabs with white spaces.
* BAEL-5228: Adding code for approaches to concatening null string in java
* BAEL-5228: Moved file to correct folder and added a UT.
* BAEL-5228: corrected import statements.
* BAEL-5228: corrected last commit.
* BAEL-5228: removed extra import.
* BAEL-5228: renamed UT
* BAEL-5280: added code for ArrayIndexOutOfBoundsException.
* BAEL-5280: moved code for ArrayIndexOutOfBoundsException in a new module.
* BAEL-5280: Fixed tab/spaces in pom.xml.
* BAEL-5280: Fixed indentation in ArrayIndexOutOfBoundsExceptionDemoUnitTest.java.
Co-authored-by: Vaibhav Jain
---
.../core-java-exceptions-4/pom.xml | 47 +++++++++++++++++++
.../ArrayIndexOutOfBoundsExceptionDemo.java | 31 ++++++++++++
...IndexOutOfBoundsExceptionDemoUnitTest.java | 34 ++++++++++++++
core-java-modules/pom.xml | 1 +
4 files changed, 113 insertions(+)
create mode 100644 core-java-modules/core-java-exceptions-4/pom.xml
create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemo.java
create mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemoUnitTest.java
diff --git a/core-java-modules/core-java-exceptions-4/pom.xml b/core-java-modules/core-java-exceptions-4/pom.xml
new file mode 100644
index 0000000000..cc81fdc40b
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/pom.xml
@@ -0,0 +1,47 @@
+
+
+ 4.0.0
+ com.baeldung.exceptions
+ core-java-exceptions-4
+ 0.1.0-SNAPSHOT
+ core-java-exceptions-4
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ com.h2database
+ h2
+ ${h2.version}
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.1
+
+
+
+
+
+
+
+
+
+
+
+ 1.4.191
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemo.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemo.java
new file mode 100644
index 0000000000..6b320976a6
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemo.java
@@ -0,0 +1,31 @@
+package com.baeldung.exception.arrayindexoutofbounds;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class ArrayIndexOutOfBoundsExceptionDemo {
+
+ public static void main(String[] args) {
+ int[] numbers = new int[] { 1, 2, 3, 4, 5 };
+
+ getArrayElementAtIndex(numbers, 5);
+ getListElementAtIndex(5);
+ addArrayElementsUsingLoop(numbers);
+ }
+
+ public static void addArrayElementsUsingLoop(int[] numbers) {
+ int sum = 0;
+ for (int i = 0; i <= numbers.length; i++) {
+ sum += numbers[i];
+ }
+ }
+
+ public static int getListElementAtIndex(int index) {
+ List numbersList = Arrays.asList(1, 2, 3, 4, 5);
+ return numbersList.get(index);
+ }
+
+ public static int getArrayElementAtIndex(int[] numbers, int index) {
+ return numbers[index];
+ }
+}
diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemoUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemoUnitTest.java
new file mode 100644
index 0000000000..e1ad2b8021
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/arrayindexoutofbounds/ArrayIndexOutOfBoundsExceptionDemoUnitTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.exception.arrayindexoutofbounds;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class ArrayIndexOutOfBoundsExceptionDemoUnitTest {
+
+ private static int[] numbers;
+
+ @BeforeAll
+ public static void setUp() {
+ numbers = new int[] { 1, 2, 3, 4, 5 };
+ }
+
+ @Test
+ void givenAnArrayOfSizeFive_whenAccessedElementBeyondRange_thenShouldThrowArrayIndexOutOfBoundsException() {
+ assertThrows(ArrayIndexOutOfBoundsException.class,
+ () -> ArrayIndexOutOfBoundsExceptionDemo.addArrayElementsUsingLoop(numbers));
+ }
+
+ @Test
+ void givenAnArrayOfSizeFive_whenAccessedAnElementAtIndexEqualToSize_thenShouldThrowArrayIndexOutOfBoundsException() {
+ assertThrows(ArrayIndexOutOfBoundsException.class,
+ () -> ArrayIndexOutOfBoundsExceptionDemo.getArrayElementAtIndex(numbers, 5));
+ }
+
+ @Test
+ void givenAListReturnedByArraysAsListMethod_whenAccessedAnElementAtIndexEqualToSize_thenShouldThrowArrayIndexOutOfBoundsException() {
+ assertThrows(ArrayIndexOutOfBoundsException.class,
+ () -> ArrayIndexOutOfBoundsExceptionDemo.getListElementAtIndex(5));
+ }
+}
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index 8404d75024..a25cf11454 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -56,6 +56,7 @@
core-java-exceptions
core-java-exceptions-2
core-java-exceptions-3
+ core-java-exceptions-4
core-java-function
core-java-functional
core-java-io
From 61dd13d64e02b3ef8434dd3faefa87014ad69b5f Mon Sep 17 00:00:00 2001
From: Azhwani <13301425+azhwani@users.noreply.github.com>
Date: Tue, 8 Feb 2022 15:48:06 +0100
Subject: [PATCH 088/235] init commit (#11767)
---
.../controller/StudentRestController.java | 11 +++++++
.../NoConverterFoundIntegrationTest.java | 30 +++++++++++++++----
2 files changed, 36 insertions(+), 5 deletions(-)
diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/noconverterfound/controller/StudentRestController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/noconverterfound/controller/StudentRestController.java
index 21cb98710d..4119b624e1 100644
--- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/noconverterfound/controller/StudentRestController.java
+++ b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/noconverterfound/controller/StudentRestController.java
@@ -1,5 +1,6 @@
package com.baeldung.boot.noconverterfound.controller;
+import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -18,4 +19,14 @@ public class StudentRestController {
return ResponseEntity.ok(new Student(id, "John", "Wiliams", "AA"));
}
+ @GetMapping(value = "/student/v2/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity getV2(@PathVariable("id") int id) {
+ return ResponseEntity.ok(new Student(id, "Kevin", "Cruyff", "AA"));
+ }
+
+ @GetMapping(value = "/student/v3/{id}", produces = MediaType.APPLICATION_XML_VALUE)
+ public ResponseEntity getV3(@PathVariable("id") int id) {
+ return ResponseEntity.ok(new Student(id, "Robert", "Miller", "BB"));
+ }
+
}
diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/noconverterfound/NoConverterFoundIntegrationTest.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/noconverterfound/NoConverterFoundIntegrationTest.java
index f8ded91e65..6f89ef0e58 100644
--- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/noconverterfound/NoConverterFoundIntegrationTest.java
+++ b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/noconverterfound/NoConverterFoundIntegrationTest.java
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -25,16 +26,16 @@ public class NoConverterFoundIntegrationTest {
/* Remove Getters from Student class to successfully run this test case
* @Test
public void whenGettersNotDefined_thenThrowException() throws Exception {
-
+
String url = "/api/student/1";
-
+
this.mockMvc.perform(get(url))
.andExpect(status().isInternalServerError())
.andExpect(result -> assertThat(result.getResolvedException())
.isInstanceOf(HttpMessageNotWritableException.class))
.andExpect(result -> assertThat(result.getResolvedException().getMessage())
.contains("No converter found for return value of type"));
-
+
}
*/
@@ -44,9 +45,28 @@ public class NoConverterFoundIntegrationTest {
String url = "/api/student/2";
this.mockMvc.perform(get(url))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.firstName").value("John"));
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.firstName").value("John"));
+ }
+ @Test
+ public void whenJsonConverterIsFound_thenReturnResponse() throws Exception {
+ String url = "/api/student/v2/1";
+
+ this.mockMvc.perform(get(url))
+ .andExpect(status().isOk())
+ .andExpect(content().json("{'id':1,'firstName':'Kevin','lastName':'Cruyff', 'grade':'AA'}"));
+ }
+
+ @Test
+ public void whenConverterNotFound_thenThrowException() throws Exception {
+ String url = "/api/student/v3/1";
+
+ this.mockMvc.perform(get(url))
+ .andExpect(status().isInternalServerError())
+ .andExpect(result -> assertThat(result.getResolvedException()).isInstanceOf(HttpMessageNotWritableException.class))
+ .andExpect(result -> assertThat(result.getResolvedException()
+ .getMessage()).contains("No converter for [class com.baeldung.boot.noconverterfound.model.Student] with preset Content-Type"));
}
}
From 5f7a0c20b21a50f66439b49bc5c49c5b9856e1db Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Tue, 8 Feb 2022 20:28:30 +0530
Subject: [PATCH 089/235] COMAUTO-9485 Fixed DB url in spring-project and added
missing maven wrapper
---
.../.mvn/wrapper/maven-wrapper.properties | 18 +
quarkus-vs-springboot/quarkus-project/mvnw | 316 ++++++++++++++++++
.../quarkus-project/mvnw.cmd | 188 +++++++++++
.../.mvn/wrapper/maven-wrapper.properties | 18 +
quarkus-vs-springboot/spring-project/mvnw | 316 ++++++++++++++++++
quarkus-vs-springboot/spring-project/mvnw.cmd | 188 +++++++++++
.../src/main/resources/application.properties | 2 +-
7 files changed, 1045 insertions(+), 1 deletion(-)
create mode 100644 quarkus-vs-springboot/quarkus-project/.mvn/wrapper/maven-wrapper.properties
create mode 100755 quarkus-vs-springboot/quarkus-project/mvnw
create mode 100644 quarkus-vs-springboot/quarkus-project/mvnw.cmd
create mode 100644 quarkus-vs-springboot/spring-project/.mvn/wrapper/maven-wrapper.properties
create mode 100755 quarkus-vs-springboot/spring-project/mvnw
create mode 100644 quarkus-vs-springboot/spring-project/mvnw.cmd
diff --git a/quarkus-vs-springboot/quarkus-project/.mvn/wrapper/maven-wrapper.properties b/quarkus-vs-springboot/quarkus-project/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000000..8c79a83ae4
--- /dev/null
+++ b/quarkus-vs-springboot/quarkus-project/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
diff --git a/quarkus-vs-springboot/quarkus-project/mvnw b/quarkus-vs-springboot/quarkus-project/mvnw
new file mode 100755
index 0000000000..5643201c7d
--- /dev/null
+++ b/quarkus-vs-springboot/quarkus-project/mvnw
@@ -0,0 +1,316 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /usr/local/etc/mavenrc ] ; then
+ . /usr/local/etc/mavenrc
+ fi
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`\\unset -f command; \\command -v java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found .mvn/wrapper/maven-wrapper.jar"
+ fi
+else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+ fi
+ if [ -n "$MVNW_REPOURL" ]; then
+ jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ else
+ jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ fi
+ while IFS="=" read key value; do
+ case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+ esac
+ done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Downloading from: $jarUrl"
+ fi
+ wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+ if $cygwin; then
+ wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+ fi
+
+ if command -v wget > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found wget ... using wget"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ else
+ wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ fi
+ elif command -v curl > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found curl ... using curl"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ curl -o "$wrapperJarPath" "$jarUrl" -f
+ else
+ curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+ fi
+
+ else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Falling back to using Java to download"
+ fi
+ javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+ # For Cygwin, switch paths to Windows format before running javac
+ if $cygwin; then
+ javaClass=`cygpath --path --windows "$javaClass"`
+ fi
+ if [ -e "$javaClass" ]; then
+ if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Compiling MavenWrapperDownloader.java ..."
+ fi
+ # Compiling the Java class
+ ("$JAVA_HOME/bin/javac" "$javaClass")
+ fi
+ if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ # Running the downloader
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Running MavenWrapperDownloader.java ..."
+ fi
+ ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+ fi
+ fi
+ fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ $MAVEN_DEBUG_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" \
+ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/quarkus-vs-springboot/quarkus-project/mvnw.cmd b/quarkus-vs-springboot/quarkus-project/mvnw.cmd
new file mode 100644
index 0000000000..23b7079a3d
--- /dev/null
+++ b/quarkus-vs-springboot/quarkus-project/mvnw.cmd
@@ -0,0 +1,188 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
+if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+
+FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+ IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Found %WRAPPER_JAR%
+ )
+) else (
+ if not "%MVNW_REPOURL%" == "" (
+ SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ )
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Couldn't find %WRAPPER_JAR%, downloading it ...
+ echo Downloading from: %DOWNLOAD_URL%
+ )
+
+ powershell -Command "&{"^
+ "$webclient = new-object System.Net.WebClient;"^
+ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+ "}"^
+ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+ "}"
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Finished downloading %WRAPPER_JAR%
+ )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% ^
+ %JVM_CONFIG_MAVEN_PROPS% ^
+ %MAVEN_OPTS% ^
+ %MAVEN_DEBUG_OPTS% ^
+ -classpath %WRAPPER_JAR% ^
+ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
+ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
+if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%"=="on" pause
+
+if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
+
+cmd /C exit /B %ERROR_CODE%
diff --git a/quarkus-vs-springboot/spring-project/.mvn/wrapper/maven-wrapper.properties b/quarkus-vs-springboot/spring-project/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000000..8c79a83ae4
--- /dev/null
+++ b/quarkus-vs-springboot/spring-project/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
diff --git a/quarkus-vs-springboot/spring-project/mvnw b/quarkus-vs-springboot/spring-project/mvnw
new file mode 100755
index 0000000000..5643201c7d
--- /dev/null
+++ b/quarkus-vs-springboot/spring-project/mvnw
@@ -0,0 +1,316 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /usr/local/etc/mavenrc ] ; then
+ . /usr/local/etc/mavenrc
+ fi
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`\\unset -f command; \\command -v java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found .mvn/wrapper/maven-wrapper.jar"
+ fi
+else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+ fi
+ if [ -n "$MVNW_REPOURL" ]; then
+ jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ else
+ jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ fi
+ while IFS="=" read key value; do
+ case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+ esac
+ done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Downloading from: $jarUrl"
+ fi
+ wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+ if $cygwin; then
+ wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+ fi
+
+ if command -v wget > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found wget ... using wget"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ else
+ wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ fi
+ elif command -v curl > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found curl ... using curl"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ curl -o "$wrapperJarPath" "$jarUrl" -f
+ else
+ curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+ fi
+
+ else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Falling back to using Java to download"
+ fi
+ javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+ # For Cygwin, switch paths to Windows format before running javac
+ if $cygwin; then
+ javaClass=`cygpath --path --windows "$javaClass"`
+ fi
+ if [ -e "$javaClass" ]; then
+ if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Compiling MavenWrapperDownloader.java ..."
+ fi
+ # Compiling the Java class
+ ("$JAVA_HOME/bin/javac" "$javaClass")
+ fi
+ if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ # Running the downloader
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Running MavenWrapperDownloader.java ..."
+ fi
+ ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+ fi
+ fi
+ fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ $MAVEN_DEBUG_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" \
+ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/quarkus-vs-springboot/spring-project/mvnw.cmd b/quarkus-vs-springboot/spring-project/mvnw.cmd
new file mode 100644
index 0000000000..23b7079a3d
--- /dev/null
+++ b/quarkus-vs-springboot/spring-project/mvnw.cmd
@@ -0,0 +1,188 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
+if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+
+FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+ IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Found %WRAPPER_JAR%
+ )
+) else (
+ if not "%MVNW_REPOURL%" == "" (
+ SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ )
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Couldn't find %WRAPPER_JAR%, downloading it ...
+ echo Downloading from: %DOWNLOAD_URL%
+ )
+
+ powershell -Command "&{"^
+ "$webclient = new-object System.Net.WebClient;"^
+ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+ "}"^
+ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+ "}"
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Finished downloading %WRAPPER_JAR%
+ )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% ^
+ %JVM_CONFIG_MAVEN_PROPS% ^
+ %MAVEN_OPTS% ^
+ %MAVEN_DEBUG_OPTS% ^
+ -classpath %WRAPPER_JAR% ^
+ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
+ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
+if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%"=="on" pause
+
+if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
+
+cmd /C exit /B %ERROR_CODE%
diff --git a/quarkus-vs-springboot/spring-project/src/main/resources/application.properties b/quarkus-vs-springboot/spring-project/src/main/resources/application.properties
index adc2f8b0b4..1d49b67fda 100644
--- a/quarkus-vs-springboot/spring-project/src/main/resources/application.properties
+++ b/quarkus-vs-springboot/spring-project/src/main/resources/application.properties
@@ -1,4 +1,4 @@
-spring.r2dbc.url=${DB_URL:'r2dbc:postgresql://localhost:5432/postgres'}
+spring.r2dbc.url=${DB_URL:r2dbc:postgresql://localhost:5432/postgres}
spring.r2dbc.username=postgres
spring.r2dbc.password=example
spring.r2dbc.pool.enabled=true
From 3dd2802e2db7ad12994e16e79aa2a4ca2dadc202 Mon Sep 17 00:00:00 2001
From: palani-a
Date: Wed, 9 Feb 2022 00:15:13 +0530
Subject: [PATCH 090/235] BAEL-5348: Invert a Map in Java + tests
---
.../map/invert/InvertHashMapExample.java | 59 ++++++++++++++++++
.../map/invert/InvertHashMapExampleTest.java | 60 +++++++++++++++++++
2 files changed, 119 insertions(+)
create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
create mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
new file mode 100644
index 0000000000..a203fd17c4
--- /dev/null
+++ b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
@@ -0,0 +1,59 @@
+package com.baeldung.map.invert;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+public class InvertHashMapExample {
+
+ public static void main(String[] args) {
+
+ Map map = new HashMap<>();
+ map.put("first", 1);
+ map.put("second", 2);
+ System.out.println(map);
+
+ invertMapUsingForLoop(map);
+ invertMapUsingStreams(map);
+ invertMapUsingMapper(map);
+
+ map.put("two", 2);
+ invertMapUsingGroupingBy(map);
+ }
+
+ public static Map invertMapUsingForLoop(Map map) {
+ Map inversedMap = new HashMap();
+ for (Entry entry : map.entrySet()) {
+ inversedMap.put(entry.getValue(), entry.getKey());
+ }
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map invertMapUsingStreams(Map map) {
+ Map inversedMap = map.entrySet()
+ .stream()
+ .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map invertMapUsingMapper(Map sourceMap) {
+ Map inversedMap = sourceMap.entrySet()
+ .stream()
+ .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map> invertMapUsingGroupingBy(Map map) {
+ Map> inversedMap = map.entrySet()
+ .stream()
+ .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+}
diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
new file mode 100644
index 0000000000..aecfbfe675
--- /dev/null
+++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.map.invert;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+public class InvertHashMapExampleTest {
+
+ Map sourceMap;
+
+ @BeforeAll
+ void setup() {
+ sourceMap = new HashMap<>();
+ sourceMap.put("Sunday", 0);
+ sourceMap.put("Monday", 1);
+ }
+
+ @Test
+ void test1_invertMapUsingForLoop() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test2_invertMapUsingStreams() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test3_invertMapUsingMapper() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test4_invertMapUsingGroupingBy() {
+ sourceMap.put("monday", 1);
+ Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertTrue(inversedMap.get(1) instanceof List);
+ }
+
+}
From 667cff71edc3b4f2ba4a52af34e55e8bb550a53a Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Wed, 9 Feb 2022 00:56:36 +0530
Subject: [PATCH 091/235] JAVA-7535 Added code for maven-multi-module
---
.../maven-simple/maven-dependency/pom.xml | 4 +-
.../maven-simple/parent-project/core/pom.xml | 16 ++++++
.../maven-simple/parent-project/pom.xml | 22 ++++++++
.../parent-project/service/pom.xml | 16 ++++++
.../parent-project/webapp/pom.xml | 16 ++++++
.../maven-simple/plugin-management/pom.xml | 2 +-
.../plugin-management/submodule-2/pom.xml | 18 +++----
maven-modules/maven-simple/pom.xml | 54 +++++++++++--------
8 files changed, 115 insertions(+), 33 deletions(-)
create mode 100644 maven-modules/maven-simple/parent-project/core/pom.xml
create mode 100644 maven-modules/maven-simple/parent-project/pom.xml
create mode 100644 maven-modules/maven-simple/parent-project/service/pom.xml
create mode 100644 maven-modules/maven-simple/parent-project/webapp/pom.xml
diff --git a/maven-modules/maven-simple/maven-dependency/pom.xml b/maven-modules/maven-simple/maven-dependency/pom.xml
index 46c59409ef..ac4902e1ad 100644
--- a/maven-modules/maven-simple/maven-dependency/pom.xml
+++ b/maven-modules/maven-simple/maven-dependency/pom.xml
@@ -9,7 +9,7 @@
com.baeldung
- maven-modules
+ maven-simple
0.0.1-SNAPSHOT
@@ -18,7 +18,7 @@
org.apache.commons
commons-lang3
- 3.12.0
+ ${commons-lang3.version}
diff --git a/maven-modules/maven-simple/parent-project/core/pom.xml b/maven-modules/maven-simple/parent-project/core/pom.xml
new file mode 100644
index 0000000000..5ae3f6a0bb
--- /dev/null
+++ b/maven-modules/maven-simple/parent-project/core/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ org.baeldung
+ core
+ core
+
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
+
+
diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml
new file mode 100644
index 0000000000..7d541a3353
--- /dev/null
+++ b/maven-modules/maven-simple/parent-project/pom.xml
@@ -0,0 +1,22 @@
+
+
+ 4.0.0
+ parent-project
+ 1.0-SNAPSHOT
+ parent-project
+ pom
+
+
+ com.baeldung
+ maven-simple
+ 0.0.1-SNAPSHOT
+
+
+
+ core
+ service
+ webapp
+
+
diff --git a/maven-modules/maven-simple/parent-project/service/pom.xml b/maven-modules/maven-simple/parent-project/service/pom.xml
new file mode 100644
index 0000000000..b20b3ad1d2
--- /dev/null
+++ b/maven-modules/maven-simple/parent-project/service/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ org.baeldung
+ service
+ service
+
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
+
+
diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml
new file mode 100644
index 0000000000..05594d0995
--- /dev/null
+++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ org.baeldung
+ webapp
+ webapp
+
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
+
+
diff --git a/maven-modules/maven-simple/plugin-management/pom.xml b/maven-modules/maven-simple/plugin-management/pom.xml
index b680d1d39b..9ca65dd549 100644
--- a/maven-modules/maven-simple/plugin-management/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/pom.xml
@@ -7,7 +7,7 @@
pom
- maven-modules
+ maven-simple
com.baeldung
0.0.1-SNAPSHOT
diff --git a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
index e50d3cc26d..df460ec159 100644
--- a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
@@ -1,14 +1,14 @@
- 4.0.0
- submodule-2
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ submodule-2
-
- plugin-management
- com.baeldung
- 0.0.1-SNAPSHOT
-
+
+ plugin-management
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml
index 87df6a9bca..7272ef45f1 100644
--- a/maven-modules/maven-simple/pom.xml
+++ b/maven-modules/maven-simple/pom.xml
@@ -1,22 +1,34 @@
-
-
- 4.0.0
- maven-simple
- maven-simple
- pom
-
-
- com.baeldung
- maven-modules
- 0.0.1-SNAPSHOT
-
-
-
- maven-profiles
- plugin-management
- maven-dependency
-
-
+
+
+
+ 4.0.0
+
+ maven-simple
+
+ maven-simple
+
+ pom
+
+
+
+ com.baeldung
+
+ maven-modules
+
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ maven-profiles
+
+ plugin-management
+
+ maven-dependency
+
+ parent-project
+
+
+
From c5e767a14aca10772fbd3f9ac89ecfd9cae8947f Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Wed, 9 Feb 2022 01:00:12 +0530
Subject: [PATCH 092/235] JAVA-7535 Pom formatting
---
maven-modules/maven-simple/pom.xml | 55 ++++++++++++------------------
1 file changed, 22 insertions(+), 33 deletions(-)
diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml
index 7272ef45f1..78e4e8df46 100644
--- a/maven-modules/maven-simple/pom.xml
+++ b/maven-modules/maven-simple/pom.xml
@@ -1,34 +1,23 @@
-
-
- 4.0.0
-
- maven-simple
-
- maven-simple
-
- pom
-
-
-
- com.baeldung
-
- maven-modules
-
- 0.0.1-SNAPSHOT
-
-
-
-
-
- maven-profiles
-
- plugin-management
-
- maven-dependency
-
- parent-project
-
-
-
-
+
+ 4.0.0
+ maven-simple
+ maven-simple
+ pom
+
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ maven-profiles
+ plugin-management
+ maven-dependency
+ parent-project
+
+
+
\ No newline at end of file
From e5bf53cdfd49d3972e08f360b268a51c9c47e050 Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Wed, 9 Feb 2022 01:03:55 +0530
Subject: [PATCH 093/235] JAVA-7535 Pom formatting
---
.../maven-simple/maven-dependency/pom.xml | 60 +++---
.../maven-simple/maven-profiles/pom.xml | 180 +++++++++---------
.../maven-simple/parent-project/core/pom.xml | 22 +--
.../maven-simple/parent-project/pom.xml | 34 ++--
.../parent-project/service/pom.xml | 22 +--
.../parent-project/webapp/pom.xml | 22 +--
.../maven-simple/plugin-management/pom.xml | 110 +++++------
.../plugin-management/submodule-2/pom.xml | 18 +-
maven-modules/maven-simple/pom.xml | 34 ++--
9 files changed, 251 insertions(+), 251 deletions(-)
diff --git a/maven-modules/maven-simple/maven-dependency/pom.xml b/maven-modules/maven-simple/maven-dependency/pom.xml
index ac4902e1ad..628c1b62d4 100644
--- a/maven-modules/maven-simple/maven-dependency/pom.xml
+++ b/maven-modules/maven-simple/maven-dependency/pom.xml
@@ -1,37 +1,37 @@
- 4.0.0
- maven-dependency
- 1.0.0-SNAPSHOT
- pom
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ maven-dependency
+ 1.0.0-SNAPSHOT
+ pom
-
- com.baeldung
- maven-simple
- 0.0.1-SNAPSHOT
-
+
+ com.baeldung
+ maven-simple
+ 0.0.1-SNAPSHOT
+
-
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
-
-
- org.junit.vintage
- junit-vintage-engine
-
-
- org.apache.commons
- commons-lang3
-
-
+
+
+ org.junit.vintage
+ junit-vintage-engine
+
+
+ org.apache.commons
+ commons-lang3
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/maven-profiles/pom.xml b/maven-modules/maven-simple/maven-profiles/pom.xml
index 1168350de9..322dada104 100644
--- a/maven-modules/maven-simple/maven-profiles/pom.xml
+++ b/maven-modules/maven-simple/maven-profiles/pom.xml
@@ -1,96 +1,96 @@
- 4.0.0
- com.baeldung
- maven-profiles
- 0.0.1-SNAPSHOT
- maven-profiles
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ maven-profiles
+ 0.0.1-SNAPSHOT
+ maven-profiles
-
-
- no-tests
-
- true
-
-
-
- integration-tests
-
- true
-
-
-
- mutation-tests
-
-
- active-on-jdk-11
-
- 11
-
-
-
- active-on-windows-10
-
-
- windows 10
- Windows
- amd64
- 10.0
-
-
-
-
- active-on-property-environment
-
-
- environment
- !test
-
-
-
-
- active-on-missing-file
-
-
- target/testreport.html
-
-
-
-
- active-on-present-file
-
-
- target/artifact.jar
-
-
-
-
- show-active-profiles
-
-
-
- org.apache.maven.plugins
- maven-help-plugin
- ${help.plugin.version}
-
-
- show-profiles
- compile
-
- active-profiles
-
-
-
-
-
-
-
-
+
+
+ no-tests
+
+ true
+
+
+
+ integration-tests
+
+ true
+
+
+
+ mutation-tests
+
+
+ active-on-jdk-11
+
+ 11
+
+
+
+ active-on-windows-10
+
+
+ windows 10
+ Windows
+ amd64
+ 10.0
+
+
+
+
+ active-on-property-environment
+
+
+ environment
+ !test
+
+
+
+
+ active-on-missing-file
+
+
+ target/testreport.html
+
+
+
+
+ active-on-present-file
+
+
+ target/artifact.jar
+
+
+
+
+ show-active-profiles
+
+
+
+ org.apache.maven.plugins
+ maven-help-plugin
+ ${help.plugin.version}
+
+
+ show-profiles
+ compile
+
+ active-profiles
+
+
+
+
+
+
+
+
-
- 3.2.0
-
+
+ 3.2.0
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/parent-project/core/pom.xml b/maven-modules/maven-simple/parent-project/core/pom.xml
index 5ae3f6a0bb..ec25c9ace5 100644
--- a/maven-modules/maven-simple/parent-project/core/pom.xml
+++ b/maven-modules/maven-simple/parent-project/core/pom.xml
@@ -1,16 +1,16 @@
- 4.0.0
- org.baeldung
- core
- core
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ org.baeldung
+ core
+ core
-
- parent-project
- com.baeldung
- 1.0-SNAPSHOT
-
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml
index 7d541a3353..a68f8e63bc 100644
--- a/maven-modules/maven-simple/parent-project/pom.xml
+++ b/maven-modules/maven-simple/parent-project/pom.xml
@@ -1,22 +1,22 @@
- 4.0.0
- parent-project
- 1.0-SNAPSHOT
- parent-project
- pom
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ parent-project
+ 1.0-SNAPSHOT
+ parent-project
+ pom
-
- com.baeldung
- maven-simple
- 0.0.1-SNAPSHOT
-
+
+ com.baeldung
+ maven-simple
+ 0.0.1-SNAPSHOT
+
-
- core
- service
- webapp
-
+
+ core
+ service
+ webapp
+
diff --git a/maven-modules/maven-simple/parent-project/service/pom.xml b/maven-modules/maven-simple/parent-project/service/pom.xml
index b20b3ad1d2..1953ec8638 100644
--- a/maven-modules/maven-simple/parent-project/service/pom.xml
+++ b/maven-modules/maven-simple/parent-project/service/pom.xml
@@ -1,16 +1,16 @@
- 4.0.0
- org.baeldung
- service
- service
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ org.baeldung
+ service
+ service
-
- parent-project
- com.baeldung
- 1.0-SNAPSHOT
-
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml
index 05594d0995..bd13c5aeb8 100644
--- a/maven-modules/maven-simple/parent-project/webapp/pom.xml
+++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml
@@ -1,16 +1,16 @@
- 4.0.0
- org.baeldung
- webapp
- webapp
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ org.baeldung
+ webapp
+ webapp
-
- parent-project
- com.baeldung
- 1.0-SNAPSHOT
-
+
+ parent-project
+ com.baeldung
+ 1.0-SNAPSHOT
+
diff --git a/maven-modules/maven-simple/plugin-management/pom.xml b/maven-modules/maven-simple/plugin-management/pom.xml
index 9ca65dd549..2fb2d5ed41 100644
--- a/maven-modules/maven-simple/plugin-management/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/pom.xml
@@ -1,63 +1,63 @@
- 4.0.0
- plugin-management
- pom
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ plugin-management
+ pom
-
- maven-simple
- com.baeldung
- 0.0.1-SNAPSHOT
-
+
+ maven-simple
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
-
- submodule-1
- submodule-2
-
+
+ submodule-1
+ submodule-2
+
-
-
-
-
- org.codehaus.mojo
- build-helper-maven-plugin
- ${maven.bulid.helper.plugin}
-
-
- add-resource
- generate-resources
-
- add-resource
-
-
-
-
- src/resources
- json
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven.compiler.plugin}
-
- 1.8
- 1.8
-
-
-
-
-
+
+
+
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ ${maven.bulid.helper.plugin}
+
+
+ add-resource
+ generate-resources
+
+ add-resource
+
+
+
+
+ src/resources
+ json
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.plugin}
+
+ 1.8
+ 1.8
+
+
+
+
+
-
- 3.8.1
- 3.2.0
-
+
+ 3.8.1
+ 3.2.0
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
index df460ec159..e50d3cc26d 100644
--- a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
@@ -1,14 +1,14 @@
- 4.0.0
- submodule-2
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ submodule-2
-
- plugin-management
- com.baeldung
- 0.0.1-SNAPSHOT
-
+
+ plugin-management
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml
index 78e4e8df46..938e2240f8 100644
--- a/maven-modules/maven-simple/pom.xml
+++ b/maven-modules/maven-simple/pom.xml
@@ -1,23 +1,23 @@
- 4.0.0
- maven-simple
- maven-simple
- pom
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ maven-simple
+ maven-simple
+ pom
-
- com.baeldung
- maven-modules
- 0.0.1-SNAPSHOT
-
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
-
- maven-profiles
- plugin-management
- maven-dependency
- parent-project
-
+
+ maven-profiles
+ plugin-management
+ maven-dependency
+ parent-project
+
\ No newline at end of file
From d1792871d58a5280ff18efb655a8614b97e8dc50 Mon Sep 17 00:00:00 2001
From: thibaultfaure
Date: Tue, 8 Feb 2022 19:11:06 -0300
Subject: [PATCH 094/235] =?UTF-8?q?Code=20for=20the=20Spring=20@Autowired?=
=?UTF-8?q?=20Field=20Null=20=E2=80=93=20Common=20Causes=20and=20Solutions?=
=?UTF-8?q?=20article=20(#11792)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
spring-5-autowiring-beans/pom.xml | 24 ++++++++++++++++
.../java/com/baeldung/autowiring/App.java | 14 ++++++++++
.../controller/CorrectController.java | 18 ++++++++++++
.../controller/FlawedController.java | 15 ++++++++++
.../autowiring/service/MyComponent.java | 10 +++++++
.../autowiring/service/MyService.java | 19 +++++++++++++
.../service/MyServiceConfiguration.java | 14 ++++++++++
.../CorrectControllerIntegrationTest.java | 23 +++++++++++++++
.../FlawedControllerIntegrationTest.java | 28 +++++++++++++++++++
9 files changed, 165 insertions(+)
create mode 100644 spring-5-autowiring-beans/pom.xml
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
create mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
create mode 100644 spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
create mode 100644 spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
diff --git a/spring-5-autowiring-beans/pom.xml b/spring-5-autowiring-beans/pom.xml
new file mode 100644
index 0000000000..32b56cc9ad
--- /dev/null
+++ b/spring-5-autowiring-beans/pom.xml
@@ -0,0 +1,24 @@
+
+
+ 4.0.0
+ spring-5-autowiring-beans
+ 0.0.1-SNAPSHOT
+ spring-5-autowiring-beans
+
+
+ com.baeldung
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
new file mode 100644
index 0000000000..d2d0db7a60
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
@@ -0,0 +1,14 @@
+package com.baeldung.autowiring;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+public class App {
+
+ public static void main(String[] args) {
+ SpringApplication.run(App.class, args);
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
new file mode 100644
index 0000000000..e0c0d7eeac
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
@@ -0,0 +1,18 @@
+package com.baeldung.autowiring.controller;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+
+import com.baeldung.autowiring.service.MyService;
+
+@Controller
+public class CorrectController {
+
+ @Autowired
+ MyService myService;
+
+ public String control() {
+ return myService.serve();
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
new file mode 100644
index 0000000000..673e686f79
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
@@ -0,0 +1,15 @@
+package com.baeldung.autowiring.controller;
+
+import org.springframework.stereotype.Controller;
+
+import com.baeldung.autowiring.service.MyService;
+
+@Controller
+public class FlawedController {
+
+ public String control() {
+ MyService userService = new MyService();
+ return userService.serve();
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
new file mode 100644
index 0000000000..c04ca3f4ba
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
@@ -0,0 +1,10 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class MyComponent {
+
+ public void doWork() {}
+
+}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
new file mode 100644
index 0000000000..3443dc05de
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
@@ -0,0 +1,19 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * The bean corresponding to this class is defined in MyServiceConfiguration
+ * Alternatively, you could choose to decorate this class with @Component or @Service
+ */
+public class MyService {
+
+ @Autowired
+ MyComponent myComponent;
+
+ public String serve() {
+ myComponent.doWork();
+ return "success";
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
new file mode 100644
index 0000000000..e30e4f770e
--- /dev/null
+++ b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
@@ -0,0 +1,14 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class MyServiceConfiguration {
+
+ @Bean
+ MyService myService() {
+ return new MyService();
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
new file mode 100644
index 0000000000..3807641edd
--- /dev/null
+++ b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
@@ -0,0 +1,23 @@
+package com.baeldung.autowiring.controller;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest
+public class CorrectControllerIntegrationTest {
+
+ @Autowired
+ CorrectController controller;
+
+ @Test
+ void whenControl_ThenRunSuccessfully() {
+ assertDoesNotThrow(() -> controller.control());
+ }
+
+}
diff --git a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
new file mode 100644
index 0000000000..79d446604f
--- /dev/null
+++ b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.autowiring.controller;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest
+public class FlawedControllerIntegrationTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(FlawedControllerIntegrationTest.class);
+
+ @Autowired
+ FlawedController myController;
+
+ @Test
+ void whenControl_ThenThrowNullPointerException() {
+ NullPointerException npe = assertThrows(NullPointerException.class, () -> myController.control());
+ LOGGER.error("Got a NullPointerException", npe);
+ }
+
+}
From 02bfadafc027252744f0a923ebe26de30572565a Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 13:53:54 +0800
Subject: [PATCH 095/235] Update README.md
---
spring-boot-modules/spring-boot-swagger/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-boot-modules/spring-boot-swagger/README.md b/spring-boot-modules/spring-boot-swagger/README.md
index ef33be8e07..e0cbc0c62a 100644
--- a/spring-boot-modules/spring-boot-swagger/README.md
+++ b/spring-boot-modules/spring-boot-swagger/README.md
@@ -3,3 +3,4 @@
- [Hiding Endpoints From Swagger Documentation in Spring Boot](https://www.baeldung.com/spring-swagger-hiding-endpoints)
- [Swagger @Api Description Is Deprecated](https://www.baeldung.com/java-swagger-api-description-deprecated)
- [Generate PDF from Swagger API Documentation](https://www.baeldung.com/swagger-generate-pdf)
+- [Remove Basic Error Controller In SpringFox Swagger-UI](https://www.baeldung.com/spring-swagger-remove-error-controller)
From d58a355efbd8768c48967a1020670d7d35935cd7 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 13:54:57 +0800
Subject: [PATCH 096/235] Update README.md
---
spring-sleuth/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-sleuth/README.md b/spring-sleuth/README.md
index ebaebde6c9..0740b0f6a6 100644
--- a/spring-sleuth/README.md
+++ b/spring-sleuth/README.md
@@ -5,3 +5,4 @@ This module contains articles about Spring Cloud Sleuth
### Relevant articles:
- [Spring Cloud Sleuth in a Monolith Application](https://www.baeldung.com/spring-cloud-sleuth-single-application)
+- [Get Current Trace ID in Spring Cloud Sleuth](https://www.baeldung.com/spring-cloud-sleuth-get-trace-id)
From 2e25f0b294a47bf5a03cd337ec7fef080d8961fb Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 13:55:59 +0800
Subject: [PATCH 097/235] Update README.md
---
logging-modules/log4j2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md
index 06f218f469..f53df508bf 100644
--- a/logging-modules/log4j2/README.md
+++ b/logging-modules/log4j2/README.md
@@ -7,3 +7,4 @@
- [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output)
- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers)
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)
+- [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info)
From c5218dfec6d93638cc0e176b2d9cc871f78cb859 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 13:57:22 +0800
Subject: [PATCH 098/235] Update README.md
---
javaxval/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/javaxval/README.md b/javaxval/README.md
index cc237e1e59..24c2cf98c5 100644
--- a/javaxval/README.md
+++ b/javaxval/README.md
@@ -11,3 +11,4 @@ This module contains articles about Bean Validation.
- [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups)
- [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums)
- [Guide to ParameterMessageInterpolator](https://www.baeldung.com/hibernate-parametermessageinterpolator)
+- [Hibernate Validator Annotation Processor in Depth](https://www.baeldung.com/hibernate-validator-annotation-processor)
From e541f200955d021a6c2c053aff6c2b5b69f41827 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 13:58:25 +0800
Subject: [PATCH 099/235] Update README.md
---
spring-boot-modules/spring-boot-swagger/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-boot-modules/spring-boot-swagger/README.md b/spring-boot-modules/spring-boot-swagger/README.md
index e0cbc0c62a..174bfe626d 100644
--- a/spring-boot-modules/spring-boot-swagger/README.md
+++ b/spring-boot-modules/spring-boot-swagger/README.md
@@ -4,3 +4,4 @@
- [Swagger @Api Description Is Deprecated](https://www.baeldung.com/java-swagger-api-description-deprecated)
- [Generate PDF from Swagger API Documentation](https://www.baeldung.com/swagger-generate-pdf)
- [Remove Basic Error Controller In SpringFox Swagger-UI](https://www.baeldung.com/spring-swagger-remove-error-controller)
+- [Setting Example and Description with Swagger](https://www.baeldung.com/swagger-set-example-description)
From 6a1b6d6ced8712712eb3562dc2486faa9fa91e92 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 14:00:22 +0800
Subject: [PATCH 100/235] Update README.md
---
persistence-modules/core-java-persistence-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/persistence-modules/core-java-persistence-2/README.md b/persistence-modules/core-java-persistence-2/README.md
index 7b215bfef1..f245392cb3 100644
--- a/persistence-modules/core-java-persistence-2/README.md
+++ b/persistence-modules/core-java-persistence-2/README.md
@@ -5,3 +5,4 @@
- [How to Check if a Database Table Exists with JDBC](https://www.baeldung.com/jdbc-check-table-exists)
- [Inserting Null Into an Integer Column Using JDBC](https://www.baeldung.com/jdbc-insert-null-into-integer-column)
- [A Guide to Auto-Commit in JDBC](https://www.baeldung.com/java-jdbc-auto-commit)
+- [JDBC Connection Status](https://www.baeldung.com/jdbc-connection-status)
From ee5139b8fd90708c57742bd0bf6f1b45d59f78cd Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 14:03:10 +0800
Subject: [PATCH 101/235] Create README.md
---
spring-cloud/spring-cloud-zuul/spring-zuul-ui/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-ui/README.md
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/README.md b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/README.md
new file mode 100644
index 0000000000..91a0c5503b
--- /dev/null
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Customizing Zuul Exceptions](https://www.baeldung.com/zuul-customize-exception)
From 63ea5889d2c1904ef346bca1a75ed0b94e2922a4 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 9 Feb 2022 14:06:10 +0800
Subject: [PATCH 102/235] Create README.md
---
core-java-modules/core-java-exceptions-4/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 core-java-modules/core-java-exceptions-4/README.md
diff --git a/core-java-modules/core-java-exceptions-4/README.md b/core-java-modules/core-java-exceptions-4/README.md
new file mode 100644
index 0000000000..259feb685c
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Java ArrayIndexOutOfBoundsException](https://www.baeldung.com/java-arrayindexoutofboundsexception)
From 5da21d6bba964c02f0a3936149ff5b0674f5282f Mon Sep 17 00:00:00 2001
From: Palaniappan Arunachalam
Date: Wed, 9 Feb 2022 13:21:48 +0530
Subject: [PATCH 103/235] Revert "Implementation for Simple Hexagonal
Architecture"
This reverts commit ad893be8ac4d6fea0f1e2799cad6b3c8c3ba40c1.
---
.../ConferenceApplication.java | 15 --
.../controllers/SessionController.java | 54 --------
.../controllers/SpeakerController.java | 57 --------
.../simplehexagonal/domain/Session.java | 58 --------
.../simplehexagonal/domain/Speaker.java | 90 ------------
.../domain/repository/SessionRepository.java | 17 ---
.../domain/repository/SpeakerRepository.java | 17 ---
.../domain/services/SessionService.java | 19 ---
.../domain/services/SessionServiceImpl.java | 40 ------
.../domain/services/SpeakerService.java | 19 ---
.../domain/services/SpeakerServiceImpl.java | 39 ------
.../config/BeanConfiguration.java | 30 ----
.../repositories/SessionEntity.java | 99 --------------
.../repositories/SessionJpaRepository.java | 9 --
.../repositories/SessionRepositoryImpl.java | 42 ------
.../repositories/SpeakerEntity.java | 129 ------------------
.../repositories/SpeakerJpaRepository.java | 9 --
.../repositories/SpeakerRepositoryImpl.java | 42 ------
.../resources/simple-hexagonal.properties | 8 --
.../services/SessionServiceUnitTest.java | 74 ----------
.../services/SpeakerServiceUnitTest.java | 74 ----------
21 files changed, 941 deletions(-)
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
delete mode 100644 ddd/src/main/resources/simple-hexagonal.properties
delete mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
delete mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
deleted file mode 100644
index 106b013ab6..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.baeldung.simplehexagonal;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.annotation.PropertySource;
-
-@SpringBootApplication(scanBasePackages = "com.baeldung.simplehexagonal")
-@PropertySource(value = { "classpath:simple-hexagonal.properties" })
-public class ConferenceApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(ConferenceApplication.class, args);
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
deleted file mode 100644
index 5cc3880851..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.baeldung.simplehexagonal.application.controllers;
-
-import java.util.List;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.baeldung.simplehexagonal.domain.Session;
-import com.baeldung.simplehexagonal.domain.services.SessionService;
-
-@RestController
-@RequestMapping("/api/v1/sessions")
-public class SessionController {
-
- private SessionService sessionService;
-
- @Autowired
- public SessionController(SessionService sessionService) {
- this.sessionService = sessionService;
- }
-
- @GetMapping
- public List findAll() {
- return sessionService.findAll();
- }
-
- @GetMapping
- @RequestMapping("{id}")
- public Session get(@PathVariable Long id) {
- return sessionService.get(id);
- }
-
- @PostMapping
- public Session create(@RequestBody final Session session) {
- return sessionService.create(session);
- }
-
- @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
- public void delete(@PathVariable Long id) {
- sessionService.delete(id);
- }
-
- @RequestMapping(value = "{id}", method = RequestMethod.PUT)
- public Session update(@PathVariable Long id, @RequestBody Session session) {
- return sessionService.update(id, session);
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
deleted file mode 100644
index bea5370da7..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.baeldung.simplehexagonal.application.controllers;
-
-import java.util.List;
-
-import org.springframework.beans.BeanUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-import com.baeldung.simplehexagonal.domain.services.SpeakerService;
-
-@RestController
-@RequestMapping("/api/v1/speakers")
-public class SpeakerController {
-
- private SpeakerService speakerService;
-
- @Autowired
- public SpeakerController(SpeakerService speakerService) {
- this.speakerService = speakerService;
- }
-
- @GetMapping
- public List findAll() {
- return speakerService.findAll();
- }
-
- @GetMapping
- @RequestMapping("{id}")
- public Speaker get(@PathVariable Long id) {
- return speakerService.get(id);
- }
-
- @PostMapping
- public Speaker create(@RequestBody final Speaker speaker) {
- return speakerService.save(speaker);
- }
-
- @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
- public void delete(@PathVariable Long id) {
- speakerService.delete(id);
- }
-
- @RequestMapping(value = "{id}", method = RequestMethod.PUT)
- public Speaker update(@PathVariable Long id, @RequestBody Speaker speaker) {
- Speaker currentSpeaker = speakerService.get(id);
- BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id");
- return speakerService.save(currentSpeaker);
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
deleted file mode 100644
index 93c88b1461..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.baeldung.simplehexagonal.domain;
-
-import java.util.List;
-
-public class Session {
-
- private Long sessionId;
-
- private String sessionName;
- private String sessionDescription;
- private Integer sessionLength;
-
- private List speakers;
-
- public Session() {
- }
-
- public Long getSessionId() {
- return sessionId;
- }
-
- public void setSessionId(Long sessionId) {
- this.sessionId = sessionId;
- }
-
- public String getSessionName() {
- return sessionName;
- }
-
- public void setSessionName(String sessionName) {
- this.sessionName = sessionName;
- }
-
- public String getSessionDescription() {
- return sessionDescription;
- }
-
- public void setSessionDescription(String sessionDescription) {
- this.sessionDescription = sessionDescription;
- }
-
- public Integer getSessionLength() {
- return sessionLength;
- }
-
- public void setSessionLength(Integer sessionLength) {
- this.sessionLength = sessionLength;
- }
-
- public List getSpeakers() {
- return speakers;
- }
-
- public void setSpeakers(List speakers) {
- this.speakers = speakers;
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
deleted file mode 100644
index 078c7d38f7..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package com.baeldung.simplehexagonal.domain;
-
-import java.util.List;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-public class Speaker {
-
- private Long speakerId;
-
- private String firstName;
- private String lastName;
- private String title;
- private String company;
- private String speakerBio;
-
- private byte[] speakerPhoto;
-
- @JsonIgnore
- private List sessions;
-
- public Speaker() {
-
- }
-
- public Long getSpeakerId() {
- return speakerId;
- }
-
- public void setSpeakerId(Long speakerId) {
- this.speakerId = speakerId;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getCompany() {
- return company;
- }
-
- public void setCompany(String company) {
- this.company = company;
- }
-
- public String getSpeakerBio() {
- return speakerBio;
- }
-
- public void setSpeakerBio(String speakerBio) {
- this.speakerBio = speakerBio;
- }
-
- public byte[] getSpeakerPhoto() {
- return speakerPhoto;
- }
-
- public void setSpeakerPhoto(byte[] speakerPhoto) {
- this.speakerPhoto = speakerPhoto;
- }
-
- public List getSessions() {
- return sessions;
- }
-
- public void setSessions(List sessions) {
- this.sessions = sessions;
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
deleted file mode 100644
index 7011506ffb..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.simplehexagonal.domain.repository;
-
-import java.util.List;
-
-import com.baeldung.simplehexagonal.domain.Session;
-
-public interface SessionRepository {
-
- List findAll();
-
- Session findById(Long id);
-
- Session save(Session session);
-
- void deleteById(Long id);
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
deleted file mode 100644
index a12863f85f..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.simplehexagonal.domain.repository;
-
-import java.util.List;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-
-public interface SpeakerRepository {
-
- List findAll();
-
- Speaker findById(Long id);
-
- Speaker save(Speaker Speaker);
-
- void deleteById(Long id);
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
deleted file mode 100644
index eff942672e..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import java.util.List;
-
-import com.baeldung.simplehexagonal.domain.Session;
-
-public interface SessionService {
-
- List findAll();
-
- Session get(Long id);
-
- Session create(Session session);
-
- void delete(Long id);
-
- Session update(Long id, Session session);
-
-}
\ No newline at end of file
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
deleted file mode 100644
index abf8ea1f86..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import java.util.List;
-
-import org.springframework.beans.BeanUtils;
-
-import com.baeldung.simplehexagonal.domain.Session;
-import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
-
-public class SessionServiceImpl implements SessionService {
-
- private SessionRepository sessionRepository;
-
- public SessionServiceImpl(SessionRepository sessionRepository) {
- this.sessionRepository = sessionRepository;
- }
-
- public List findAll() {
- return sessionRepository.findAll();
- }
-
- public Session get(Long id) {
- return sessionRepository.findById(id);
- }
-
- public Session create(Session session) {
- return sessionRepository.save(session);
- }
-
- public void delete(Long id) {
- sessionRepository.deleteById(id);
- }
-
- public Session update(Long id, Session session) {
- Session currentSession = sessionRepository.findById(id);
- BeanUtils.copyProperties(session, currentSession, "session_id");
- return sessionRepository.save(currentSession);
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
deleted file mode 100644
index 041fb24fe1..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import java.util.List;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-
-public interface SpeakerService {
-
- List findAll();
-
- Speaker get(Long id);
-
- Speaker save(Speaker speaker);
-
- void delete(Long id);
-
- Speaker update(Long id, Speaker speaker);
-
-}
\ No newline at end of file
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
deleted file mode 100644
index cf01259983..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import java.util.List;
-
-import org.springframework.beans.BeanUtils;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
-
-public class SpeakerServiceImpl implements SpeakerService {
-
- private SpeakerRepository speakerRepository;
-
- public SpeakerServiceImpl(SpeakerRepository speakerRepository) {
- this.speakerRepository = speakerRepository;
- }
-
- public List findAll() {
- return speakerRepository.findAll();
- }
-
- public Speaker get(Long id) {
- return speakerRepository.findById(id);
- }
-
- public Speaker save(Speaker speaker) {
- return speakerRepository.save(speaker);
- }
-
- public void delete(Long id) {
- speakerRepository.deleteById(id);
- }
-
- public Speaker update(Long id, Speaker speaker) {
- Speaker currentSpeaker = speakerRepository.findById(id);
- BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id");
- return speakerRepository.save(currentSpeaker);
- }
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
deleted file mode 100644
index c1875354d9..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.config;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
-
-import com.baeldung.simplehexagonal.ConferenceApplication;
-import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
-import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
-import com.baeldung.simplehexagonal.domain.services.SessionService;
-import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl;
-import com.baeldung.simplehexagonal.domain.services.SpeakerService;
-import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl;
-
-@Configuration
-@ComponentScan(basePackageClasses = ConferenceApplication.class)
-@EnableJpaRepositories(basePackages = "com.baeldung.simplehexagonal")
-public class BeanConfiguration {
-
- @Bean
- SessionService sessionService(SessionRepository sessionRepository) {
- return new SessionServiceImpl(sessionRepository);
- }
-
- @Bean
- SpeakerService speakerService(SpeakerRepository speakerRepository) {
- return new SpeakerServiceImpl(speakerRepository);
- }
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
deleted file mode 100644
index b9d9c765da..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import java.util.List;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-
-import com.baeldung.simplehexagonal.domain.Session;
-import com.baeldung.simplehexagonal.domain.Speaker;
-
-@Entity(name = "sessions")
-public class SessionEntity {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long session_id;
-
- private String session_name;
- private String session_description;
- private Integer session_length;
-
- @ManyToMany
- @JoinTable(name = "session_speakers", joinColumns = @JoinColumn(name = "session_id"), inverseJoinColumns = @JoinColumn(name = "speaker_id"))
- private List speakerEntities;
-
- public SessionEntity() {
- }
-
- public SessionEntity(Session session) {
- this.setSession_id(session.getSessionId());
- this.setSession_name(session.getSessionName());
- this.setSession_description(session.getSessionDescription());
- this.setSession_length(session.getSessionLength());
- List speakerEntities = session.getSpeakers()
- .stream()
- .map(it -> new SpeakerEntity(it))
- .toList();
- this.speakerEntities = speakerEntities;
- }
-
- public Session toSession() {
- Session session = new Session();
- session.setSessionId(session_id);
- session.setSessionName(session_name);
- session.setSessionDescription(session_description);
- session.setSessionLength(session_length);
- List speakers = speakerEntities.stream()
- .map(it -> it.toSpeaker())
- .toList();
- session.setSpeakers(speakers);
- return session;
- }
-
- public Long getSession_id() {
- return session_id;
- }
-
- public void setSession_id(Long session_id) {
- this.session_id = session_id;
- }
-
- public String getSession_name() {
- return session_name;
- }
-
- public void setSession_name(String session_name) {
- this.session_name = session_name;
- }
-
- public String getSession_description() {
- return session_description;
- }
-
- public void setSession_description(String session_description) {
- this.session_description = session_description;
- }
-
- public Integer getSession_length() {
- return session_length;
- }
-
- public void setSession_length(Integer session_length) {
- this.session_length = session_length;
- }
-
- public List getSpeakerEntities() {
- return speakerEntities;
- }
-
- public void setSpeakerEntities(List speakerEntities) {
- this.speakerEntities = speakerEntities;
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
deleted file mode 100644
index 83cc944dd6..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public interface SessionJpaRepository extends JpaRepository {
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
deleted file mode 100644
index 3af9021fff..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.baeldung.simplehexagonal.domain.Session;
-import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
-
-@Component
-public class SessionRepositoryImpl implements SessionRepository {
-
- @Autowired
- private SessionJpaRepository sessionJpaRepository;
-
- @Override
- public List findAll() {
- return sessionJpaRepository.findAll()
- .stream()
- .map(SessionEntity::toSession)
- .collect(Collectors.toList());
- }
-
- @Override
- public Session findById(Long id) {
- SessionEntity sessionEntity = sessionJpaRepository.getById(id);
- return sessionEntity.toSession();
- }
-
- @Override
- public Session save(Session session) {
- return sessionJpaRepository.saveAndFlush(new SessionEntity(session))
- .toSession();
- }
-
- public void deleteById(Long id) {
- sessionJpaRepository.deleteById(id);
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
deleted file mode 100644
index 8937ac578f..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import java.util.List;
-
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Lob;
-import javax.persistence.ManyToMany;
-
-import org.hibernate.annotations.Type;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-@Entity(name = "speakers")
-public class SpeakerEntity {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long speaker_id;
-
- private String first_name;
- private String last_name;
- private String title;
- private String company;
- private String speaker_bio;
-
- @Lob
- @Type(type = "org.hibernate.type.BinaryType")
- private byte[] speaker_photo;
-
- @JsonIgnore
- @ManyToMany(mappedBy = "speakerEntities", fetch = FetchType.LAZY)
- private List sessionEntities;
-
- public SpeakerEntity() {
-
- }
-
- public SpeakerEntity(Speaker speaker) {
- this.setSpeaker_id(speaker.getSpeakerId());
- this.setFirst_name(speaker.getFirstName());
- this.setLast_name(speaker.getLastName());
- this.setTitle(speaker.getTitle());
- this.setCompany(speaker.getCompany());
- this.setSpeaker_bio(speaker.getSpeakerBio());
- this.setSpeaker_photo(speaker.getSpeakerPhoto());
- }
-
- public Speaker toSpeaker() {
- Speaker speaker = new Speaker();
- speaker.setSpeakerId(speaker_id);
- speaker.setFirstName(first_name);
- speaker.setLastName(last_name);
- speaker.setTitle(title);
- speaker.setCompany(company);
- speaker.setSpeakerBio(speaker_bio);
- speaker.setSpeakerPhoto(speaker_photo);
- return speaker;
- }
-
- public Long getSpeaker_id() {
- return speaker_id;
- }
-
- public void setSpeaker_id(Long speaker_id) {
- this.speaker_id = speaker_id;
- }
-
- public String getFirst_name() {
- return first_name;
- }
-
- public void setFirst_name(String first_name) {
- this.first_name = first_name;
- }
-
- public String getLast_name() {
- return last_name;
- }
-
- public void setLast_name(String last_name) {
- this.last_name = last_name;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getCompany() {
- return company;
- }
-
- public void setCompany(String company) {
- this.company = company;
- }
-
- public String getSpeaker_bio() {
- return speaker_bio;
- }
-
- public void setSpeaker_bio(String speaker_bio) {
- this.speaker_bio = speaker_bio;
- }
-
- public byte[] getSpeaker_photo() {
- return speaker_photo;
- }
-
- public void setSpeaker_photo(byte[] speaker_photo) {
- this.speaker_photo = speaker_photo;
- }
-
- public List getSessionEntities() {
- return sessionEntities;
- }
-
- public void setSessionEntities(List sessionEntities) {
- this.sessionEntities = sessionEntities;
- }
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
deleted file mode 100644
index 9bbce066fb..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public interface SpeakerJpaRepository extends JpaRepository {
-
-}
diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
deleted file mode 100644
index 294bd0a1ff..0000000000
--- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.simplehexagonal.infrastructure.repositories;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
-
-@Component
-public class SpeakerRepositoryImpl implements SpeakerRepository {
-
- @Autowired
- private SpeakerJpaRepository speakerJpaRepository;
-
- @Override
- public List findAll() {
- return speakerJpaRepository.findAll()
- .stream()
- .map(SpeakerEntity::toSpeaker)
- .collect(Collectors.toList());
- }
-
- @Override
- public Speaker findById(Long id) {
- SpeakerEntity speakerEntity = speakerJpaRepository.getById(id);
- return speakerEntity.toSpeaker();
- }
-
- @Override
- public Speaker save(Speaker speaker) {
- return speakerJpaRepository.saveAndFlush(new SpeakerEntity(speaker))
- .toSpeaker();
- }
-
- public void deleteById(Long id) {
- speakerJpaRepository.deleteById(id);
- }
-
-}
diff --git a/ddd/src/main/resources/simple-hexagonal.properties b/ddd/src/main/resources/simple-hexagonal.properties
deleted file mode 100644
index 6277d15543..0000000000
--- a/ddd/src/main/resources/simple-hexagonal.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration
-spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
-spring.datasource.username=postgres
-spring.datasource.password=admin
-spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
-spring.jpa.hibernate.ddl-auto=none
-spring.jpa.show-sql=true
-spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
\ No newline at end of file
diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
deleted file mode 100644
index 3fdc34e402..0000000000
--- a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import static org.junit.jupiter.api.Assertions.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.springframework.util.Assert.notNull;
-
-import java.util.List;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-
-import com.baeldung.simplehexagonal.domain.Session;
-import com.baeldung.simplehexagonal.domain.repository.SessionRepository;
-import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl;
-
-public class SessionServiceUnitTest {
-
- private SessionServiceImpl sessionService;
-
- private SessionRepository sessionRepository;
-
- Session session;
-
- @BeforeEach
- void setUp() {
- sessionRepository = mock(SessionRepository.class);
- sessionService = new SessionServiceImpl(sessionRepository);
-
- session = new Session();
- session.setSessionId(1L);
- session.setSessionName("Introduction to Hexagonal Architecture");
- session.setSessionDescription("A quick and practical eample of Hexagonal Architecture");
- session.setSessionLength(30);
-
- when(sessionRepository.save(Mockito.any())).thenReturn(session);
- when(sessionRepository.findById(1L)).thenReturn(session);
- }
-
- @Test
- void testFindAll() {
- List list = sessionService.findAll();
- notNull(list, "should not return null");
- }
-
- @Test
- void testGet() {
- Session mySession = sessionService.get(1L);
- notNull(mySession, "should not return null");
- }
-
- @Test
- void testCreate() {
- session = sessionService.create(new Session());
- notNull(session.getSessionId(), "Id should be populated");
- }
-
- @Test
- void testDelete() {
- try {
- sessionService.delete(1L);
- } catch (Exception e) {
- fail("Should not throw error");
- }
- }
-
- @Test
- void testUpdate() {
- Session updatedSession = sessionService.update(1L, new Session());
- notNull(updatedSession, "Id should be populated");
- }
-
-}
diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
deleted file mode 100644
index 5fd3f9dcab..0000000000
--- a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.baeldung.simplehexagonal.domain.services;
-
-import static org.junit.jupiter.api.Assertions.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.springframework.util.Assert.notNull;
-
-import java.util.List;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-
-import com.baeldung.simplehexagonal.domain.Speaker;
-import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository;
-import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl;
-
-public class SpeakerServiceUnitTest {
-
- private SpeakerServiceImpl speakerService;
-
- private SpeakerRepository speakerRepository;
-
- Speaker speaker;
-
- @BeforeEach
- void setUp() {
- speakerRepository = mock(SpeakerRepository.class);
- speakerService = new SpeakerServiceImpl(speakerRepository);
-
- speaker = new Speaker();
- speaker.setSpeakerId(1L);
- speaker.setTitle("Mr");
- speaker.setFirstName("Palani");
- speaker.setLastName("Arun");
-
- when(speakerRepository.save(Mockito.any())).thenReturn(speaker);
- when(speakerRepository.findById(1L)).thenReturn(speaker);
- }
-
- @Test
- void testFindAll() {
- List list = speakerService.findAll();
- notNull(list, "should not return null");
- }
-
- @Test
- void testGet() {
- Speaker mySpeaker = speakerService.get(1L);
- notNull(mySpeaker, "should not return null");
- }
-
- @Test
- void testCreate() {
- speaker = speakerService.save(new Speaker());
- notNull(speaker.getSpeakerId(), "Id should be populated");
- }
-
- @Test
- void testDelete() {
- try {
- speakerService.delete(1L);
- } catch (Exception e) {
- fail("Should not throw error");
- }
- }
-
- @Test
- void testUpdate() {
- Speaker updatedSpeaker = speakerService.update(1L, new Speaker());
- notNull(updatedSpeaker, "Id should be populated");
- }
-
-}
From e4c615b52200ef94ce51669b9e443b6b33f4c1ae Mon Sep 17 00:00:00 2001
From: Palaniappan Arunachalam
Date: Wed, 9 Feb 2022 13:26:47 +0530
Subject: [PATCH 104/235] Revert "BAEL-5348: Invert a Map in Java + tests"
This reverts commit 3dd2802e2db7ad12994e16e79aa2a4ca2dadc202.
---
.../map/invert/InvertHashMapExample.java | 59 ------------------
.../map/invert/InvertHashMapExampleTest.java | 60 -------------------
2 files changed, 119 deletions(-)
delete mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
delete mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
deleted file mode 100644
index a203fd17c4..0000000000
--- a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.baeldung.map.invert;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-public class InvertHashMapExample {
-
- public static void main(String[] args) {
-
- Map map = new HashMap<>();
- map.put("first", 1);
- map.put("second", 2);
- System.out.println(map);
-
- invertMapUsingForLoop(map);
- invertMapUsingStreams(map);
- invertMapUsingMapper(map);
-
- map.put("two", 2);
- invertMapUsingGroupingBy(map);
- }
-
- public static Map invertMapUsingForLoop(Map map) {
- Map inversedMap = new HashMap();
- for (Entry entry : map.entrySet()) {
- inversedMap.put(entry.getValue(), entry.getKey());
- }
- System.out.println(inversedMap);
- return inversedMap;
- }
-
- public static Map invertMapUsingStreams(Map map) {
- Map inversedMap = map.entrySet()
- .stream()
- .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
- System.out.println(inversedMap);
- return inversedMap;
- }
-
- public static Map invertMapUsingMapper(Map sourceMap) {
- Map inversedMap = sourceMap.entrySet()
- .stream()
- .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
- System.out.println(inversedMap);
- return inversedMap;
- }
-
- public static Map> invertMapUsingGroupingBy(Map map) {
- Map> inversedMap = map.entrySet()
- .stream()
- .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
- System.out.println(inversedMap);
- return inversedMap;
- }
-
-}
diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
deleted file mode 100644
index aecfbfe675..0000000000
--- a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.baeldung.map.invert;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestInstance;
-
-@TestInstance(TestInstance.Lifecycle.PER_CLASS)
-public class InvertHashMapExampleTest {
-
- Map sourceMap;
-
- @BeforeAll
- void setup() {
- sourceMap = new HashMap<>();
- sourceMap.put("Sunday", 0);
- sourceMap.put("Monday", 1);
- }
-
- @Test
- void test1_invertMapUsingForLoop() {
- Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
- assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
- assertEquals("Monday", inversedMap.get(1));
- }
-
- @Test
- void test2_invertMapUsingStreams() {
- Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
- assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
- assertEquals("Monday", inversedMap.get(1));
- }
-
- @Test
- void test3_invertMapUsingMapper() {
- Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
- assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
- assertEquals("Monday", inversedMap.get(1));
- }
-
- @Test
- void test4_invertMapUsingGroupingBy() {
- sourceMap.put("monday", 1);
- Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
- assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
- assertTrue(inversedMap.get(1) instanceof List);
- }
-
-}
From 34aa920593fb808b6312eb7dd8e350a8066b8da5 Mon Sep 17 00:00:00 2001
From: sampadawagde
Date: Wed, 9 Feb 2022 16:09:44 +0530
Subject: [PATCH 105/235] JAVA-9825: Upgrade log4j version for modules that use
log4j-core library directly
---
apache-shiro/pom.xml | 2 +-
logging-modules/log-mdc/pom.xml | 2 +-
logging-modules/log4j/pom.xml | 4 ++--
logging-modules/log4j2/pom.xml | 2 +-
spring-4/pom.xml | 3 +++
spring-boot-modules/spring-boot-1/pom.xml | 2 +-
spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml | 1 +
testing-modules/junit-5/pom.xml | 2 +-
testing-modules/junit5-annotations/pom.xml | 2 +-
testing-modules/test-containers/pom.xml | 2 +-
10 files changed, 13 insertions(+), 9 deletions(-)
diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml
index 325a9939b9..850653ef98 100644
--- a/apache-shiro/pom.xml
+++ b/apache-shiro/pom.xml
@@ -47,7 +47,7 @@
1.5.3
- 1.2.17
+ 2.17.1
\ No newline at end of file
diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml
index a21b9a8fb7..c329a9dbdb 100644
--- a/logging-modules/log-mdc/pom.xml
+++ b/logging-modules/log-mdc/pom.xml
@@ -94,7 +94,7 @@
- 2.7
+ 2.17.1
3.3.6
3.3.0.Final
diff --git a/logging-modules/log4j/pom.xml b/logging-modules/log4j/pom.xml
index d3c7f8287e..ac7c8620cd 100644
--- a/logging-modules/log4j/pom.xml
+++ b/logging-modules/log4j/pom.xml
@@ -46,8 +46,8 @@
1.2.17
- 2.7
- 2.7
+ 2.17.1
+ 2.17.1
3.3.6
diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml
index 0b6fa9b902..c3a3f4e0f9 100644
--- a/logging-modules/log4j2/pom.xml
+++ b/logging-modules/log4j2/pom.xml
@@ -111,7 +111,7 @@
2.1.1
- 2.11.0
+ 2.17.1
yyyyMMddHHmmss
diff --git a/spring-4/pom.xml b/spring-4/pom.xml
index 41f55ea13b..5887bd43e2 100644
--- a/spring-4/pom.xml
+++ b/spring-4/pom.xml
@@ -74,10 +74,12 @@
org.apache.logging.log4j
log4j-api
+ ${log4j2.version}
org.apache.logging.log4j
log4j-core
+ ${log4j2.version}
org.easymock
@@ -115,6 +117,7 @@
3.6
2.4.0
4.0.3
+ 2.17.1
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml
index b6e3717f7c..594e6459a4 100644
--- a/spring-boot-modules/spring-boot-1/pom.xml
+++ b/spring-boot-modules/spring-boot-1/pom.xml
@@ -68,7 +68,7 @@
- 2.14.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
index 7dfb2c7436..bdd75d0635 100644
--- a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
+++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
@@ -45,6 +45,7 @@
2.0.0.RELEASE
3.4.13
+ 2.17.1
\ No newline at end of file
diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml
index 69382e5546..f794c3990f 100644
--- a/testing-modules/junit-5/pom.xml
+++ b/testing-modules/junit-5/pom.xml
@@ -134,7 +134,7 @@
- 2.8.2
+ 2.17.1
2.0.9
5.0.1.RELEASE
3.0.0-M3
diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml
index fad5402242..a4035a23f1 100644
--- a/testing-modules/junit5-annotations/pom.xml
+++ b/testing-modules/junit5-annotations/pom.xml
@@ -39,7 +39,7 @@
- 2.8.2
+ 2.17.1
\ No newline at end of file
diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml
index 3975b6df31..bd20035eab 100644
--- a/testing-modules/test-containers/pom.xml
+++ b/testing-modules/test-containers/pom.xml
@@ -70,7 +70,7 @@
1.5.0
- 2.12.0
+ 2.17.1
1.11.4
42.2.6
3.141.59
From 437c050aeed0543372e22d2a2c290b6195178eb3 Mon Sep 17 00:00:00 2001
From: Benjamin Caure
Date: Wed, 9 Feb 2022 16:48:33 +0100
Subject: [PATCH 106/235] BAEL-5188 Add CSRF cookie protection + test (#11775)
* BAEL-5188 Add CSRF cookie protection + test
* BAEL-5188 Break long lines of code
* BAEL-5188 Remove line-breaks before semi-colons
---
.../CsrfCookieEnabledIntegrationTest.java | 41 ++++++++++++
.../csrf/CsrfDisabledIntegrationTest.java | 17 ++++-
.../csrf/CsrfEnabledIntegrationTest.java | 19 +++++-
.../spring/SecurityWithCsrfConfig.java | 15 ++++-
.../spring/SecurityWithCsrfCookieConfig.java | 67 +++++++++++++++++++
.../spring/SecurityWithoutCsrfConfig.java | 15 ++++-
6 files changed, 164 insertions(+), 10 deletions(-)
create mode 100644 spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfCookieEnabledIntegrationTest.java
create mode 100644 spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfCookieEnabledIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfCookieEnabledIntegrationTest.java
new file mode 100644
index 0000000000..73f83f9b0c
--- /dev/null
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfCookieEnabledIntegrationTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.security.csrf;
+
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.baeldung.security.spring.SecurityWithCsrfCookieConfig;
+import com.baeldung.spring.MvcConfig;
+import org.junit.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.ContextConfiguration;
+
+@ContextConfiguration(classes = { SecurityWithCsrfCookieConfig.class, MvcConfig.class })
+public class CsrfCookieEnabledIntegrationTest extends CsrfAbstractIntegrationTest {
+
+ @Test
+ public void givenNoCsrf_whenAddFoo_thenForbidden() throws Exception {
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo())
+ .with(testUser()))
+ .andExpect(status().isForbidden());
+ // @formatter:on
+ }
+
+ @Test
+ public void givenCsrf_whenAddFoo_thenCreated() throws Exception {
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo())
+ .with(testUser())
+ .with(csrf()))
+ .andExpect(status().isCreated());
+ // @formatter:on
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
index a1c8be9daf..6dc01ab2bd 100644
--- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java
@@ -14,12 +14,25 @@ public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
@Test
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
- mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo()))
+ .andExpect(status().isUnauthorized());
+ // @formatter:on
}
@Test
public void givenAuth_whenAddFoo_thenCreated() throws Exception {
- mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo())
+ .with(testUser()))
+ .andExpect(status().isCreated());
+ // @formatter:on
}
}
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java
index 87e5005e17..50af9bba6f 100644
--- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java
@@ -15,12 +15,27 @@ public class CsrfEnabledIntegrationTest extends CsrfAbstractIntegrationTest {
@Test
public void givenNoCsrf_whenAddFoo_thenForbidden() throws Exception {
- mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden());
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo())
+ .with(testUser()))
+ .andExpect(status().isForbidden());
+ // @formatter:on
}
@Test
public void givenCsrf_whenAddFoo_thenCreated() throws Exception {
- mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated());
+ // @formatter:off
+ mvc
+ .perform(post("/auth/foos")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(createFoo())
+ .with(testUser())
+ .with(csrf()))
+ .andExpect(status().isCreated());
+ // @formatter:on
}
}
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java
index 9b3ac50546..4ec7a50abc 100644
--- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java
@@ -27,7 +27,17 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
+ // @formatter:off
+ auth
+ .inMemoryAuthentication()
+ .withUser("user1")
+ .password("user1Pass")
+ .authorities("ROLE_USER")
+ .and()
+ .withUser("admin")
+ .password("adminPass")
+ .authorities("ROLE_ADMIN");
+ // @formatter:on
}
@Override
@@ -45,8 +55,7 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter {
.and()
.httpBasic()
.and()
- .headers().cacheControl().disable()
- ;
+ .headers().cacheControl().disable();
// @formatter:on
}
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java
new file mode 100644
index 0000000000..5b58349629
--- /dev/null
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java
@@ -0,0 +1,67 @@
+package com.baeldung.security.spring;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
+
+@Configuration
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+public class SecurityWithCsrfCookieConfig extends WebSecurityConfigurerAdapter {
+
+ public SecurityWithCsrfCookieConfig() {
+ super();
+ }
+
+ @Bean("authenticationManager")
+ @Override
+ public AuthenticationManager authenticationManagerBean() throws Exception {
+ return super.authenticationManagerBean();
+ }
+
+ @Override
+ protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
+ // @formatter:off
+ auth
+ .inMemoryAuthentication()
+ .withUser("user1")
+ .password("user1Pass")
+ .authorities("ROLE_USER")
+ .and()
+ .withUser("admin")
+ .password("adminPass")
+ .authorities("ROLE_ADMIN");
+ // @formatter:on
+ }
+
+ @Override
+ public void configure(final WebSecurity web) throws Exception {
+ web.ignoring().antMatchers("/resources/**");
+ }
+
+ @Override
+ protected void configure(final HttpSecurity http) throws Exception {
+ // @formatter:off
+ http
+ .authorizeRequests()
+ .antMatchers("/auth/admin/*").hasAnyRole("ROLE_ADMIN")
+ .anyRequest().authenticated()
+ .and()
+ .httpBasic()
+ .and()
+ .headers().cacheControl().disable()
+ // Stateless API CSRF configuration
+ .and()
+ .csrf()
+ .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
+ // @formatter:on
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java
index 4a1263b498..bd9ca67ad5 100644
--- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java
+++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java
@@ -27,7 +27,17 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
+ // @formatter:off
+ auth
+ .inMemoryAuthentication()
+ .withUser("user1")
+ .password("user1Pass")
+ .authorities("ROLE_USER")
+ .and()
+ .withUser("admin")
+ .password("adminPass")
+ .authorities("ROLE_ADMIN");
+ // @formatter:on
}
@Override
@@ -47,8 +57,7 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
.and()
.headers().cacheControl().disable()
.and()
- .csrf().disable()
- ;
+ .csrf().disable();
// @formatter:on
}
From 4b1630dc3faee93d6821dc73b2c6f7704f39419e Mon Sep 17 00:00:00 2001
From: Palaniappan Arunachalam
Date: Wed, 9 Feb 2022 22:13:21 +0530
Subject: [PATCH 107/235] BAEL-5348: How to invert a Hashmap + tests
---
.../map/invert/InvertHashMapExample.java | 59 ++++++++++++++++++
.../map/invert/InvertHashMapUnitTest.java | 60 +++++++++++++++++++
2 files changed, 119 insertions(+)
create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
create mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
new file mode 100644
index 0000000000..a203fd17c4
--- /dev/null
+++ b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java
@@ -0,0 +1,59 @@
+package com.baeldung.map.invert;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
+public class InvertHashMapExample {
+
+ public static void main(String[] args) {
+
+ Map map = new HashMap<>();
+ map.put("first", 1);
+ map.put("second", 2);
+ System.out.println(map);
+
+ invertMapUsingForLoop(map);
+ invertMapUsingStreams(map);
+ invertMapUsingMapper(map);
+
+ map.put("two", 2);
+ invertMapUsingGroupingBy(map);
+ }
+
+ public static Map invertMapUsingForLoop(Map map) {
+ Map inversedMap = new HashMap();
+ for (Entry entry : map.entrySet()) {
+ inversedMap.put(entry.getValue(), entry.getKey());
+ }
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map invertMapUsingStreams(Map map) {
+ Map inversedMap = map.entrySet()
+ .stream()
+ .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map invertMapUsingMapper(Map sourceMap) {
+ Map inversedMap = sourceMap.entrySet()
+ .stream()
+ .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+ public static Map> invertMapUsingGroupingBy(Map map) {
+ Map> inversedMap = map.entrySet()
+ .stream()
+ .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
+ System.out.println(inversedMap);
+ return inversedMap;
+ }
+
+}
diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
new file mode 100644
index 0000000000..5759cc76d6
--- /dev/null
+++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.map.invert;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+public class InvertHashMapUnitTest {
+
+ Map sourceMap;
+
+ @BeforeAll
+ void setup() {
+ sourceMap = new HashMap<>();
+ sourceMap.put("Sunday", 0);
+ sourceMap.put("Monday", 1);
+ }
+
+ @Test
+ void test1_invertMapUsingForLoop() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test2_invertMapUsingStreams() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test3_invertMapUsingMapper() {
+ Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertEquals("Monday", inversedMap.get(1));
+ }
+
+ @Test
+ void test4_invertMapUsingGroupingBy() {
+ sourceMap.put("monday", 1);
+ Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
+ assertNotNull(inversedMap);
+ assertEquals(inversedMap.size(), 2);
+ assertTrue(inversedMap.get(1) instanceof List);
+ }
+
+}
From 3c701c53885d101efb3ecdf4e191ed95c8eabd1a Mon Sep 17 00:00:00 2001
From: Graham Cox
Date: Thu, 10 Feb 2022 07:32:33 +0000
Subject: [PATCH 108/235] Replaced tabs with spaces in auto-generated files
---
persistence-modules/fauna/pom.xml | 88 +++++++++----------
.../faunablog/FaunaBlogApplication.java | 6 +-
2 files changed, 47 insertions(+), 47 deletions(-)
diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml
index 72c0f0a751..67aabb7501 100644
--- a/persistence-modules/fauna/pom.xml
+++ b/persistence-modules/fauna/pom.xml
@@ -1,30 +1,30 @@
- 4.0.0
-
- org.springframework.boot
- spring-boot-starter-parent
- 2.6.2
-
-
- com.baeldung
- fauna-blog
- 0.0.1-SNAPSHOT
- fauna-blog
- Blogging Service built with FaunaDB
-
- 17
-
-
-
- org.springframework.boot
- spring-boot-starter-security
-
-
- org.springframework.boot
- spring-boot-starter-web
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.6.2
+
+
+ com.baeldung
+ fauna-blog
+ 0.0.1-SNAPSHOT
+ fauna-blog
+ Blogging Service built with FaunaDB
+
+ 17
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
com.faunadb
faunadb-java
@@ -32,25 +32,25 @@
compile
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
- org.springframework.security
- spring-security-test
- test
-
-
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
index f0ca6881b7..12739342bf 100644
--- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
+++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/FaunaBlogApplication.java
@@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FaunaBlogApplication {
- public static void main(String[] args) {
- SpringApplication.run(FaunaBlogApplication.class, args);
- }
+ public static void main(String[] args) {
+ SpringApplication.run(FaunaBlogApplication.class, args);
+ }
}
From a8a362dfcb7db5129d2aaf876b3b16e3d2be6ffd Mon Sep 17 00:00:00 2001
From: ashleyfrieze
Date: Fri, 11 Feb 2022 03:35:28 +0000
Subject: [PATCH 109/235] BAEL-5378 Rename exceptions to avoid confusion
(#11801)
---
.../webclient/status/WebClientStatusCodeHandler.java | 12 ++++++------
.../status/exception/BadRequestException.java | 7 -------
.../status/exception/CustomBadRequestException.java | 7 +++++++
.../status/exception/CustomServerErrorException.java | 7 +++++++
.../status/exception/ServerErrorException.java | 7 -------
5 files changed, 20 insertions(+), 20 deletions(-)
delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/BadRequestException.java
create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomBadRequestException.java
create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomServerErrorException.java
delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/ServerErrorException.java
diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/WebClientStatusCodeHandler.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/WebClientStatusCodeHandler.java
index 9594ca32f1..784fcf2812 100644
--- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/WebClientStatusCodeHandler.java
+++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/WebClientStatusCodeHandler.java
@@ -1,7 +1,7 @@
package com.baeldung.webclient.status;
-import com.baeldung.webclient.status.exception.BadRequestException;
-import com.baeldung.webclient.status.exception.ServerErrorException;
+import com.baeldung.webclient.status.exception.CustomBadRequestException;
+import com.baeldung.webclient.status.exception.CustomServerErrorException;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
@@ -32,10 +32,10 @@ public class WebClientStatusCodeHandler {
.retrieve()
.onStatus(
HttpStatus.INTERNAL_SERVER_ERROR::equals,
- response -> response.bodyToMono(String.class).map(ServerErrorException::new))
+ response -> response.bodyToMono(String.class).map(CustomServerErrorException::new))
.onStatus(
HttpStatus.BAD_REQUEST::equals,
- response -> response.bodyToMono(String.class).map(BadRequestException::new))
+ response -> response.bodyToMono(String.class).map(CustomBadRequestException::new))
.bodyToMono(String.class);
}
@@ -43,11 +43,11 @@ public class WebClientStatusCodeHandler {
HttpStatus status = response.statusCode();
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
return response.bodyToMono(String.class)
- .flatMap(body -> Mono.error(new ServerErrorException(body)));
+ .flatMap(body -> Mono.error(new CustomServerErrorException(body)));
}
if (HttpStatus.BAD_REQUEST.equals(status)) {
return response.bodyToMono(String.class)
- .flatMap(body -> Mono.error(new BadRequestException(body)));
+ .flatMap(body -> Mono.error(new CustomBadRequestException(body)));
}
return Mono.just(response);
}
diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/BadRequestException.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/BadRequestException.java
deleted file mode 100644
index bf5c599805..0000000000
--- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/BadRequestException.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.baeldung.webclient.status.exception;
-
-public class BadRequestException extends Exception {
- public BadRequestException(String message) {
- super(message);
- }
-}
diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomBadRequestException.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomBadRequestException.java
new file mode 100644
index 0000000000..ddc814b2d4
--- /dev/null
+++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomBadRequestException.java
@@ -0,0 +1,7 @@
+package com.baeldung.webclient.status.exception;
+
+public class CustomBadRequestException extends Exception {
+ public CustomBadRequestException(String message) {
+ super(message);
+ }
+}
diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomServerErrorException.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomServerErrorException.java
new file mode 100644
index 0000000000..12adbc94e4
--- /dev/null
+++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/CustomServerErrorException.java
@@ -0,0 +1,7 @@
+package com.baeldung.webclient.status.exception;
+
+public class CustomServerErrorException extends Exception {
+ public CustomServerErrorException(String message) {
+ super(message);
+ }
+}
diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/ServerErrorException.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/ServerErrorException.java
deleted file mode 100644
index 7e97f17dff..0000000000
--- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/status/exception/ServerErrorException.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.baeldung.webclient.status.exception;
-
-public class ServerErrorException extends Exception {
- public ServerErrorException(String message) {
- super(message);
- }
-}
From 7f84edf0f8885a5159f65c229b079a422c2b1da1 Mon Sep 17 00:00:00 2001
From: Ralf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com>
Date: Fri, 11 Feb 2022 20:49:43 +0100
Subject: [PATCH 110/235] BAEL-5323: Merge sources into existing persistence
module (#11804)
* BAEL-5323: Spring Boot with multiple data sources
* BAEL-5323: small fixes
* BAEL-5323: fix test class
* BAEL-5323: Refactor configuration classes
* BAEL-5323: Set proeprty to private
* BAEL-5323: rename test class to follow naming conventions
* BAEL-5323: merge sources into existing persistence module
* BAEL-5323: merge sources into existing persistence module
---
.local-db/todos.mv.db | Bin 0 -> 20480 bytes
.local-db/topics.mv.db | Bin 0 -> 16384 bytes
persistence-modules/spring-data-jdbc/pom.xml | 10 +++-
.../springdatajdbcintro/Application.java | 12 ++---
.../springdatajdbcintro/entity/Person.java | 2 +
.../repository/PersonRepository.java | 1 +
.../Application.java | 15 ++++++
.../springmultipledatasources/todos/Todo.java | 48 ++++++++++++++++++
.../todos/TodoDatasourceConfiguration.java | 28 ++++++++++
.../todos/TodoJpaConfiguration.java | 40 +++++++++++++++
.../todos/TodoRepository.java | 6 +++
.../topics/Topic.java | 39 ++++++++++++++
.../topics/TopicDatasourceConfiguration.java | 26 ++++++++++
.../topics/TopicJpaConfiguration.java | 41 +++++++++++++++
.../topics/TopicRepository.java | 6 +++
.../application-jdbcintro.properties | 6 +++
...application-multipledatasources.properties | 9 ++++
.../src/main/resources/application.properties | 7 +--
.../MultipleDatasourcesIntegrationTest.java | 41 +++++++++++++++
19 files changed, 324 insertions(+), 13 deletions(-)
create mode 100644 .local-db/todos.mv.db
create mode 100644 .local-db/topics.mv.db
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/Application.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoJpaConfiguration.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoRepository.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicDatasourceConfiguration.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicJpaConfiguration.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicRepository.java
create mode 100644 persistence-modules/spring-data-jdbc/src/main/resources/application-jdbcintro.properties
create mode 100644 persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
create mode 100644 persistence-modules/spring-data-jdbc/src/test/java/com/baeldung/springmultipledatasources/MultipleDatasourcesIntegrationTest.java
diff --git a/.local-db/todos.mv.db b/.local-db/todos.mv.db
new file mode 100644
index 0000000000000000000000000000000000000000..c081aa5aad90461a90d0c7fac9019601525a5933
GIT binary patch
literal 20480
zcmeI4PjA~c7{;T_TY+>L;KOdiz^ZMM0-hmJe=O@JTiPs4u`^5Ql3oH?qT8U3Y}igw
zbl0AC8#e6g?Yi5(!YGoK6fZ%sqD}+!^+BOU*?Re-6ytgL*gYFJMw4ms($@Ij@ca$2
zRYg%6$&1VErEN5l35hdXZ6tFNFG*^vEkbY`D@j5cf00e*l5C8%|00`U$0lvtuiwpp6Oh~@ee-Y1Yi*8@r8Vv$u^$pEFSDhspbb1|q+olp{nu7~>mD0G6N|sv
z=d|>u%C@|%v$nyuCfl~y*7`DwFGzDT9l7x`zQ1~M7|)9Kkc_`(`=>LKMe{gY#L1F|
z92Weg%Xl;)O{Mxo|B4-dnWfWU`n;)rk+W)Qze^l*8MWY;C+DxoA%(0o^41aKt1$TH
zRrr)A>%<(s#n_vws&MvL(HfW8<${JY+G8S`&hn|qWZ+_6aAjV86-9~MhpmgbUlo`2kBwAGM`LpXIvVZp^Bcu?0M_;YOH$?vT
zs6U91cjAXph~&_bQRoB_+E;PAZCGtBZ6_8^M&o_dbHX0lS5o?Q2Q^8I6q|;nrKz4;
zv4RaHZjD+P$1Q_s*f2ChH(N=&t;HiV9$8juD5J45PL+M+xQBkfUVDi4PV*|=&RI7Y
zgx;C!1-bv;7t0mQI`{?1WEd~*KKOKAhZWUqA?|8$0eub<$>D))oFhW23
zQ4guqS$ZR7rL&|7XNmhrcgJV(
zR$N(2|E=nM%tqmOy`!$G6?yk;ru*XmXzrta0-ts;L?8eJfB+Bx0zd!=0D*P=z0&`c
z@6nG;s{hGG_5b=BaK8Tk|AoS;_No-vglU2D<^N~f|A71l`7eKX`JYI$QvR!}fC&qY
zaQTl}`^I?5Ee1<|6GB^E%kSJQw0W>Z)kLa?-m2AL2{-jLQ%`uXq`iujlnIkk`8;M#Bzl`Y#+q6by?JeMBw-<{aLt@2?EgMHs
z&%L+(b1U`GVZcAus#>MWZZ40*FfhZ+n~wqOeR*$a%3?HM#BWTc-21a%h>0ah664pK
z>=OoNbEXFGm<|Hw3hY-0dlStFVbg{Y(bK3Zptk$zdM!TnTlE<&f$|PzUcOogO
zbFcvcAOHk_01yBIKmZ5;0U!VbfB+Bx0w0yY5d8m-${!{N0zd!=00AHX1b_e#00KY&
z2mk>f@DK#bkNmib0g%NxDL(bzhD%eYf00e*l5C8%|00_Jz+MYsg7Q)siE*U&Q`oF~@-+7i?_gj0X1gLI1l(HES*OtYKEm@a>-__NafzXz288
zZ&XM@+eZ5129_6~mrgK5nB(}rPQKv2Th7Wz1%c_;Xs1kejDL#h+-#tlN
zPYWGwr;X7RB$j%#Gv#a6Txwsi@0U!VbfB+Bx
a0zlwH6FBz2xBmY@9(`A%{=acg{{P=HZ%TOp
literal 0
HcmV?d00001
diff --git a/persistence-modules/spring-data-jdbc/pom.xml b/persistence-modules/spring-data-jdbc/pom.xml
index 2b4c6d21aa..168b171337 100644
--- a/persistence-modules/spring-data-jdbc/pom.xml
+++ b/persistence-modules/spring-data-jdbc/pom.xml
@@ -21,11 +21,19 @@
org.springframework.boot
spring-boot-starter-data-jdbc
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
com.h2database
h2
runtime
+
+ org.springframework.boot
+ spring-boot-starter-test
+
-
\ No newline at end of file
+
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java
index 8fff82de32..a808a3daea 100644
--- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java
@@ -1,17 +1,16 @@
package com.baeldung.springdatajdbcintro;
-import java.util.Optional;
-
+import ch.qos.logback.classic.Logger;
+import com.baeldung.springdatajdbcintro.entity.Person;
+import com.baeldung.springdatajdbcintro.repository.PersonRepository;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.core.env.AbstractEnvironment;
-import com.baeldung.springdatajdbcintro.entity.Person;
-import com.baeldung.springdatajdbcintro.repository.PersonRepository;
-
-import ch.qos.logback.classic.Logger;
+import java.util.Optional;
@SpringBootApplication
public class Application implements CommandLineRunner {
@@ -24,6 +23,7 @@ public class Application implements CommandLineRunner {
private DatabaseSeeder dbSeeder;
public static void main(String[] args) {
+ System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "jdbcintro");
SpringApplication.run(Application.class, args);
}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java
index 7c4c1eec73..ac2c329e08 100644
--- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java
@@ -1,7 +1,9 @@
package com.baeldung.springdatajdbcintro.entity;
import org.springframework.data.annotation.Id;
+import org.springframework.data.relational.core.mapping.Table;
+@Table
public class Person {
@Id
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java
index b2f026fa0c..ceb7a968a4 100644
--- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java
@@ -3,6 +3,7 @@ package com.baeldung.springdatajdbcintro.repository;
import com.baeldung.springdatajdbcintro.entity.Person;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
+import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/Application.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/Application.java
new file mode 100644
index 0000000000..a08949585c
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/Application.java
@@ -0,0 +1,15 @@
+package com.baeldung.springmultipledatasources;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.core.env.AbstractEnvironment;
+
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "multipledatasources");
+ SpringApplication.run(Application.class, args);
+ }
+
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java
new file mode 100644
index 0000000000..56f513027b
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java
@@ -0,0 +1,48 @@
+package com.baeldung.springmultipledatasources.todos;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Todo {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ private String title;
+ private boolean completed;
+
+ public Todo() {
+ }
+
+ public Todo(String title) {
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public boolean isCompleted() {
+ return completed;
+ }
+
+ public void setCompleted(boolean completed) {
+ this.completed = completed;
+ }
+
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
new file mode 100644
index 0000000000..b6a16eb7e4
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
@@ -0,0 +1,28 @@
+package com.baeldung.springmultipledatasources.todos;
+
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class TodoDatasourceConfiguration {
+
+ @Bean
+ @ConfigurationProperties("spring.datasource.todos")
+ public DataSourceProperties todosDataSourceProperties() {
+ return new DataSourceProperties();
+ }
+
+ @Bean
+ @Primary
+ public DataSource todosDataSource() {
+ return todosDataSourceProperties()
+ .initializeDataSourceBuilder()
+ .build();
+ }
+
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoJpaConfiguration.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoJpaConfiguration.java
new file mode 100644
index 0000000000..e1c4e1c9be
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoJpaConfiguration.java
@@ -0,0 +1,40 @@
+package com.baeldung.springmultipledatasources.todos;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Objects;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(
+ basePackageClasses = Todo.class,
+ entityManagerFactoryRef = "todosEntityManagerFactory",
+ transactionManagerRef = "todosTransactionManager"
+)
+public class TodoJpaConfiguration {
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean todosEntityManagerFactory(
+ @Qualifier("todosDataSource") DataSource dataSource,
+ EntityManagerFactoryBuilder builder) {
+ return builder
+ .dataSource(dataSource)
+ .packages(Todo.class)
+ .build();
+ }
+
+ @Bean
+ public PlatformTransactionManager todosTransactionManager(
+ @Qualifier("todosEntityManagerFactory") LocalContainerEntityManagerFactoryBean todosEntityManagerFactory) {
+ return new JpaTransactionManager(Objects.requireNonNull(todosEntityManagerFactory.getObject()));
+ }
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoRepository.java
new file mode 100644
index 0000000000..ebdd59551b
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoRepository.java
@@ -0,0 +1,6 @@
+package com.baeldung.springmultipledatasources.todos;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface TodoRepository extends JpaRepository {
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java
new file mode 100644
index 0000000000..390300ff1a
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java
@@ -0,0 +1,39 @@
+package com.baeldung.springmultipledatasources.topics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Topic {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ private String title;
+
+ public Topic() {
+ }
+
+ public Topic(String title) {
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicDatasourceConfiguration.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicDatasourceConfiguration.java
new file mode 100644
index 0000000000..38daa13d7d
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicDatasourceConfiguration.java
@@ -0,0 +1,26 @@
+package com.baeldung.springmultipledatasources.topics;
+
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class TopicDatasourceConfiguration {
+
+ @Bean
+ @ConfigurationProperties("spring.datasource.topics")
+ public DataSourceProperties topicsDataSourceProperties() {
+ return new DataSourceProperties();
+ }
+
+ @Bean
+ public DataSource topicsDataSource() {
+ return topicsDataSourceProperties()
+ .initializeDataSourceBuilder()
+ .build();
+ }
+
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicJpaConfiguration.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicJpaConfiguration.java
new file mode 100644
index 0000000000..a7daf54c07
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicJpaConfiguration.java
@@ -0,0 +1,41 @@
+package com.baeldung.springmultipledatasources.topics;
+
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Objects;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(
+ basePackageClasses = Topic.class,
+ entityManagerFactoryRef = "topicsEntityManagerFactory",
+ transactionManagerRef = "topicsTransactionManager"
+)
+public class TopicJpaConfiguration {
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory(
+ @Qualifier("topicsDataSource") DataSource dataSource,
+ EntityManagerFactoryBuilder builder
+ ) {
+ return builder
+ .dataSource(dataSource)
+ .packages(Topic.class)
+ .build();
+ }
+
+ @Bean
+ public PlatformTransactionManager topicsTransactionManager(
+ @Qualifier("topicsEntityManagerFactory") LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory) {
+ return new JpaTransactionManager(Objects.requireNonNull(topicsEntityManagerFactory.getObject()));
+ }
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicRepository.java
new file mode 100644
index 0000000000..5aebc3fe87
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/TopicRepository.java
@@ -0,0 +1,6 @@
+package com.baeldung.springmultipledatasources.topics;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface TopicRepository extends JpaRepository {
+}
diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/application-jdbcintro.properties b/persistence-modules/spring-data-jdbc/src/main/resources/application-jdbcintro.properties
new file mode 100644
index 0000000000..4980c71be4
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/resources/application-jdbcintro.properties
@@ -0,0 +1,6 @@
+#H2 DB
+spring.jpa.hibernate.ddl-auto=none
+spring.datasource.url=jdbc:h2:mem:persondb
+spring.datasource.driverClassName=org.h2.Driver
+spring.datasource.username=sa
+spring.datasource.password=test
diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties b/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
new file mode 100644
index 0000000000..0f2b643498
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
@@ -0,0 +1,9 @@
+spring.jpa.hibernate.ddl-auto=update
+spring.datasource.todos.url=jdbc:h2:mem:todos
+spring.datasource.todos.username=sa
+spring.datasource.todos.password=null
+spring.datasource.todos.driverClassName=org.h2.Driver
+spring.datasource.topics.url=jdbc:h2:mem:topics
+spring.datasource.topics.username=sa
+spring.datasource.topics.password=null
+spring.datasource.topics.driverClassName=org.h2.Driver
diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/application.properties b/persistence-modules/spring-data-jdbc/src/main/resources/application.properties
index 45099222fc..2a0c259c00 100644
--- a/persistence-modules/spring-data-jdbc/src/main/resources/application.properties
+++ b/persistence-modules/spring-data-jdbc/src/main/resources/application.properties
@@ -1,8 +1,3 @@
#H2 DB
-spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true
-spring.datasource.url=jdbc:h2:mem:persondb
-spring.datasource.driverClassName=org.h2.Driver
-spring.datasource.username=sa
-spring.datasource.password=test
-spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
\ No newline at end of file
+spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
diff --git a/persistence-modules/spring-data-jdbc/src/test/java/com/baeldung/springmultipledatasources/MultipleDatasourcesIntegrationTest.java b/persistence-modules/spring-data-jdbc/src/test/java/com/baeldung/springmultipledatasources/MultipleDatasourcesIntegrationTest.java
new file mode 100644
index 0000000000..4d401396a2
--- /dev/null
+++ b/persistence-modules/spring-data-jdbc/src/test/java/com/baeldung/springmultipledatasources/MultipleDatasourcesIntegrationTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.springmultipledatasources;
+
+import com.baeldung.springmultipledatasources.todos.Todo;
+import com.baeldung.springmultipledatasources.todos.TodoRepository;
+import com.baeldung.springmultipledatasources.topics.Topic;
+import com.baeldung.springmultipledatasources.topics.TopicRepository;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@ActiveProfiles("multipledatasources")
+@DataJpaTest // no test database!
+class MultipleDatasourcesIntegrationTest {
+
+ @Autowired
+ TodoRepository todoRepo;
+ @Autowired
+ TopicRepository topicRepo;
+
+ @Test
+ void shouldSaveTodoToTodoDB() {
+ Todo todo = new Todo("test");
+ Todo saved =todoRepo.save(todo);
+ Optional result= todoRepo.findById(saved.getId());
+ assertThat(result).isPresent();
+ }
+
+ @Test
+ void shouldSaveTopicToTopicDB() {
+ Topic todo = new Topic("test");
+ Topic saved =topicRepo.save(todo);
+ Optional result= topicRepo.findById(saved.getId());
+ assertThat(result).isPresent();
+ }
+
+}
From 13b769cd370c372a9e125ab268ec86e58b035f6f Mon Sep 17 00:00:00 2001
From: Abhinav Pandey
Date: Sun, 13 Feb 2022 14:31:17 +0530
Subject: [PATCH 111/235] BAEL-5340 - Spring security configuring ant matchers
---
.../AntMatchersExampleApplication.java | 13 +++++++
.../config/SecurityConfiguration.java | 39 +++++++++++++++++++
.../controllers/CustomerController.java | 15 +++++++
.../controllers/ProductController.java | 21 ++++++++++
.../baeldung/antmatchers/dtos/Customer.java | 39 +++++++++++++++++++
.../baeldung/antmatchers/dtos/Product.java | 39 +++++++++++++++++++
.../controllers/CustomerControllerTest.java | 38 ++++++++++++++++++
.../controllers/ProductControllerTest.java | 25 ++++++++++++
8 files changed, 229 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java
create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java
create mode 100644 spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java
create mode 100644 spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java
new file mode 100644
index 0000000000..0a7828eff4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.antmatchers;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class AntMatchersExampleApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(AntMatchersExampleApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java
new file mode 100644
index 0000000000..43e8c73bf0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java
@@ -0,0 +1,39 @@
+package com.baeldung.antmatchers.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+
+@Configuration
+public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+ @Override
+ public void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.inMemoryAuthentication()
+ .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN")
+ .and()
+ .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
+ }
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .antMatchers("/products/**").permitAll()
+ .and()
+ .authorizeRequests()
+ .antMatchers("/customers/**").hasRole("ADMIN")
+ .anyRequest().authenticated()
+ .and()
+ .httpBasic();
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java
new file mode 100644
index 0000000000..a031449797
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java
@@ -0,0 +1,15 @@
+package com.baeldung.antmatchers.controllers;
+
+import com.baeldung.antmatchers.dtos.Customer;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class CustomerController {
+
+ @GetMapping("/customers/{id}")
+ public Customer getCustomerById(@PathVariable("id") String id) {
+ return new Customer("Customer 1", "Address 1", "Phone 1");
+ }
+}
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java
new file mode 100644
index 0000000000..2968f3c025
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java
@@ -0,0 +1,21 @@
+package com.baeldung.antmatchers.controllers;
+
+import com.baeldung.antmatchers.dtos.Product;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@RestController
+public class ProductController {
+
+ @GetMapping("/products")
+ public List getProducts() {
+ return new ArrayList<>(Arrays.asList(
+ new Product("Product 1", "Description 1", 1.0),
+ new Product("Product 2", "Description 2", 2.0)
+ ));
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java
new file mode 100644
index 0000000000..64bd95b095
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java
@@ -0,0 +1,39 @@
+package com.baeldung.antmatchers.dtos;
+
+import java.io.Serializable;
+
+public class Customer implements Serializable {
+ private String name;
+ private String address;
+ private String phone;
+
+ public Customer(String name, String address, String phone) {
+ this.name = name;
+ this.address = address;
+ this.phone = phone;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java
new file mode 100644
index 0000000000..84073ee8c0
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java
@@ -0,0 +1,39 @@
+package com.baeldung.antmatchers.dtos;
+
+import java.io.Serializable;
+
+public class Product implements Serializable {
+ private String name;
+ private String description;
+ private double price;
+
+ public Product(String name, String description, double price) {
+ this.name = name;
+ this.description = description;
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public double getPrice() {
+ return price;
+ }
+
+ public void setPrice(double price) {
+ this.price = price;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java
new file mode 100644
index 0000000000..de13dc0aea
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.antmatchers.controllers;
+
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(value = CustomerController.class)
+class CustomerControllerIntegrationTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Test
+ void getCustomerByIdUnauthorized() throws Exception {
+ mockMvc.perform(get("/customers/1")).andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ void getCustomerByIdForbidden() throws Exception {
+ mockMvc.perform(get("/customers/1").with(user("user").roles("USER")))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void getCustomerByIdOk() throws Exception {
+ mockMvc.perform(get("/customers/1").with(user("admin").roles("ADMIN")))
+ .andExpect(status().isOk());
+ }
+
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java
new file mode 100644
index 0000000000..370e5f1597
--- /dev/null
+++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.antmatchers.controllers;
+
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(value = ProductController.class)
+class ProductControllerIntegrationTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Test
+ void getProducts() throws Exception {
+ mockMvc.perform(get("/products"))
+ .andExpect(status().isOk());
+ }
+}
\ No newline at end of file
From 7995f7d7c52963a557bca75e210842299464b89a Mon Sep 17 00:00:00 2001
From: Mayank Agarwal
Date: Sun, 13 Feb 2022 16:43:59 +0530
Subject: [PATCH 112/235] BAEL-5351: Moved to core-java-collections-4
---
.../com/baeldung/maps}/initialize/EmptyMapInitializer.java | 5 +++--
.../maps}/initialize/EmptyMapInitializerUnitTest.java | 2 +-
2 files changed, 4 insertions(+), 3 deletions(-)
rename core-java-modules/{core-java-collections-maps-2/src/main/java/com/baeldung/map => core-java-collections-4/src/main/java/com/baeldung/maps}/initialize/EmptyMapInitializer.java (91%)
rename core-java-modules/{core-java-collections-maps-2/src/test/java/com/baeldung/map => core-java-collections-4/src/test/java/com/baeldung/maps}/initialize/EmptyMapInitializerUnitTest.java (95%)
diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java
similarity index 91%
rename from core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
rename to core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java
index 06185a0f93..3dc644f1af 100644
--- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java
+++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java
@@ -1,4 +1,4 @@
-package com.baeldung.map.initialize;
+package com.baeldung.maps.initialize;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
@@ -33,7 +33,8 @@ public class EmptyMapInitializer {
}
public Map createGenericEmptyMapUsingMapsObject() {
- return Maps.newHashMap();
+ Map genericEmptyMap = Maps.newHashMap();
+ return genericEmptyMap;
}
public static Map createMapUsingGuava() {
diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java
similarity index 95%
rename from core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
rename to core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java
index b40ffed94b..cc25205ba7 100644
--- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java
+++ b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.map.initialize;
+package com.baeldung.maps.initialize;
import java.util.Map;
import org.junit.Test;
From a4639b70e8ea30ff1b85e0c91175d668737050db Mon Sep 17 00:00:00 2001
From: achraftt
Date: Sun, 13 Feb 2022 12:17:53 +0100
Subject: [PATCH 113/235] BAEL-5039: Add a new section on using a datepicker to
submit date values
---
.../thymeleaf/controller/DatesController.java | 15 +++++++
.../com/baeldung/thymeleaf/model/Student.java | 14 +++++++
.../WEB-INF/views/datePicker/displayDate.html | 12 ++++++
.../WEB-INF/views/datePicker/saveStudent.html | 42 +++++++++++++++++++
4 files changed, 83 insertions(+)
create mode 100644 spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
create mode 100644 spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java
index 20f5d02fed..61443a3631 100644
--- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java
+++ b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java
@@ -5,8 +5,10 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
+import com.baeldung.thymeleaf.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@@ -22,4 +24,17 @@ public class DatesController {
return "dates.html";
}
+ @RequestMapping(value = "/saveStudent", method = RequestMethod.GET)
+ public String displaySaveStudent(Model model) {
+ model.addAttribute("student", new Student());
+ return "datePicker/saveStudent.html";
+ }
+
+ @RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
+ public String saveStudent(Model model, @ModelAttribute("student") Student student) {
+ model.addAttribute("student", student);
+
+ return "datePicker/displayDate.html";
+ }
+
}
diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
index 202c04358a..c08985fd61 100644
--- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
+++ b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java
@@ -1,6 +1,9 @@
package com.baeldung.thymeleaf.model;
+import org.springframework.format.annotation.DateTimeFormat;
+
import java.io.Serializable;
+import java.util.Date;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@@ -24,6 +27,9 @@ public class Student implements Serializable {
@NotNull(message = "Student gender is required.")
private Character gender;
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
+ private Date birthDate;
+
private Float percentage;
public Integer getId() {
@@ -50,6 +56,14 @@ public class Student implements Serializable {
this.gender = gender;
}
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
public Float getPercentage() {
return percentage;
}
diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
new file mode 100644
index 0000000000..d3409f98f3
--- /dev/null
+++ b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
@@ -0,0 +1,12 @@
+
+
+
+
+Baeldung - using a datepicker to submit date
+
+
+ Student birth date
+
+
+
\ No newline at end of file
diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
new file mode 100644
index 0000000000..2faaed173c
--- /dev/null
+++ b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
@@ -0,0 +1,42 @@
+
+
+
+
+Baeldung - using a datepicker to submit date
+
+
+
+
+
\ No newline at end of file
From a6df0b9ff9accfab245a1b0fd14d23d91c70a57a Mon Sep 17 00:00:00 2001
From: Amitabh Tiwari
Date: Sun, 13 Feb 2022 19:04:52 +0530
Subject: [PATCH 114/235] Changes to fetch the Original Message
---
.../fileupload/config/ExceptionMessage.java | 55 +++++++++++++++++++
.../fileupload/config/FeignSupportConfig.java | 6 ++
.../config/RetreiveMessageErrorDecoder.java | 35 ++++++++++++
.../fileupload/controller/FileController.java | 5 ++
.../fileupload/service/UploadClient.java | 3 +
.../fileupload/service/UploadService.java | 4 ++
6 files changed, 108 insertions(+)
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java
create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java
new file mode 100644
index 0000000000..45a555b2ea
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java
@@ -0,0 +1,55 @@
+package com.baeldung.cloud.openfeign.fileupload.config;
+
+public class ExceptionMessage {
+ private String timestamp;
+ private int status;
+ private String error;
+ private String message;
+ private String path;
+
+ public String getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public int getStatus() {
+ return status;
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public void setError(String error) {
+ this.error = error;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ @Override
+ public String toString() {
+ return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java
index 943134213a..802077a3d7 100644
--- a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java
@@ -7,6 +7,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import feign.codec.Encoder;
+import feign.codec.ErrorDecoder;
import feign.form.spring.SpringFormEncoder;
public class FeignSupportConfig {
@@ -19,4 +20,9 @@ public class FeignSupportConfig {
}
}));
}
+
+ @Bean
+ public ErrorDecoder errorDecoder() {
+ return new RetreiveMessageErrorDecoder();
+ }
}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java
new file mode 100644
index 0000000000..09bf8bf54b
--- /dev/null
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java
@@ -0,0 +1,35 @@
+package com.baeldung.cloud.openfeign.fileupload.config;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import com.baeldung.cloud.openfeign.exception.BadRequestException;
+import com.baeldung.cloud.openfeign.exception.NotFoundException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import feign.Response;
+import feign.codec.ErrorDecoder;
+
+public class RetreiveMessageErrorDecoder implements ErrorDecoder {
+ private final ErrorDecoder errorDecoder = new Default();
+
+ @Override
+ public Exception decode(String methodKey, Response response) {
+ ExceptionMessage message = null;
+ try (InputStream bodyIs = response.body()
+ .asInputStream()) {
+ ObjectMapper mapper = new ObjectMapper();
+ message = mapper.readValue(bodyIs, ExceptionMessage.class);
+ } catch (IOException e) {
+ return new Exception(e.getMessage());
+ }
+ switch (response.status()) {
+ case 400:
+ return new BadRequestException(message.getMessage() != null ? message.getMessage() : "Bad Request");
+ case 404:
+ return new NotFoundException(message.getMessage() != null ? message.getMessage() : "Not found");
+ default:
+ return errorDecoder.decode(methodKey, response);
+ }
+ }
+}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java
index ebdf7ff6c8..1ddbfcea81 100644
--- a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java
@@ -25,4 +25,9 @@ public class FileController {
return service.uploadFileWithManualClient(file);
}
+ @PostMapping(value = "/upload-error")
+ public String handleFileUploadError(@RequestPart(value = "file") MultipartFile file) {
+ return service.uploadFile(file);
+ }
+
}
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java
index 63d17130e9..8f3ef7e421 100644
--- a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java
@@ -12,4 +12,7 @@ import com.baeldung.cloud.openfeign.fileupload.config.FeignSupportConfig;
public interface UploadClient {
@PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String fileUpload(@RequestPart(value = "file") MultipartFile file);
+
+ @PostMapping(value = "/upload-file-error", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ String fileUploadError(@RequestPart(value = "file") MultipartFile file);
}
diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java
index 7dd7f5a89c..742a37668b 100644
--- a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java
+++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java
@@ -26,4 +26,8 @@ public class UploadService {
return client.fileUpload(file);
}
+ public String uploadFileError(MultipartFile file) {
+ return client.fileUpload(file);
+ }
+
}
\ No newline at end of file
From 185266113c7d623faa8bee79aeb8de4578719cc1 Mon Sep 17 00:00:00 2001
From: msavic
Date: Sun, 13 Feb 2022 23:56:05 +0100
Subject: [PATCH 115/235] Caching Maven Dependencies with Docker
---
docker/docker-caching/multi-module/Dockerfile | 21 ++++++++
.../multi-module/Dockerfile-Buildkit | 13 +++++
.../multi-module/application/pom.xml | 36 +++++++++++++
.../MavenCachingApplication.java | 15 ++++++
.../src/main/resources/application.properties | 1 +
.../MavenCachingApplicationTests.java | 13 +++++
.../docker-caching/multi-module/core/pom.xml | 19 +++++++
.../com/baeldung/maven_caching/CoreClass.java | 8 +++
docker/docker-caching/multi-module/pom.xml | 38 +++++++++++++
.../docker-caching/single-module/Dockerfile | 15 ++++++
.../single-module/Dockerfile-Buildkit | 13 +++++
docker/docker-caching/single-module/pom.xml | 53 +++++++++++++++++++
.../maven_caching/MavenCachingMain.java | 11 ++++
13 files changed, 256 insertions(+)
create mode 100644 docker/docker-caching/multi-module/Dockerfile
create mode 100644 docker/docker-caching/multi-module/Dockerfile-Buildkit
create mode 100644 docker/docker-caching/multi-module/application/pom.xml
create mode 100644 docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
create mode 100644 docker/docker-caching/multi-module/application/src/main/resources/application.properties
create mode 100644 docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
create mode 100644 docker/docker-caching/multi-module/core/pom.xml
create mode 100644 docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
create mode 100644 docker/docker-caching/multi-module/pom.xml
create mode 100644 docker/docker-caching/single-module/Dockerfile
create mode 100644 docker/docker-caching/single-module/Dockerfile-Buildkit
create mode 100644 docker/docker-caching/single-module/pom.xml
create mode 100644 docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
diff --git a/docker/docker-caching/multi-module/Dockerfile b/docker/docker-caching/multi-module/Dockerfile
new file mode 100644
index 0000000000..1f0cc85f7c
--- /dev/null
+++ b/docker/docker-caching/multi-module/Dockerfile
@@ -0,0 +1,21 @@
+FROM maven:alpine as build
+ENV HOME=/usr/app
+RUN mkdir -p $HOME
+WORKDIR $HOME
+
+ADD pom.xml $HOME
+ADD core/pom.xml $HOME/core/pom.xml
+ADD application/pom.xml $HOME/application/pom.xml
+
+RUN mvn -pl core verify --fail-never
+ADD core $HOME/core
+RUN mvn -pl core install
+RUN mvn -pl application verify --fail-never
+ADD application $HOME/application
+RUN mvn -pl core,application package
+
+FROM openjdk:8-jdk-alpine
+
+COPY --from=build /usr/app/application/target/application-0.0.1-SNAPSHOT.jar /app/runner.jar
+
+ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/Dockerfile-Buildkit b/docker/docker-caching/multi-module/Dockerfile-Buildkit
new file mode 100644
index 0000000000..f51657c9ce
--- /dev/null
+++ b/docker/docker-caching/multi-module/Dockerfile-Buildkit
@@ -0,0 +1,13 @@
+FROM maven:alpine as build
+ENV HOME=/usr/app
+RUN mkdir -p $HOME
+WORKDIR $HOME
+
+ADD . $HOME
+RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
+
+FROM openjdk:8-jdk-alpine
+
+COPY --from=build /usr/app/application/target/application-0.0.1-SNAPSHOT.jar /app/runner.jar
+
+ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/application/pom.xml b/docker/docker-caching/multi-module/application/pom.xml
new file mode 100644
index 0000000000..49611e7fbd
--- /dev/null
+++ b/docker/docker-caching/multi-module/application/pom.xml
@@ -0,0 +1,36 @@
+
+
+
+ maven-caching
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+ application
+
+
+ com.baeldung
+ core
+ 0.0.1-SNAPSHOT
+
+
+
+
+ 8
+ 8
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java b/docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
new file mode 100644
index 0000000000..dec5453dc9
--- /dev/null
+++ b/docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.maven_caching;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class MavenCachingApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(MavenCachingApplication.class, args);
+ CoreClass cc = new CoreClass();
+ System.out.println(cc.method());
+ }
+
+}
diff --git a/docker/docker-caching/multi-module/application/src/main/resources/application.properties b/docker/docker-caching/multi-module/application/src/main/resources/application.properties
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/docker/docker-caching/multi-module/application/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java b/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
new file mode 100644
index 0000000000..ec550fb990
--- /dev/null
+++ b/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
@@ -0,0 +1,13 @@
+package com.baeldung.maven_caching;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class MavenCachingApplicationTests {
+
+ @Test
+ void contextLoads() {
+ }
+
+}
diff --git a/docker/docker-caching/multi-module/core/pom.xml b/docker/docker-caching/multi-module/core/pom.xml
new file mode 100644
index 0000000000..5df8ea7dde
--- /dev/null
+++ b/docker/docker-caching/multi-module/core/pom.xml
@@ -0,0 +1,19 @@
+
+
+
+ maven-caching
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+ core
+
+
+ 8
+ 8
+
+
+
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java b/docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
new file mode 100644
index 0000000000..a33624d4e7
--- /dev/null
+++ b/docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
@@ -0,0 +1,8 @@
+package com.baeldung.maven_caching;
+
+public class CoreClass {
+
+ public String method(){
+ return "Hello from core module!!";
+ }
+}
diff --git a/docker/docker-caching/multi-module/pom.xml b/docker/docker-caching/multi-module/pom.xml
new file mode 100644
index 0000000000..0cc309e2ad
--- /dev/null
+++ b/docker/docker-caching/multi-module/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+ pom
+
+ application
+ core
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.6.3
+
+
+ com.baeldung
+ maven-caching
+ 0.0.1-SNAPSHOT
+ maven-caching
+ maven-caching
+
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
diff --git a/docker/docker-caching/single-module/Dockerfile b/docker/docker-caching/single-module/Dockerfile
new file mode 100644
index 0000000000..309945440b
--- /dev/null
+++ b/docker/docker-caching/single-module/Dockerfile
@@ -0,0 +1,15 @@
+FROM maven:alpine as build
+ENV HOME=/usr/app
+RUN mkdir -p $HOME
+WORKDIR $HOME
+ADD pom.xml $HOME
+RUN mvn verify --fail-never
+
+ADD . $HOME
+RUN mvn package
+
+FROM openjdk:8-jdk-alpine
+
+COPY --from=build /usr/app/target/maven-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
+
+ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/single-module/Dockerfile-Buildkit b/docker/docker-caching/single-module/Dockerfile-Buildkit
new file mode 100644
index 0000000000..d3d2aad90d
--- /dev/null
+++ b/docker/docker-caching/single-module/Dockerfile-Buildkit
@@ -0,0 +1,13 @@
+FROM maven:alpine as build
+ENV HOME=/usr/app
+RUN mkdir -p $HOME
+WORKDIR $HOME
+ADD . $HOME
+
+RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
+
+FROM openjdk:8-jdk-alpine
+
+COPY --from=build /usr/app/target/maven-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
+
+ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/single-module/pom.xml b/docker/docker-caching/single-module/pom.xml
new file mode 100644
index 0000000000..54337436c5
--- /dev/null
+++ b/docker/docker-caching/single-module/pom.xml
@@ -0,0 +1,53 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ single-maven-caching
+ 1.0-SNAPSHOT
+
+
+ 8
+ 8
+
+
+
+
+ com.google.guava
+ guava
+ 31.0.1-jre
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 3.3.0
+
+
+ jar-with-dependencies
+
+
+
+ true
+ com.baeldung.maven_caching.MavenCachingMain
+
+
+
+
+
+ assemble-all
+ package
+
+ single
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java b/docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
new file mode 100644
index 0000000000..81673fd9ac
--- /dev/null
+++ b/docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
@@ -0,0 +1,11 @@
+package com.baeldung.maven_caching;
+
+import com.google.common.io.Files;
+
+public class MavenCachingMain {
+
+ public static void main(String[] args) {
+ System.out.println("Hello from maven_caching app!!!");
+ System.out.println(Files.simplifyPath("/home/app/test"));
+ }
+}
From 7a15270fc368677b08daffd4e40eee52f443729b Mon Sep 17 00:00:00 2001
From: thibaultfaure
Date: Mon, 14 Feb 2022 14:31:59 -0300
Subject: [PATCH 116/235] BAEL-5336 Move code for the article to spring-di-3
(#11807)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* JAVA-7535 Moved ebook specific code snippets to maven-simple module
* COMAUTO-9485 Fixed DB url in spring-project and added missing maven wrapper
* Code for the Spring @Autowired Field Null – Common Causes and Solutions article
* JAVA-7535 Added code for maven-multi-module
* JAVA-7535 Pom formatting
* JAVA-7535 Pom formatting
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* Create README.md
* Create README.md
* JAVA-9825: Upgrade log4j version for modules that use log4j-core library
directly
* BAEL-5188 Add CSRF cookie protection + test (#11775)
* BAEL-5188 Add CSRF cookie protection + test
* BAEL-5188 Break long lines of code
* BAEL-5188 Remove line-breaks before semi-colons
* BAEL-5378 Rename exceptions to avoid confusion (#11801)
* BAEL-5336 Move code for the article to spring-di-3
Co-authored-by: Dhawal Kapil
Co-authored-by: Dhawal Kapil
Co-authored-by: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Co-authored-by: sampadawagde
Co-authored-by: Benjamin Caure
Co-authored-by: ashleyfrieze
---
.../java/com/baeldung/autowiring/App.java | 14 ++++++++++
.../controller/CorrectController.java | 18 ++++++++++++
.../controller/FlawedController.java | 15 ++++++++++
.../autowiring/service/MyComponent.java | 10 +++++++
.../autowiring/service/MyService.java | 19 +++++++++++++
.../service/MyServiceConfiguration.java | 14 ++++++++++
.../CorrectControllerIntegrationTest.java | 23 +++++++++++++++
.../FlawedControllerIntegrationTest.java | 28 +++++++++++++++++++
8 files changed, 141 insertions(+)
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/App.java
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java
create mode 100644 spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
create mode 100644 spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
create mode 100644 spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/App.java b/spring-di-3/src/main/java/com/baeldung/autowiring/App.java
new file mode 100644
index 0000000000..d2d0db7a60
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/App.java
@@ -0,0 +1,14 @@
+package com.baeldung.autowiring;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+public class App {
+
+ public static void main(String[] args) {
+ SpringApplication.run(App.class, args);
+ }
+
+}
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java b/spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
new file mode 100644
index 0000000000..e0c0d7eeac
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
@@ -0,0 +1,18 @@
+package com.baeldung.autowiring.controller;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+
+import com.baeldung.autowiring.service.MyService;
+
+@Controller
+public class CorrectController {
+
+ @Autowired
+ MyService myService;
+
+ public String control() {
+ return myService.serve();
+ }
+
+}
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java b/spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
new file mode 100644
index 0000000000..673e686f79
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
@@ -0,0 +1,15 @@
+package com.baeldung.autowiring.controller;
+
+import org.springframework.stereotype.Controller;
+
+import com.baeldung.autowiring.service.MyService;
+
+@Controller
+public class FlawedController {
+
+ public String control() {
+ MyService userService = new MyService();
+ return userService.serve();
+ }
+
+}
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java
new file mode 100644
index 0000000000..c04ca3f4ba
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java
@@ -0,0 +1,10 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class MyComponent {
+
+ public void doWork() {}
+
+}
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java
new file mode 100644
index 0000000000..3443dc05de
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java
@@ -0,0 +1,19 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * The bean corresponding to this class is defined in MyServiceConfiguration
+ * Alternatively, you could choose to decorate this class with @Component or @Service
+ */
+public class MyService {
+
+ @Autowired
+ MyComponent myComponent;
+
+ public String serve() {
+ myComponent.doWork();
+ return "success";
+ }
+
+}
diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
new file mode 100644
index 0000000000..e30e4f770e
--- /dev/null
+++ b/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
@@ -0,0 +1,14 @@
+package com.baeldung.autowiring.service;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class MyServiceConfiguration {
+
+ @Bean
+ MyService myService() {
+ return new MyService();
+ }
+
+}
diff --git a/spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java b/spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
new file mode 100644
index 0000000000..3807641edd
--- /dev/null
+++ b/spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
@@ -0,0 +1,23 @@
+package com.baeldung.autowiring.controller;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest
+public class CorrectControllerIntegrationTest {
+
+ @Autowired
+ CorrectController controller;
+
+ @Test
+ void whenControl_ThenRunSuccessfully() {
+ assertDoesNotThrow(() -> controller.control());
+ }
+
+}
diff --git a/spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java b/spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
new file mode 100644
index 0000000000..79d446604f
--- /dev/null
+++ b/spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.autowiring.controller;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest
+public class FlawedControllerIntegrationTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(FlawedControllerIntegrationTest.class);
+
+ @Autowired
+ FlawedController myController;
+
+ @Test
+ void whenControl_ThenThrowNullPointerException() {
+ NullPointerException npe = assertThrows(NullPointerException.class, () -> myController.control());
+ LOGGER.error("Got a NullPointerException", npe);
+ }
+
+}
From fc4c77ed94c01d75860d92bda6398708e1735e57 Mon Sep 17 00:00:00 2001
From: Parikshit Murria
Date: Mon, 14 Feb 2022 12:43:32 -0500
Subject: [PATCH 117/235] BAEL-5326 - Documenting Enum in swagger using swagger
maven plugin (#11811)
* BAEL-5326 - Documenting Enum in swagger using swagger maven plugin
* BAEL-5326 - Documenting Enum in swagger using swagger maven plugin
Changes:
HireControllerTest -> HireControllerUnitTest
hireEmployee_RoleEngineer_ReturnsRoleString -> givenRoleEngineer_whenHireEmployee_thenReturnsRoleInString
* Moved to module: spring-boot-swagger
---
.../generated/swagger-ui/swagger.json | 57 +++++++++++++++++++
.../spring-boot-swagger/pom.xml | 44 ++++++++++++++
.../swaggerenums/SwaggerEnumsApplication.java | 13 +++++
.../controller/HireController.java | 22 +++++++
.../baeldung/swaggerenums/model/Employee.java | 17 ++++++
.../com/baeldung/swaggerenums/model/Role.java | 8 +++
.../controller/HireControllerUnitTest.java | 25 ++++++++
7 files changed, 186 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/SwaggerEnumsApplication.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/controller/HireController.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Employee.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Role.java
create mode 100644 spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerenums/controller/HireControllerUnitTest.java
diff --git a/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json b/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
new file mode 100644
index 0000000000..4ebe165384
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
@@ -0,0 +1,57 @@
+{
+ "swagger" : "2.0",
+ "info" : {
+ "description" : "This is a Baeldung Document Enum Sample Code",
+ "version" : "v1",
+ "title" : "Baeldung - Document Enum",
+ "contact" : {
+ "name" : "Parikshit Murria",
+ "email" : "pmurria@baeldung.com"
+ },
+ "license" : {
+ "name" : "Apache 2.0",
+ "url" : "https://www.apache.org/licenses/LICENSE-2.0.html"
+ }
+ },
+ "host" : "baeldung.com",
+ "basePath" : "/api",
+ "schemes" : [ "http", "https" ],
+ "paths" : {
+ "/hire" : {
+ "post" : {
+ "summary" : "This method is used to hire employee with a specific role",
+ "description" : "",
+ "operationId" : "hireEmployee",
+ "produces" : [ "application/json" ],
+ "parameters" : [ {
+ "in" : "body",
+ "name" : "body",
+ "description" : "role",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/definitions/Employee"
+ }
+ } ],
+ "responses" : {
+ "200" : {
+ "description" : "successful operation",
+ "schema" : {
+ "type" : "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "definitions" : {
+ "Employee" : {
+ "type" : "object",
+ "properties" : {
+ "role" : {
+ "type" : "string",
+ "enum" : [ "Engineer", "Clerk", "Driver", "Janitor" ]
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml
index d6b62bce3c..2c0e52b671 100644
--- a/spring-boot-modules/spring-boot-swagger/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger/pom.xml
@@ -25,6 +25,11 @@
springfox-boot-starter
${springfox.version}
+
+ com.github.kongchen
+ swagger-maven-plugin
+ ${swagger-maven-plugin.version}
+
@@ -33,11 +38,50 @@
org.springframework.boot
spring-boot-maven-plugin
+
+ com.github.kongchen
+ swagger-maven-plugin
+ ${swagger-maven-plugin.version}
+
+
+
+ false
+ com.baeldung.swaggerenums.controller
+ http,https
+ baeldung.com
+ /api
+
+ Baeldung - Document Enum
+ v1
+ This is a Baeldung Document Enum Sample Code
+
+ pmurria@baeldung.com
+ Parikshit Murria
+
+
+ https://www.apache.org/licenses/LICENSE-2.0.html
+ Apache 2.0
+
+
+ generated/swagger-ui
+
+
+
+
+
+ compile
+
+ generate
+
+
+
+
3.0.0
+ 3.1.1
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/SwaggerEnumsApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/SwaggerEnumsApplication.java
new file mode 100644
index 0000000000..0bb80df65f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/SwaggerEnumsApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerenums;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SwaggerEnumsApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SwaggerEnumsApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/controller/HireController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/controller/HireController.java
new file mode 100644
index 0000000000..7b7bfdc2c5
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/controller/HireController.java
@@ -0,0 +1,22 @@
+package com.baeldung.swaggerenums.controller;
+
+import com.baeldung.swaggerenums.model.Employee;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+
+@Api
+@Path(value="/hire")
+@Produces({"application/json"})
+public class HireController {
+
+ @POST
+ @ApiOperation(value = "This method is used to hire employee with a specific role")
+ public String hireEmployee(@ApiParam(value = "role", required = true) Employee employee) {
+ return String.format("Hired for role: %s", employee.role.name());
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Employee.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Employee.java
new file mode 100644
index 0000000000..ce9e5089c9
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Employee.java
@@ -0,0 +1,17 @@
+package com.baeldung.swaggerenums.model;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+@ApiModel
+public class Employee {
+ @ApiModelProperty
+ public Role role;
+
+ public Role getRole() {
+ return role;
+ }
+ public void setRole(Role role) {
+ this.role = role;
+ }
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Role.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Role.java
new file mode 100644
index 0000000000..fa62b2d0b5
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swaggerenums/model/Role.java
@@ -0,0 +1,8 @@
+package com.baeldung.swaggerenums.model;
+
+import io.swagger.annotations.ApiModel;
+
+@ApiModel
+public enum Role {
+ Engineer, Clerk, Driver, Janitor;
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerenums/controller/HireControllerUnitTest.java b/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerenums/controller/HireControllerUnitTest.java
new file mode 100644
index 0000000000..b2ec5ccaa5
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger/src/test/java/com/baeldung/swaggerenums/controller/HireControllerUnitTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.swaggerenums.controller;
+
+import com.baeldung.swaggerenums.model.Employee;
+import com.baeldung.swaggerenums.model.Role;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class HireControllerUnitTest {
+
+ @Test
+ public void givenRoleEngineer_whenHireEmployee_thenReturnsRoleInString() {
+ //Arrange
+ Role testRole = Role.Engineer;
+ Employee employee = new Employee();
+ employee.setRole(testRole);
+
+ //Act
+ HireController hireController = new HireController();
+ String response = hireController.hireEmployee(employee);
+
+ //Assert
+ Assert.assertEquals(String.format("Hired for role: %s", testRole),
+ response);
+ }
+}
From e5f1f8a3b6937c3dd4154a3d7669ac7ea2b8fe89 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Mon, 14 Feb 2022 21:15:53 +0000
Subject: [PATCH 118/235] [JAVA-9910] Update Cargo plugin to latest version
---
.../spring-rest-testing/pom.xml | 46 ++++++++++---------
.../baeldung/cargo/CargoPluginLiveTest.java | 13 ++++++
2 files changed, 38 insertions(+), 21 deletions(-)
create mode 100644 spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java
diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml
index 1390898bf9..67b3115a6f 100644
--- a/spring-web-modules/spring-rest-testing/pom.xml
+++ b/spring-web-modules/spring-rest-testing/pom.xml
@@ -64,11 +64,6 @@
org.springframework.data
spring-data-commons
-
-
- org.springframework.boot
- spring-boot-starter-tomcat
-
org.apache.httpcomponents
@@ -154,17 +149,9 @@
org.codehaus.cargo
- cargo-maven2-plugin
- ${cargo-maven2-plugin.version}
+ cargo-maven3-plugin
+ ${cargo-maven3-plugin.version}
- true
-
- jetty8x
- embedded
-
-
-
-
8082
@@ -194,15 +181,32 @@
- live
+ cargo-integration
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+ **/*LiveTest.java
+
+
+
+
+
org.codehaus.cargo
- cargo-maven2-plugin
-
- false
-
+ cargo-maven3-plugin
start-server
@@ -232,7 +236,7 @@
3.25.0-GA
- 1.6.1
+ 1.9.9
1.1.3
diff --git a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java b/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java
new file mode 100644
index 0000000000..8d6dd6a823
--- /dev/null
+++ b/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java
@@ -0,0 +1,13 @@
+package com.baeldung.cargo;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class CargoPluginLiveTest {
+
+ @Test
+ void givenCargoProfile_expectTestRuns() {
+ assertTrue(true);
+ }
+}
From a4a03c47900136dcdc4aa7cc494175e847fb982f Mon Sep 17 00:00:00 2001
From: Loredana Crusoveanu
Date: Tue, 15 Feb 2022 13:31:37 +0200
Subject: [PATCH 119/235] move remaining files for instrumentation article
---
core-java-modules/core-java-jar/pom.xml | 105 +---------------
core-java-modules/core-java-jvm/pom.xml | 114 ++++++++++++++++++
.../src/main/resources/META-INF/MANIFEST.MF | 5 +
3 files changed, 120 insertions(+), 104 deletions(-)
create mode 100644 core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF
diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml
index da107c745f..714a370287 100644
--- a/core-java-modules/core-java-jar/pom.xml
+++ b/core-java-modules/core-java-jar/pom.xml
@@ -259,110 +259,7 @@
-
-
- buildAgentLoader
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
- package
-
- jar
-
-
- agentLoader
- target/classes
-
-
- true
-
- ${project.build.outputDirectory}/META-INF/MANIFEST.MF
-
-
-
- com/baeldung/instrumentation/application/AgentLoader.class
- com/baeldung/instrumentation/application/Launcher.class
-
-
-
-
-
-
-
-
-
- buildApplication
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
- package
-
- jar
-
-
- application
- target/classes
-
-
- true
-
- ${project.build.outputDirectory}/META-INF/MANIFEST.MF
-
-
-
- com/baeldung/instrumentation/application/MyAtm.class
- com/baeldung/instrumentation/application/MyAtmApplication.class
- com/baeldung/instrumentation/application/Launcher.class
-
-
-
-
-
-
-
-
-
- buildAgent
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
- package
-
- jar
-
-
- agent
- target/classes
-
-
- true
-
- ${project.build.outputDirectory}/META-INF/MANIFEST.MF
-
-
-
- com/baeldung/instrumentation/agent/AtmTransformer.class
- com/baeldung/instrumentation/agent/MyInstrumentationAgent.class
-
-
-
-
-
-
-
-
+
diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml
index c47765e43d..216e408114 100644
--- a/core-java-modules/core-java-jvm/pom.xml
+++ b/core-java-modules/core-java-jvm/pom.xml
@@ -57,6 +57,11 @@
jol-core
${jol-core.version}
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
@@ -66,5 +71,114 @@
8.0.1
6.5.0
+
+
+
+ buildAgentLoader
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+ package
+
+ jar
+
+
+ agentLoader
+ target/classes
+
+
+ true
+com.baeldung.instrumentation.application.Launcher
+
+ ${project.build.outputDirectory}/META-INF/MANIFEST.MF
+
+
+
+ com/baeldung/instrumentation/application/AgentLoader.class
+ com/baeldung/instrumentation/application/Launcher.class
+
+
+
+
+
+
+
+
+
+ buildApplication
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+ package
+
+ jar
+
+
+ application
+ target/classes
+
+
+ true
+ com.baeldung.instrumentation.application.Launcher
+
+ ${project.build.outputDirectory}/META-INF/MANIFEST.MF
+
+
+
+ com/baeldung/instrumentation/application/MyAtm.class
+ com/baeldung/instrumentation/application/MyAtmApplication.class
+ com/baeldung/instrumentation/application/Launcher.class
+
+
+
+
+
+
+
+
+
+ buildAgent
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+ package
+
+ jar
+
+
+ agent
+ target/classes
+
+
+ true
+com.baeldung.instrumentation.application.Launcher
+
+ ${project.build.outputDirectory}/META-INF/MANIFEST.MF
+
+
+
+ com/baeldung/instrumentation/agent/AtmTransformer.class
+ com/baeldung/instrumentation/agent/MyInstrumentationAgent.class
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF b/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF
new file mode 100644
index 0000000000..d16a93ec83
--- /dev/null
+++ b/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF
@@ -0,0 +1,5 @@
+Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
+Can-Redefine-Classes: true
+Can-Retransform-Classes: true
+Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
+Main-Class: com.baeldung.instrumentation.application.Launcher
\ No newline at end of file
From 9dc5d75a160071c025bc48745f2e473cb0ce97d7 Mon Sep 17 00:00:00 2001
From: Loredana Crusoveanu
Date: Tue, 15 Feb 2022 13:39:08 +0200
Subject: [PATCH 120/235] formatting, additional details on how to run the app
---
core-java-modules/core-java-jvm/README.md | 10 ++++++++++
core-java-modules/core-java-jvm/pom.xml | 6 +++---
2 files changed, 13 insertions(+), 3 deletions(-)
diff --git a/core-java-modules/core-java-jvm/README.md b/core-java-modules/core-java-jvm/README.md
index 431cf021c8..e9266dea3b 100644
--- a/core-java-modules/core-java-jvm/README.md
+++ b/core-java-modules/core-java-jvm/README.md
@@ -15,3 +15,13 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread)
- [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode)
- More articles: [[next -->]](/core-java-modules/core-java-jvm-2)
+
+
+To run the code for the Instrumentation: https://www.baeldung.com/java-instrumentation article:
+1- build the module
+2- run the module 3 times to build the 3 jars:
+ mvn install -PbuildAgentLoader
+ mvn install -PbuildApplication
+ mvn install -PbuildAgent
+3- update the commands in the article with the exact names of the jars generated in the target folder
+4- update the path in the AgentLoader class with the path of the agent on your system
\ No newline at end of file
diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml
index 216e408114..e4c0f949c2 100644
--- a/core-java-modules/core-java-jvm/pom.xml
+++ b/core-java-modules/core-java-jvm/pom.xml
@@ -57,7 +57,7 @@
jol-core
${jol-core.version}
-
+
org.slf4j
log4j-over-slf4j
${org.slf4j.version}
@@ -92,7 +92,7 @@
true
-com.baeldung.instrumentation.application.Launcher
+ com.baeldung.instrumentation.application.Launcher
${project.build.outputDirectory}/META-INF/MANIFEST.MF
@@ -163,7 +163,7 @@
true
-com.baeldung.instrumentation.application.Launcher
+ com.baeldung.instrumentation.application.Launcher
${project.build.outputDirectory}/META-INF/MANIFEST.MF
From 9e4da20259db43a742eaa2648f2afa3030ce2cb0 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 15 Feb 2022 21:36:09 +0500
Subject: [PATCH 121/235] Updated README.md
Linked back to: https://www.baeldung.com/spring-no-converter-with-preset
---
spring-boot-modules/spring-boot-data-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md
index 875ee502b4..b99356492b 100644
--- a/spring-boot-modules/spring-boot-data-2/README.md
+++ b/spring-boot-modules/spring-boot-data-2/README.md
@@ -1,5 +1,6 @@
### Relevant Articles:
+- [HttpMessageNotWritableException: No Converter for [class …] With Preset Content-Type](https://www.baeldung.com/spring-no-converter-with-preset)
- [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper)
- [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found)
- [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository)
From b73253cfbcf7c98ad74a87c9221fe08f8a4e0886 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 15 Feb 2022 21:38:49 +0500
Subject: [PATCH 122/235] Updated README.md
Linked back to: https://www.baeldung.com/spring-boot-configure-multiple-datasources
---
persistence-modules/spring-data-jdbc/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/persistence-modules/spring-data-jdbc/README.md b/persistence-modules/spring-data-jdbc/README.md
index 0e54d0ba88..b9ff9417a9 100644
--- a/persistence-modules/spring-data-jdbc/README.md
+++ b/persistence-modules/spring-data-jdbc/README.md
@@ -1,3 +1,4 @@
### Relevant Articles:
+- [Configure and Use Multiple DataSources in Spring Boot](https://www.baeldung.com/spring-boot-configure-multiple-datasources)
- [Introduction to Spring Data JDBC](https://www.baeldung.com/spring-data-jdbc-intro)
From 5538a7686f0977e98364b19b5aadfed8dbb9db89 Mon Sep 17 00:00:00 2001
From: Palaniappan Arunachalam
Date: Tue, 15 Feb 2022 23:30:00 +0530
Subject: [PATCH 123/235] BAEL-5348: Fixed tests based on review comments
---
.../map/invert/InvertHashMapUnitTest.java | 36 ++++++++++++-------
1 file changed, 24 insertions(+), 12 deletions(-)
diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
index 5759cc76d6..6870cdef23 100644
--- a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
+++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java
@@ -1,5 +1,6 @@
package com.baeldung.map.invert;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -8,7 +9,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@@ -17,44 +18,55 @@ public class InvertHashMapUnitTest {
Map sourceMap;
- @BeforeAll
+ @BeforeEach
void setup() {
sourceMap = new HashMap<>();
sourceMap.put("Sunday", 0);
sourceMap.put("Monday", 1);
+ sourceMap.put("Tuesday", 2);
+ sourceMap.put("Wednesday", 3);
+ sourceMap.put("Thursday", 4);
+ sourceMap.put("Friday", 5);
+ sourceMap.put("Saturday", 6);
}
@Test
- void test1_invertMapUsingForLoop() {
+ void givenSourceMap_whenUsingForLoop_returnsInvertedMap() {
Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
+
assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
+ assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
- void test2_invertMapUsingStreams() {
+ void givenSourceMap_whenUsingStreams_returnsInvertedMap() {
Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
+
assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
+ assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
- void test3_invertMapUsingMapper() {
+ void givenSourceMap_whenUsingMapper_returnsInvertedMap() {
Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
+
assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
+ assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
- void test4_invertMapUsingGroupingBy() {
- sourceMap.put("monday", 1);
+ void givenSourceMapWithDuplicateValues_whenUsingGroupBy_returnsInvertedMap() {
+ sourceMap.put("MONDAY", 1);
Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
+
assertNotNull(inversedMap);
- assertEquals(inversedMap.size(), 2);
- assertTrue(inversedMap.get(1) instanceof List);
+ assertNotEquals(sourceMap.size(), inversedMap.size()); // duplicate keys are merged now
+ assertEquals(2, inversedMap.get(1).size());
+ assertTrue(inversedMap.get(1).contains("Monday"));
+ assertTrue(inversedMap.get(1).contains("MONDAY"));
}
}
From 864b139aa4961c64f0aee37250616d44b608b557 Mon Sep 17 00:00:00 2001
From: vunamtien
Date: Wed, 16 Feb 2022 03:19:44 +0700
Subject: [PATCH 124/235] BAEL-5332-convert-byte-array-and-uuid (#11822)
Co-authored-by: tienvn4
---
.../java/com/baeldung/uuid/UuidHelper.java | 33 +++++++++++++++++++
1 file changed, 33 insertions(+)
create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java
new file mode 100644
index 0000000000..5807262094
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java
@@ -0,0 +1,33 @@
+package com.baeldung.uuid;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.UUID;
+
+public class UuidHelper {
+
+ public static byte[] convertUUIDToBytes(UUID uuid) {
+ ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
+ bb.putLong(uuid.getMostSignificantBits());
+ bb.putLong(uuid.getLeastSignificantBits());
+ return bb.array();
+ }
+
+ public static UUID convertBytesToUUID(byte[] bytes) {
+ ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+ long high = byteBuffer.getLong();
+ long low = byteBuffer.getLong();
+ return new UUID(high, low);
+ }
+
+ public static void main(String[] args) {
+ UUID uuid = UUID.randomUUID();
+ System.out.println("Original UUID: " + uuid);
+
+ byte[] bytes = convertUUIDToBytes(uuid);
+ System.out.println("Converted byte array: " + Arrays.toString(bytes));
+
+ UUID uuidNew = convertBytesToUUID(bytes);
+ System.out.println("Converted UUID: " + uuidNew);
+ }
+}
From 7966e98d90671a4580fe0378a2fa441d830a7b38 Mon Sep 17 00:00:00 2001
From: polomos
Date: Tue, 15 Feb 2022 22:14:36 +0100
Subject: [PATCH 125/235] BAEL-4388 Test reading keyStore without trustAnchor
(#11785)
---
.../truststore/TrustStoreUnitTest.java | 29 +++++++++++++++++++
1 file changed, 29 insertions(+)
create mode 100644 core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java
diff --git a/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java
new file mode 100644
index 0000000000..2c3d4c8959
--- /dev/null
+++ b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.truststore;
+
+import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.PKIXParameters;
+
+public class TrustStoreUnitTest {
+
+ @Test
+ public void whenOpeningTrustStore_thenExceptionIsThrown() throws Exception {
+ KeyStore keyStore = getKeyStore();
+ InvalidAlgorithmParameterException invalidAlgorithmParameterException =
+ Assertions.assertThrows(InvalidAlgorithmParameterException.class, () -> new PKIXParameters(keyStore));
+ Assertions.assertEquals("the trustAnchors parameter must be non-empty", invalidAlgorithmParameterException.getMessage());
+ }
+
+ private KeyStore getKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, "changeIt".toCharArray());
+ return ks;
+ }
+}
\ No newline at end of file
From 16b843dcb60f724ccb09a0cfe818d0fe020ab1c1 Mon Sep 17 00:00:00 2001
From: kpentaris
Date: Wed, 16 Feb 2022 08:17:56 +0200
Subject: [PATCH 126/235] BAEL-4513 Gradle source vs target compatibility
(#11762)
* Add example code for Gradle sourceCompatibility vs targetCompatibility
* Fix code format
---
.../build.gradle | 12 ++++++++++++
.../java/com/baeldung/helloworld/HelloWorldApp.java | 9 +++++++++
gradle/settings.gradle | 1 +
3 files changed, 22 insertions(+)
create mode 100644 gradle/gradle-source-vs-target-compatibility/build.gradle
create mode 100644 gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java
diff --git a/gradle/gradle-source-vs-target-compatibility/build.gradle b/gradle/gradle-source-vs-target-compatibility/build.gradle
new file mode 100644
index 0000000000..8cc50c15c6
--- /dev/null
+++ b/gradle/gradle-source-vs-target-compatibility/build.gradle
@@ -0,0 +1,12 @@
+plugins {
+ id 'java'
+}
+
+description = 'gradle-source-vs-target-compatibility'
+
+group 'com.baeldung'
+
+java {
+ sourceCompatibility = "1.6"
+ targetCompatibility = "1.8"
+}
diff --git a/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java b/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java
new file mode 100644
index 0000000000..a951a72dd6
--- /dev/null
+++ b/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java
@@ -0,0 +1,9 @@
+package com.baeldung.helloworld;
+
+public class HelloWorldApp {
+
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+
+}
diff --git a/gradle/settings.gradle b/gradle/settings.gradle
index 59300f9281..d1eb10f4d2 100644
--- a/gradle/settings.gradle
+++ b/gradle/settings.gradle
@@ -6,5 +6,6 @@ include 'greeter'
include 'gradletaskdemo'
include 'junit5'
include 'gradle-employee-app'
+include 'gradle-source-vs-target-compatibility'
println 'This will be executed during the initialization phase.'
From a7765c6a1966566e0cc5d1745990f6a56402db46 Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Wed, 16 Feb 2022 13:42:23 +0100
Subject: [PATCH 127/235] JAVA-9880: Temporarily disable spring-boot-swagger
module as it fails the builds
---
spring-boot-modules/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index 4925530a35..f872a6f8d5 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -69,7 +69,7 @@
spring-boot-runtime-2
spring-boot-security
spring-boot-springdoc
- spring-boot-swagger
+
spring-boot-swagger-jwt
spring-boot-swagger-keycloak
spring-boot-testing
From adca84eca2fb787d80589188088ae31ff537ea77 Mon Sep 17 00:00:00 2001
From: achraftt
Date: Wed, 16 Feb 2022 14:22:45 +0100
Subject: [PATCH 128/235] BAEL-5039: edit identation
---
.../WEB-INF/views/datePicker/displayDate.html | 10 +--
.../WEB-INF/views/datePicker/saveStudent.html | 66 +++++++++----------
2 files changed, 38 insertions(+), 38 deletions(-)
diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
index d3409f98f3..7ae84e026f 100644
--- a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
+++ b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/displayDate.html
@@ -1,12 +1,12 @@
+ xmlns:th="http://www.thymeleaf.org">
-
-Baeldung - using a datepicker to submit date
+
+ Baeldung - using a datepicker to submit date
- Student birth date
-
+Student birth date
+
\ No newline at end of file
diff --git a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
index 2faaed173c..d897369326 100644
--- a/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
+++ b/spring-web-modules/spring-thymeleaf/src/main/webapp/WEB-INF/views/datePicker/saveStudent.html
@@ -1,42 +1,42 @@
+ xmlns:th="http://www.thymeleaf.org">
-
-Baeldung - using a datepicker to submit date
+
+ Baeldung - using a datepicker to submit date
\ No newline at end of file
From cd70006bb6bccea7a9ce529cef35c8e46de65940 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Thu, 17 Feb 2022 08:29:23 +0000
Subject: [PATCH 129/235] [JAVA-9986] Fix ThreadStamped unit test
---
.../StampedAccount.java | 32 +++++++++++++------
.../ThreadStampedAccountUnitTest.java | 29 +++++++++++++----
2 files changed, 45 insertions(+), 16 deletions(-)
diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java
index 415b24738a..69aed0b979 100644
--- a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java
+++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java
@@ -1,25 +1,22 @@
package com.baeldung.atomicstampedreference;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
public class StampedAccount {
- private AtomicInteger stamp = new AtomicInteger(0);
- private AtomicStampedReference account = new AtomicStampedReference<>(0, 0);
-
- public int getBalance() {
- return account.getReference();
- }
-
- public int getStamp() {
- return account.getStamp();
- }
+ private final AtomicInteger stamp = new AtomicInteger(0);
+ private final AtomicStampedReference account = new AtomicStampedReference<>(0, 0);
public boolean deposit(int funds) {
int[] stamps = new int[1];
int current = this.account.get(stamps);
int newStamp = this.stamp.incrementAndGet();
+
+ // Thread is paused here to allow other threads to update the stamp and amount (for testing only)
+ sleep();
+
return this.account.compareAndSet(current, current + funds, stamps[0], newStamp);
}
@@ -29,4 +26,19 @@ public class StampedAccount {
int newStamp = this.stamp.incrementAndGet();
return this.account.compareAndSet(current, current - funds, stamps[0], newStamp);
}
+
+ public int getBalance() {
+ return account.getReference();
+ }
+
+ public int getStamp() {
+ return account.getStamp();
+ }
+
+ private static void sleep() {
+ try {
+ TimeUnit.SECONDS.sleep(1);
+ } catch (InterruptedException ignored) {
+ }
+ }
}
diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java
index ce83355073..2840c25cf6 100644
--- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java
@@ -1,21 +1,38 @@
package com.baeldung.atomicstampedreference;
-import org.junit.Assert;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class ThreadStampedAccountUnitTest {
@Test
public void givenMultiThread_whenStampedAccount_thenSetBalance() throws InterruptedException {
StampedAccount account = new StampedAccount();
+
Thread t = new Thread(() -> {
- while (!account.withdrawal(100))
+ while (!account.deposit(100)) {
Thread.yield();
+ }
});
t.start();
- Assert.assertTrue(account.deposit(100));
- t.join(1_000);
- Assert.assertFalse(t.isAlive());
- Assert.assertSame(0, account.getBalance());
+
+ Thread t2 = new Thread(() -> {
+ while (!account.withdrawal(100)) {
+ Thread.yield();
+ }
+ });
+ t2.start();
+
+ t.join(10_000);
+ t2.join(10_000);
+
+ assertFalse(t.isAlive());
+ assertFalse(t2.isAlive());
+
+ assertEquals(0, account.getBalance());
+ assertTrue(account.getStamp() > 0);
}
}
From c747712a0ea8512fbd3a19c46700b30ae8acd85f Mon Sep 17 00:00:00 2001
From: Parikshit Murria
Date: Thu, 17 Feb 2022 16:30:42 -0700
Subject: [PATCH 130/235] Update swaggerDirectory to target folder
---
.../generated/swagger-ui/swagger.json | 57 -------------------
.../spring-boot-swagger/pom.xml | 2 +-
2 files changed, 1 insertion(+), 58 deletions(-)
delete mode 100644 spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
diff --git a/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json b/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
deleted file mode 100644
index 4ebe165384..0000000000
--- a/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "swagger" : "2.0",
- "info" : {
- "description" : "This is a Baeldung Document Enum Sample Code",
- "version" : "v1",
- "title" : "Baeldung - Document Enum",
- "contact" : {
- "name" : "Parikshit Murria",
- "email" : "pmurria@baeldung.com"
- },
- "license" : {
- "name" : "Apache 2.0",
- "url" : "https://www.apache.org/licenses/LICENSE-2.0.html"
- }
- },
- "host" : "baeldung.com",
- "basePath" : "/api",
- "schemes" : [ "http", "https" ],
- "paths" : {
- "/hire" : {
- "post" : {
- "summary" : "This method is used to hire employee with a specific role",
- "description" : "",
- "operationId" : "hireEmployee",
- "produces" : [ "application/json" ],
- "parameters" : [ {
- "in" : "body",
- "name" : "body",
- "description" : "role",
- "required" : true,
- "schema" : {
- "$ref" : "#/definitions/Employee"
- }
- } ],
- "responses" : {
- "200" : {
- "description" : "successful operation",
- "schema" : {
- "type" : "string"
- }
- }
- }
- }
- }
- },
- "definitions" : {
- "Employee" : {
- "type" : "object",
- "properties" : {
- "role" : {
- "type" : "string",
- "enum" : [ "Engineer", "Clerk", "Driver", "Janitor" ]
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml
index 2c0e52b671..b6ed50534e 100644
--- a/spring-boot-modules/spring-boot-swagger/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger/pom.xml
@@ -63,7 +63,7 @@
Apache 2.0
- generated/swagger-ui
+ ${basedir}/target/swagger-ui
From 8b161f8f55da099068ad24abc242125da938fb9f Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Fri, 18 Feb 2022 09:30:42 +0100
Subject: [PATCH 131/235] JAVA-9880: Activate spring-boot-swagger module
---
spring-boot-modules/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index f872a6f8d5..4925530a35 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -69,7 +69,7 @@
spring-boot-runtime-2
spring-boot-security
spring-boot-springdoc
-
+ spring-boot-swagger
spring-boot-swagger-jwt
spring-boot-swagger-keycloak
spring-boot-testing
From 13a7a1d7eb7ea1ef6ca67a2b3c1962c9402bd37d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Maciej=20G=C5=82=C3=B3wka?=
Date: Sat, 19 Feb 2022 05:19:07 +0100
Subject: [PATCH 132/235] BAEL-4234: example of JNI registerNatives() method
(#11745)
* BAEL-4234: example of JNI registerNatives() method
* fixed formatting in the cpp file
* removed camelcase in test package name
---
...ldung_jni_RegisterNativesHelloWorldJNI.cpp | 21 ++++++++++++++
...aeldung_jni_RegisterNativesHelloWorldJNI.h | 29 +++++++++++++++++++
.../src/main/cpp/generateNativeLibMac.sh | 3 +-
.../jni/RegisterNativesHelloWorldJNI.java | 18 ++++++++++++
.../JNIRegisterNativesManualTest.java | 26 +++++++++++++++++
5 files changed, 96 insertions(+), 1 deletion(-)
create mode 100644 java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp
create mode 100644 java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h
mode change 100644 => 100755 java-native/src/main/cpp/generateNativeLibMac.sh
create mode 100644 java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java
create mode 100644 java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java
diff --git a/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp
new file mode 100644
index 0000000000..37adb35333
--- /dev/null
+++ b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp
@@ -0,0 +1,21 @@
+#include "com_baeldung_jni_RegisterNativesHelloWorldJNI.h"
+#include
+
+
+JNIEXPORT jstring JNICALL hello (JNIEnv* env, jobject thisObject) {
+ std::string hello = "Hello from registered native C++ !!";
+ std::cout << hello << std::endl;
+ return env->NewStringUTF(hello.c_str());
+}
+
+static JNINativeMethod methods[] = {
+ {"sayHello", "()Ljava/lang/String;", (void*) &hello },
+};
+
+
+JNIEXPORT void JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_register (JNIEnv* env, jobject thsObject) {
+ jclass clazz = env->FindClass("com/baeldung/jni/RegisterNativesHelloWorldJNI");
+
+ (env)->RegisterNatives(clazz, methods, sizeof(methods)/sizeof(methods[0]));
+}
+
diff --git a/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h
new file mode 100644
index 0000000000..bcca780208
--- /dev/null
+++ b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h
@@ -0,0 +1,29 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include
+/* Header for class com_baeldung_jni_RegisterNativesHelloWorldJNI */
+
+#ifndef _Included_com_baeldung_jni_RegisterNativesHelloWorldJNI
+#define _Included_com_baeldung_jni_RegisterNativesHelloWorldJNI
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class: com_baeldung_jni_RegisterNativesHelloWorldJNI
+ * Method: sayHello
+ * Signature: ()Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_sayHello
+ (JNIEnv *, jobject);
+
+/*
+ * Class: com_baeldung_jni_RegisterNativesHelloWorldJNI
+ * Method: register
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_register
+ (JNIEnv *, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/java-native/src/main/cpp/generateNativeLibMac.sh b/java-native/src/main/cpp/generateNativeLibMac.sh
old mode 100644
new mode 100755
index d11dcc7c01..834a07acc8
--- a/java-native/src/main/cpp/generateNativeLibMac.sh
+++ b/java-native/src/main/cpp/generateNativeLibMac.sh
@@ -3,4 +3,5 @@
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o
g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o
-g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc
\ No newline at end of file
+g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp -o com_baeldung_jni_RegisterNativesHelloWorldJNI.o
+g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o com_baeldung_jni_RegisterNativesHelloWorldJNI.o -lc
\ No newline at end of file
diff --git a/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java b/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java
new file mode 100644
index 0000000000..c5461aafef
--- /dev/null
+++ b/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java
@@ -0,0 +1,18 @@
+package com.baeldung.jni;
+
+public class RegisterNativesHelloWorldJNI {
+
+ static {
+ System.loadLibrary("native");
+ }
+
+ public static void main(String[] args) {
+ RegisterNativesHelloWorldJNI helloWorldJNI = new RegisterNativesHelloWorldJNI();
+ helloWorldJNI.register();
+ helloWorldJNI.sayHello();
+ }
+
+ public native String sayHello();
+
+ public native void register();
+}
diff --git a/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java b/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java
new file mode 100644
index 0000000000..96e15bd822
--- /dev/null
+++ b/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.jni.registernatives;
+
+import com.baeldung.jni.RegisterNativesHelloWorldJNI;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class JNIRegisterNativesManualTest {
+ @Before
+ public void setup() {
+ System.loadLibrary("native");
+ }
+
+ @Test
+ public void whenRegisteredNativeHelloWorld_thenOutputIsAsExpected() {
+ RegisterNativesHelloWorldJNI helloWorld = new RegisterNativesHelloWorldJNI();
+ helloWorld.register();
+
+ String helloFromNative = helloWorld.sayHello();
+
+ assertNotNull(helloFromNative);
+ assertTrue(helloFromNative.equals("Hello from registered native C++ !!"));
+ }
+}
From d28a3e642a7099aa850295194fa506b23314b048 Mon Sep 17 00:00:00 2001
From: Vikas Rajput
Date: Sat, 19 Feb 2022 17:06:34 +0530
Subject: [PATCH 133/235] Bael 4788: Completed Article - Hibernate addScalar()
method (#11783)
* BAEL-4788: Added ScalarDemo Class for Hibernate addScalar Method article
* BAEL-4788: Added unit tests in the article
* BAEL-4788: removed redundant code
Co-authored-by: Vikas Ramsingh Rajput
---
.../scalarmethod/HibernateScalarExample.java | 47 +++++++++++
.../HibernateScalarExampleUnitTest.java | 83 +++++++++++++++++++
2 files changed, 130 insertions(+)
create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java
create mode 100644 persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java
new file mode 100644
index 0000000000..69aaaae19d
--- /dev/null
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java
@@ -0,0 +1,47 @@
+package com.baeldung.hibernate.scalarmethod;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.type.StandardBasicTypes;
+
+public class HibernateScalarExample {
+
+ private Session session;
+
+ public HibernateScalarExample(Session session) {
+ this.session = session;
+ }
+
+ public List fetchColumnWithNativeQuery() {
+ return session.createNativeQuery("SELECT * FROM Student student")
+ .list();
+ }
+
+ public List fetchColumnWithScalar() {
+ return session.createNativeQuery("SELECT * FROM Student student")
+ .addScalar("studentId", StandardBasicTypes.LONG)
+ .addScalar("name", StandardBasicTypes.STRING)
+ .addScalar("age", StandardBasicTypes.INTEGER)
+ .list();
+ }
+
+ public List fetchLimitedColumnWithScalar() {
+ return session.createNativeQuery("SELECT * FROM Student student")
+ .addScalar("name", StandardBasicTypes.STRING)
+ .list();
+ }
+
+ public List fetchColumnWithOverloadedScalar() {
+ return session.createNativeQuery("SELECT * FROM Student student")
+ .addScalar("name", StandardBasicTypes.STRING)
+ .addScalar("age")
+ .list();
+ }
+
+ public Integer fetchAvgAgeWithScalar() {
+ return (Integer) session.createNativeQuery("SELECT AVG(age) as avgAge FROM Student student")
+ .addScalar("avgAge")
+ .uniqueResult();
+ }
+}
diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java
new file mode 100644
index 0000000000..ca01c5cb84
--- /dev/null
+++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.hibernate.scalarmethod;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Random;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.baeldung.hibernate.HibernateUtil;
+import com.baeldung.hibernate.pojo.Student;
+
+public class HibernateScalarExampleUnitTest {
+
+ private static Session session;
+ private static Transaction transaction;
+ private static final int DATA_SIZE = 50000;
+ private static HibernateScalarExample scalarExample;
+
+ @BeforeClass
+ public static void setUp() throws IOException {
+ session = HibernateUtil.getSessionFactory().openSession();
+ transaction = session.beginTransaction();
+ scalarExample = new HibernateScalarExample(session);
+ session.createNativeQuery("delete from Student").executeUpdate();
+ for (int i = 0; i < DATA_SIZE; i++) {
+ Student student = new Student("John-" + i, generateRandomAge(5, 24));
+ session.persist(student);
+ }
+ transaction.commit();
+ transaction = session.beginTransaction();
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ transaction.rollback();
+ session.close();
+ }
+
+ @Test
+ public void givenNativeQuery_whenNoScalarUsed_ThenFetchAll() {
+ List list = scalarExample.fetchColumnWithNativeQuery();
+ assertEquals(DATA_SIZE, list.size());
+ }
+
+ @Test
+ public void givenNativeQuery_whenScalarUsed_ThenFetchAll() {
+ List list = scalarExample.fetchColumnWithScalar();
+ assertEquals(DATA_SIZE, list.size());
+ }
+
+ @Test
+ public void givenNativeQuery_whenScalarUsed_ThenFetchLimitedColumns() {
+ List list = scalarExample.fetchLimitedColumnWithScalar();
+ for (String colValue : list) {
+ assertTrue(colValue.startsWith("John"));
+ }
+ }
+
+ @Test
+ public void givenNativeQuery_whenScalarUsedForSingleResult_ThenSingleValueReturned() {
+ List list = scalarExample.fetchColumnWithOverloadedScalar();
+ for (Object[] colArray : list) {
+ assertEquals(2, colArray.length);
+ }
+ }
+
+ @Test
+ public void whenScalarUsedForAvgAge_ThenSingleValueReturned() {
+ Integer avgAge = scalarExample.fetchAvgAgeWithScalar();
+ assertEquals(true, (avgAge >= 5 && avgAge <= 24));
+ }
+
+ private static int generateRandomAge(int min, int max) {
+ return new Random().nextInt(max - min + 1) + min;
+ }
+}
From f3b59f5316f44dc81543b293ca9b79012c9d7fc6 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Sat, 19 Feb 2022 19:41:44 +0000
Subject: [PATCH 134/235] [JAVA-10080] Add plugin for filtering xls resources
---
apache-poi/pom.xml | 18 ++++++++++++++++++
.../cellstyle/CellStyleBorderHandlerTest.xlsx | Bin 0 -> 7500 bytes
.../cellstyle/CellBorderHandlerUnitTest.java | 2 +-
3 files changed, 19 insertions(+), 1 deletion(-)
create mode 100644 apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index 1a0f77b025..546eedec5b 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -32,9 +32,27 @@
+
+
+
+ org.apache.maven.plugins
+ maven-resources-plugin
+ ${maven.resources.plugin.version}
+
+ UTF-8
+
+ xlsx
+ xls
+
+
+
+
+
+
5.2.0
1.0.6
+ 3.2.0
\ No newline at end of file
diff --git a/apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx b/apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..29f128211b6b9587a1fa5b7bc6e4401883d05a04
GIT binary patch
literal 7500
zcmbt(1yCH@*7e{L2<|p$a0?bJ!QI^*1|5RC43OXi*Fl0qaCaXd1PLwyf&~p02oUV!
z-TT+OFI4^Y-FLs~>FKKOsk8d5eQNE!*HKkKK*R?C0H_ZqH2~!YAq4~u0O*1T0I&db
z051m)Pq2%x6V`#CC<}(+LzgWWl=4xE6S-k{@h+G{0sxMtbN0)A&F_7V`a_hWo9V6?M
zbh&gZ5Nj3O>6}vQrcZj5yQL$06VOEAFHF_(@;S3->6ZVP8Lgzch;F*JXi&c5c7AfY
zsc-~7jV#nB$RP$)wpUk;OOZpucS1|vxv$!zQ-%D5eVh&_`je&TIWew{w&Txd+xfzz
zF21EN+2FPPC3`-4QTE21@?r1eV1C;#sGGpv5TcA?{wYRz_X3SZjYrCloD(8IwYA!V0^Tlf@RFcN!BWJbB)9y}R{E
z)iQOp=^91#w~$7<%Au*D007q1007>fA$0>;Ia+c2@yqph!}?v{0KCM9f5!q@FT}kz_W`tG=h6l#6-aJt6wtsyoPOek7>lyBV>zDU$Yq)k}s~Q5DxX
zLIsvl^`(4{t>%3RfCx$G$e`=f@fS4iS9^W$1P2Aag-WqC`IT-83Xs;JMOd?49D-Cq
z%}BLuDZ%Nw3!MnWPTdjmR5_UE`GBH?2OIhPP)nHr3DeOSz6m|N;)k7j&lYKL=eOPto6
zu21JIRW&1!!BJ+MJ9b6WB?$_FQ9VaILLHcxk<4Z#j$G3U-?Mf2shP@x5_UjQ?VEFD
z%jZdRJQ~uT6=zDTWYa7xCnO|@Fu}=!1g0oS<1b-5a8W3)fM`s(bT0iavBe+^oMovb
za#;TYZ5;sO97_W;Yu04Kl-Igs2^4Wp_9FalT2RAc859PNlaqZ)HE7AMe~5{FV8>Hs
z+$rpTx_&lXRjiVeEqdi$XpHup*i(&Xie&ZXc*bPa|M2E&*g#>}-M
z^;A8d`f%$Pzc#{@y-@Nj%73v(VwhYIxyp9*GuM-uBJ4Rv(ga%z^!CP&&*Q)vnO2_l
zS09Oz3`W-8S!As
z3X}kYkn0s5Qp4OPDTVfs8M6!`-qNAFt?%EU(h$CAO0S+gdhR+p!JGQ}68ARICK;MWcmzT+*1ib?7fj7(O%?4K}vC
z&xcLH$M28>*M;+{abaMVu`T%1MDhjBw+Zc1QIKz?Zzvg#aR2iZ6x+a-`1lk?bhRv&
zYXE$AxFzG8pOU^&v2ku65#ZTq`(u}RnwpamkbGb29DWCo5Gb$w$T~KHy?HiXe_&c6
z%K0wKssbL*QUdcXJq`FHXIY$95|cphI2!wmcGeO@SenjKxE8?D83uiA$8I@FF(FSv
zp)UL0vr&O8CgFaVlz!>-QkG3UcE^=hrlr){GoSt={Y@O7xJZ4tlZBo`Omp)P?KkTgw=j)Wwh8www=Z!N!bBa_YWZW`~WFNveYQ3XvDhi+bzF
z<~$_bxvgrxx%-%d-hk9HLI`q*Ga>E3X1}7Jv?M3S1o_XLk9LD@FpY)hho4B^Ix_J(
z5LEIt5w3}5(ixO*o%#?F2)rAjOuCuL20A>&n=eo|sA*_z)M%c~1&mLR9ioS922hc=
z3gXGkyvgsROfJ$-{|u2BJ=y@+E(Y-wKpMsygBaTi4udbeP>k;lDv#)MO;@p6uOr-a
z_s)`YlIdR-jk_w@AtLbX>{`0z@Y8>}Vd_jB$0YYTNEb*NPbhkaa%=}hwzq3^3w9t8
zk~r-&2HSP=0_8(=-%XQ&d52MajjU5*Ld9rB{3nK91Z(M@!%Y*98XV#`maTDTNf5uj
z`uS!DLpcCOqnyx+J>RK7~Nxt{flV<{K3TqB46pZed2&TRN;Nwec~3r_kj&P7)Mx6lPChB+hay&gbzWP)
z9_lR6!uX5BWz=~Zt=TTi*#kSjQ6P7hL(vC2ipG@kKU=%&PKk(H$c3x1x%
zT3%Q~7-A3+m^4)F!7J`Hc8Sj2S5%gol7xS;J*=595@86|=c)g`wrQwYsC4*?Tpi+ILc8C%
zZSmahRyt4n(Bp}51>G8dMp&y(X?=%J+vkhLS6Mv7oab~o1u)%(vyZF4XXzusz0j41
z%F6wr_`-h3(w1NgRTr?cD~Fl0^WRO;P*o*+1ZwPCmUWSGIR&O3-q1I%unL2nT#2B|
zsQZk9XbXWRO?i%E9UUB$U}?unGfSeO0U3v@+W0KE#U0_NZ1)F0qin{|N!+ZXQQ2~G
zk7KmolH*yPs_L?JPoCnb=|53BK!Y$THPi_Df9g>!^v13^>IgHc-v-E<({CjPvA_vB
zN1YiAfn)Zc+%`>12_3NvI?20NYA+>8gE42w&iT>><0)25lAGtYCr*B%boe=Jh9s>9
zQz^}?QJIb}Ocj*7t7xH6$Gizbt60IvfIG!7F_%RyCW-8d+vWJ3FDw9xw&DXql@VTav+EIMlY4q>!4jYxf$CQFBte^Swipy{zxL}7S&;lV*8
zy($QOZZejh{^_Y!x*r5om^>9Up
zl5`^K!+4Y5{TJYq3RK0BkP$}fvhF}QegtOb(13Q?QGZS?I``3IF}84fse6L!))(UK1YIr^5`X0q@R
z_)M8bH2CyuSjMDp%x`7|E_qj%b%72az*lGEqfw8-6TkUJAoU?M6v%*wR^i`$ge%C(
z%FUJIkIUb#JfTTTv6-CMZ%hVG{RQY8l+pDXGAmovS+tfZD`Q9?4a6Eta=Kdn7qPE%
zZHJ{anZ&Hqu5L$rR=zaV(#T9mmk1WV##V#p)oCfYV7mRa^}4p8UsrqkgF0`)839Je
zs*|#OR~l|NZgiEByn=nEJ29y-#F9Z3bNaGSRi8Vm%7-dL8eyajs24WHnDI6tBEu)F
zp;JnNAna?k#tks9(O6PqfORrcou^30{zvAS%cydi?YL`j^A8i`4gr!Axt<2@vT8UT
z?laH^tIpb9l`uUOnh{fq<*%&?Mb+k>O>Q-`>%~Hah|T?C{|cTF<^vhBXVHn;8{o+M
z1tdCx#nfJXB(M8i7mQ#BegaqK?dDQ6Q3#C6-$Y>FGCrGtF(Eka;vdawUn_gIE_M=
z^34t>vPBrpKq9>hcnW3#UZ{pNVgf+JO5d!(L)O4ay0;Jt=4(CZO2~XFVas8wS0%F>
z>{)!T5raVahx2KgCi+Uko@E;4qLI4@q)ily%w$@x!J{$GwqrsLOr6;nWnY)SfH4ijYd#2szSv%BIf@!shOm3mX*|
zvcgSK-p47fQdw5pY-u6o@pa9y`IQ%FI2Bb*HjeX@qTC%s4b%i4gl*)kjGsH_mq~>d
z_0(uI2%pS%C3_9RJK-S78ZlbECHnFO?PZ7vkECrd5y%rhy1%9
z!7g1E91#Hk4srkh^UnqE>gMfW<@$HE=)0a{+@b*X9gA9L9a^Z>aHMLo11(fjE4lF*
z)U6eZTEKL;Cf@5lLLhUC;
zZ-*5tnhj+Rk8%=vrrqTeKWZ^2S;qUC7G7J6vW$vV4`N!tg3&BVTF5LKFS2#4$+Qc$
zVivj4k_>lgcqeA;tG?K!RLUa~^paiO^|Pq6FJH0hOeQH8c}z+kHd6u^OtQvH0i|y$
zH%4vJapi>!E9bK-XowI)#L@{r_^>D=nb8yH#4gCZQ|V%LBnj_s?_*Qx=#Pj5z+H6KdTUHWq9`n-~SwVQdQ;dLmcbWhB{uGHJ&101tiY|5yKzZfkg3G`FBW0
z=g5{g?VP+?vs9PJsTdX$oVK;N4SOQq=
z`{B5bFy6_U`^NY!fwP+Aq1a%}qy(MdN=%Zx3bSCsd?)mhn{fW!*BoBGrje>p_!zh&a?%8p+1%AB%wBB{O
zd#IgGsi
zBm9{kaA`O9mEkK26(SxE!o#m!?8^i0M3GvJyYppQT6JaR+QkL^q8{J23mRwLwiM7;lUi
zdM_uoR28l@xVRNNo{k-n!&KxIXpnD0(axIr=TBJJ$i>Sz8;%^FOn!ohbc%yaLX6ir
zZ-??jWIUIk-QmcTy;`p|%Gy>+R-`)ivte5I^wpD%G&cKW?fR2PB$QXtQ(dg^q%e9Y
z8&e;o`d?<4fdtse&C1EmMAO^Z%GK!aigiWOh*KXBTPhH#rothCy{s%UQHpAWPkjn2
zmorw46ZocJc-2#p(x1_ttdNYB?Ayvl3$1jbyZr(>4e1fHC@V@K5Piyn!3kX))MoIBam6XnA9@i!((_fG
z@d&qBvp_i{PR3Jpq)_P~Kq;q*9Ea7#qfKPqTg&i`X-q%s!4vyQxj9@F|wqxS%=VtO(9
zE~HL4R&xFu@M92L$e3t{^n_}Gs;p7TO54m#9LC0uH(JsYNzrQm1Suc8)3O;vX%1rO;
zez08M+aXl~Gfpo(Yxk~C_gDiF$-+!|iTzP&@``fTxcdu(QNCbSgEGSEaK}1(zCBpyaPVvoBKZH?4|#a-AD@4)JMtLdu{;0Q=u;0e^#Jfsy!yu=
zkIjX@K)lfa|Hx{1jPSS}{|liM{XY=?o96s6#N(FoF9=zTKbZR0M%6!RFdrj5uI2wi
zdV%!^(tlUkKOX*Zy8UbTbG$!?|0l`!G0Nji2mCk8*N5f(5A&Xwt25Zuie19W!NC=1
z4R!&_xY%0Cy8=D9x!Acl*|{FS#AEUP_d5U*2>+Ps|3S(hV?CC*zp&
Date: Sun, 20 Feb 2022 22:51:08 +0100
Subject: [PATCH 135/235] Caching Maven Dependencies with Docker - improvements
---
.../Dockerfile | 10 ++--
.../Dockerfile-Buildkit | 2 +-
.../core/pom.xml | 8 ++-
.../com/baeldung/maven_caching/CoreClass.java | 6 ++
.../multi-module-caching/pom.xml | 29 ++++++++++
.../multi-module-caching/runner/pom.xml | 55 +++++++++++++++++++
.../MavenCachingApplication.java | 6 +-
.../multi-module/application/pom.xml | 36 ------------
.../src/main/resources/application.properties | 1 -
.../MavenCachingApplicationTests.java | 13 -----
docker/docker-caching/multi-module/pom.xml | 38 -------------
.../Dockerfile | 2 +-
.../Dockerfile-Buildkit | 2 +-
.../pom.xml | 2 +-
.../maven_caching/MavenCachingMain.java | 0
15 files changed, 107 insertions(+), 103 deletions(-)
rename docker/docker-caching/{multi-module => multi-module-caching}/Dockerfile (52%)
rename docker/docker-caching/{multi-module => multi-module-caching}/Dockerfile-Buildkit (68%)
rename docker/docker-caching/{multi-module => multi-module-caching}/core/pom.xml (72%)
rename docker/docker-caching/{multi-module => multi-module-caching}/core/src/main/java/com/baeldung/maven_caching/CoreClass.java (51%)
create mode 100644 docker/docker-caching/multi-module-caching/pom.xml
create mode 100644 docker/docker-caching/multi-module-caching/runner/pom.xml
rename docker/docker-caching/{multi-module/application => multi-module-caching/runner}/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java (50%)
delete mode 100644 docker/docker-caching/multi-module/application/pom.xml
delete mode 100644 docker/docker-caching/multi-module/application/src/main/resources/application.properties
delete mode 100644 docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
delete mode 100644 docker/docker-caching/multi-module/pom.xml
rename docker/docker-caching/{single-module => single-module-caching}/Dockerfile (66%)
rename docker/docker-caching/{single-module => single-module-caching}/Dockerfile-Buildkit (67%)
rename docker/docker-caching/{single-module => single-module-caching}/pom.xml (97%)
rename docker/docker-caching/{single-module => single-module-caching}/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java (100%)
diff --git a/docker/docker-caching/multi-module/Dockerfile b/docker/docker-caching/multi-module-caching/Dockerfile
similarity index 52%
rename from docker/docker-caching/multi-module/Dockerfile
rename to docker/docker-caching/multi-module-caching/Dockerfile
index 1f0cc85f7c..96ebe2a76b 100644
--- a/docker/docker-caching/multi-module/Dockerfile
+++ b/docker/docker-caching/multi-module-caching/Dockerfile
@@ -5,17 +5,17 @@ WORKDIR $HOME
ADD pom.xml $HOME
ADD core/pom.xml $HOME/core/pom.xml
-ADD application/pom.xml $HOME/application/pom.xml
+ADD runner/pom.xml $HOME/runner/pom.xml
RUN mvn -pl core verify --fail-never
ADD core $HOME/core
RUN mvn -pl core install
-RUN mvn -pl application verify --fail-never
-ADD application $HOME/application
-RUN mvn -pl core,application package
+RUN mvn -pl runner verify --fail-never
+ADD runner $HOME/runner
+RUN mvn -pl core,runner package
FROM openjdk:8-jdk-alpine
-COPY --from=build /usr/app/application/target/application-0.0.1-SNAPSHOT.jar /app/runner.jar
+COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/Dockerfile-Buildkit b/docker/docker-caching/multi-module-caching/Dockerfile-Buildkit
similarity index 68%
rename from docker/docker-caching/multi-module/Dockerfile-Buildkit
rename to docker/docker-caching/multi-module-caching/Dockerfile-Buildkit
index f51657c9ce..e89ce38e4b 100644
--- a/docker/docker-caching/multi-module/Dockerfile-Buildkit
+++ b/docker/docker-caching/multi-module-caching/Dockerfile-Buildkit
@@ -8,6 +8,6 @@ RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
FROM openjdk:8-jdk-alpine
-COPY --from=build /usr/app/application/target/application-0.0.1-SNAPSHOT.jar /app/runner.jar
+COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/core/pom.xml b/docker/docker-caching/multi-module-caching/core/pom.xml
similarity index 72%
rename from docker/docker-caching/multi-module/core/pom.xml
rename to docker/docker-caching/multi-module-caching/core/pom.xml
index 5df8ea7dde..0b79a64143 100644
--- a/docker/docker-caching/multi-module/core/pom.xml
+++ b/docker/docker-caching/multi-module-caching/core/pom.xml
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- maven-caching
+ multi-module-caching
com.baeldung
0.0.1-SNAPSHOT
@@ -16,4 +16,10 @@
8
+
+
+ com.google.guava
+ guava
+
+
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java b/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
similarity index 51%
rename from docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
rename to docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
index a33624d4e7..7d57110d72 100644
--- a/docker/docker-caching/multi-module/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
+++ b/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
@@ -1,8 +1,14 @@
package com.baeldung.maven_caching;
+import com.google.common.io.Files;
+
public class CoreClass {
public String method(){
return "Hello from core module!!";
}
+
+ public String dependencyMethod(){
+ return Files.simplifyPath("/home/app/test");
+ }
}
diff --git a/docker/docker-caching/multi-module-caching/pom.xml b/docker/docker-caching/multi-module-caching/pom.xml
new file mode 100644
index 0000000000..42205a29de
--- /dev/null
+++ b/docker/docker-caching/multi-module-caching/pom.xml
@@ -0,0 +1,29 @@
+
+
+ 4.0.0
+ pom
+
+ runner
+ core
+
+ com.baeldung
+ multi-module-caching
+ 0.0.1-SNAPSHOT
+ maven-caching
+ maven-caching
+
+ 1.8
+
+
+
+
+
+ com.google.guava
+ guava
+ 31.0.1-jre
+
+
+
+
+
diff --git a/docker/docker-caching/multi-module-caching/runner/pom.xml b/docker/docker-caching/multi-module-caching/runner/pom.xml
new file mode 100644
index 0000000000..d306baf05d
--- /dev/null
+++ b/docker/docker-caching/multi-module-caching/runner/pom.xml
@@ -0,0 +1,55 @@
+
+
+
+ multi-module-caching
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+ runner
+
+
+ com.baeldung
+ core
+ 0.0.1-SNAPSHOT
+
+
+
+
+ 8
+ 8
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 3.3.0
+
+
+ jar-with-dependencies
+
+
+
+ true
+ com.baeldung.maven_caching.MavenCachingApplication
+
+
+
+
+
+ assemble-all
+ package
+
+ single
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java b/docker/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
similarity index 50%
rename from docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
rename to docker/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
index dec5453dc9..3673dd86c1 100644
--- a/docker/docker-caching/multi-module/application/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
+++ b/docker/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
@@ -1,15 +1,11 @@
package com.baeldung.maven_caching;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
public class MavenCachingApplication {
public static void main(String[] args) {
- SpringApplication.run(MavenCachingApplication.class, args);
CoreClass cc = new CoreClass();
System.out.println(cc.method());
+ System.out.println(cc.dependencyMethod());
}
}
diff --git a/docker/docker-caching/multi-module/application/pom.xml b/docker/docker-caching/multi-module/application/pom.xml
deleted file mode 100644
index 49611e7fbd..0000000000
--- a/docker/docker-caching/multi-module/application/pom.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
- maven-caching
- com.baeldung
- 0.0.1-SNAPSHOT
-
- 4.0.0
-
- application
-
-
- com.baeldung
- core
- 0.0.1-SNAPSHOT
-
-
-
-
- 8
- 8
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
-
-
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module/application/src/main/resources/application.properties b/docker/docker-caching/multi-module/application/src/main/resources/application.properties
deleted file mode 100644
index 8b13789179..0000000000
--- a/docker/docker-caching/multi-module/application/src/main/resources/application.properties
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java b/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
deleted file mode 100644
index ec550fb990..0000000000
--- a/docker/docker-caching/multi-module/application/src/test/java/com/baeldung/maven_caching/MavenCachingApplicationTests.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.baeldung.maven_caching;
-
-import org.junit.jupiter.api.Test;
-import org.springframework.boot.test.context.SpringBootTest;
-
-@SpringBootTest
-class MavenCachingApplicationTests {
-
- @Test
- void contextLoads() {
- }
-
-}
diff --git a/docker/docker-caching/multi-module/pom.xml b/docker/docker-caching/multi-module/pom.xml
deleted file mode 100644
index 0cc309e2ad..0000000000
--- a/docker/docker-caching/multi-module/pom.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-
-
- 4.0.0
- pom
-
- application
- core
-
-
- org.springframework.boot
- spring-boot-starter-parent
- 2.6.3
-
-
- com.baeldung
- maven-caching
- 0.0.1-SNAPSHOT
- maven-caching
- maven-caching
-
- 1.8
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
-
-
diff --git a/docker/docker-caching/single-module/Dockerfile b/docker/docker-caching/single-module-caching/Dockerfile
similarity index 66%
rename from docker/docker-caching/single-module/Dockerfile
rename to docker/docker-caching/single-module-caching/Dockerfile
index 309945440b..02157c0dd6 100644
--- a/docker/docker-caching/single-module/Dockerfile
+++ b/docker/docker-caching/single-module-caching/Dockerfile
@@ -10,6 +10,6 @@ RUN mvn package
FROM openjdk:8-jdk-alpine
-COPY --from=build /usr/app/target/maven-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
+COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/single-module/Dockerfile-Buildkit b/docker/docker-caching/single-module-caching/Dockerfile-Buildkit
similarity index 67%
rename from docker/docker-caching/single-module/Dockerfile-Buildkit
rename to docker/docker-caching/single-module-caching/Dockerfile-Buildkit
index d3d2aad90d..29384ce208 100644
--- a/docker/docker-caching/single-module/Dockerfile-Buildkit
+++ b/docker/docker-caching/single-module-caching/Dockerfile-Buildkit
@@ -8,6 +8,6 @@ RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
FROM openjdk:8-jdk-alpine
-COPY --from=build /usr/app/target/maven-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
+COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar
\ No newline at end of file
diff --git a/docker/docker-caching/single-module/pom.xml b/docker/docker-caching/single-module-caching/pom.xml
similarity index 97%
rename from docker/docker-caching/single-module/pom.xml
rename to docker/docker-caching/single-module-caching/pom.xml
index 54337436c5..b1abc55772 100644
--- a/docker/docker-caching/single-module/pom.xml
+++ b/docker/docker-caching/single-module-caching/pom.xml
@@ -5,7 +5,7 @@
4.0.0
com.baeldung
- single-maven-caching
+ single-module-caching
1.0-SNAPSHOT
diff --git a/docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java b/docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
similarity index 100%
rename from docker/docker-caching/single-module/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
rename to docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
From 64ffe101dca69244c5fb85e7dca2ce71365cdf4d Mon Sep 17 00:00:00 2001
From: Mladen Savic
Date: Sun, 20 Feb 2022 22:51:08 +0100
Subject: [PATCH 136/235] Caching Maven Dependencies with Docker - improvements
---
docker/pom.xml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docker/pom.xml b/docker/pom.xml
index f481f1b8b7..5c6267c6dd 100644
--- a/docker/pom.xml
+++ b/docker/pom.xml
@@ -26,6 +26,8 @@
docker-internal-dto
docker-spring-boot
docker-sample-app
+ docker-caching/single-module-caching
+ docker-caching/multi-module-caching
From 6ece2c8805059b4b477c152baab854f99c28f787 Mon Sep 17 00:00:00 2001
From: Mladen Savic
Date: Sun, 20 Feb 2022 22:51:08 +0100
Subject: [PATCH 137/235] Caching Maven Dependencies with Docker - improvements
---
.../multi-module-caching/core/pom.xml | 16 ++++++++--------
.../docker-caching/multi-module-caching/pom.xml | 17 +++++++++--------
.../multi-module-caching/runner/pom.xml | 15 ++++++++-------
.../single-module-caching/pom.xml | 10 +++++-----
4 files changed, 30 insertions(+), 28 deletions(-)
diff --git a/docker/docker-caching/multi-module-caching/core/pom.xml b/docker/docker-caching/multi-module-caching/core/pom.xml
index 0b79a64143..eeeb5a6e5b 100644
--- a/docker/docker-caching/multi-module-caching/core/pom.xml
+++ b/docker/docker-caching/multi-module-caching/core/pom.xml
@@ -2,19 +2,14 @@
+ 4.0.0
+ core
+
multi-module-caching
com.baeldung
0.0.1-SNAPSHOT
- 4.0.0
-
- core
-
-
- 8
- 8
-
@@ -22,4 +17,9 @@
guava
+
+
+ 8
+ 8
+
\ No newline at end of file
diff --git a/docker/docker-caching/multi-module-caching/pom.xml b/docker/docker-caching/multi-module-caching/pom.xml
index 42205a29de..c5a7d9ec6f 100644
--- a/docker/docker-caching/multi-module-caching/pom.xml
+++ b/docker/docker-caching/multi-module-caching/pom.xml
@@ -2,19 +2,12 @@
4.0.0
- pom
-
- runner
- core
-
com.baeldung
multi-module-caching
0.0.1-SNAPSHOT
maven-caching
maven-caching
-
- 1.8
-
+ pom
@@ -26,4 +19,12 @@
+
+ 1.8
+
+
+
+ runner
+ core
+
diff --git a/docker/docker-caching/multi-module-caching/runner/pom.xml b/docker/docker-caching/multi-module-caching/runner/pom.xml
index d306baf05d..e3654bff17 100644
--- a/docker/docker-caching/multi-module-caching/runner/pom.xml
+++ b/docker/docker-caching/multi-module-caching/runner/pom.xml
@@ -2,14 +2,15 @@
+ 4.0.0
+ runner
+
multi-module-caching
com.baeldung
0.0.1-SNAPSHOT
- 4.0.0
- runner
com.baeldung
@@ -18,11 +19,6 @@
-
- 8
- 8
-
-
@@ -52,4 +48,9 @@
+
+
+ 8
+ 8
+
\ No newline at end of file
diff --git a/docker/docker-caching/single-module-caching/pom.xml b/docker/docker-caching/single-module-caching/pom.xml
index b1abc55772..386b040138 100644
--- a/docker/docker-caching/single-module-caching/pom.xml
+++ b/docker/docker-caching/single-module-caching/pom.xml
@@ -8,11 +8,6 @@
single-module-caching
1.0-SNAPSHOT
-
- 8
- 8
-
-
com.google.guava
@@ -50,4 +45,9 @@
+
+
+ 8
+ 8
+
\ No newline at end of file
From 505a983ae566e13a596e772a3c05ee62f5cfa9c5 Mon Sep 17 00:00:00 2001
From: psevestre
Date: Mon, 21 Feb 2022 13:12:24 -0300
Subject: [PATCH 138/235] Bael 5259 (#11832)
* [BAEL-4849] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Article code
* [BAEL-4968] Remove extra comments
* [BAEL-5259] simple test case
* [BAEL-5259] DSL-based rewrite
* [BAEL-5259] Code formatting
* [BAEL-5259] Test case naming
---
spring-cloud/spring-cloud-gateway/pom.xml | 16 +++
.../rewrite/URLRewriteGatewayApplication.java | 25 ++++
.../rewrite/routes/DynamicRewriteRoute.java | 43 +++++++
.../WebFilterGatewayApplication.java | 2 +-
.../main/resources/application-nosecurity.yml | 8 ++
.../resources/application-url-rewrite.yml | 11 ++
.../URLRewriteGatewayApplicationLiveTest.java | 109 ++++++++++++++++++
7 files changed, 213 insertions(+), 1 deletion(-)
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml
create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml
create mode 100644 spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java
diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml
index dcad2b7da6..a352bbd4e4 100644
--- a/spring-cloud/spring-cloud-gateway/pom.xml
+++ b/spring-cloud/spring-cloud-gateway/pom.xml
@@ -177,5 +177,21 @@
+
+
+ gateway-url-rewrite
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+ com.baeldung.springcloudgateway.rewrite.URLRewriteGatewayApplication
+ -Dspring.profiles.active=url-rewrite
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java
new file mode 100644
index 0000000000..46541b4826
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java
@@ -0,0 +1,25 @@
+/**
+ *
+ */
+package com.baeldung.springcloudgateway.rewrite;
+
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.cloud.gateway.filter.GatewayFilter;
+
+import reactor.core.publisher.Mono;
+
+/**
+ * @author Baeldung
+ *
+ */
+@SpringBootApplication
+public class URLRewriteGatewayApplication {
+
+ public static void main(String[] args) {
+ new SpringApplicationBuilder(URLRewriteGatewayApplication.class)
+ .profiles("url-rewrite")
+ .run(args);
+ }
+
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java
new file mode 100644
index 0000000000..29d40d7021
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java
@@ -0,0 +1,43 @@
+package com.baeldung.springcloudgateway.rewrite.routes;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cloud.gateway.route.RouteLocator;
+import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+
+import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
+import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
+
+import java.util.Random;
+
+@Configuration
+@Profile("url-rewrite")
+public class DynamicRewriteRoute {
+
+ @Value("${rewrite.backend.uri}")
+ private String backendUri;
+ private static Random rnd = new Random();
+
+ @Bean
+ public RouteLocator dynamicZipCodeRoute(RouteLocatorBuilder builder) {
+ return builder.routes()
+ .route("dynamicRewrite", r ->
+ r.path("/v2/zip/**")
+ .filters(f -> f.filter((exchange, chain) -> {
+ ServerHttpRequest req = exchange.getRequest();
+ addOriginalRequestUrl(exchange, req.getURI());
+ String path = req.getURI().getRawPath();
+ String newPath = path.replaceAll(
+ "/v2/zip/(?.*)",
+ "/api/zip/${zipcode}-" + String.format("%03d", rnd.nextInt(1000)));
+ ServerHttpRequest request = req.mutate().path(newPath).build();
+ exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
+ return chain.filter(exchange.mutate().request(request).build());
+ }))
+ .uri(backendUri))
+ .build();
+ }
+}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java
index 852e5cadba..9e212cc4bf 100644
--- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java
+++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java
@@ -8,7 +8,7 @@ public class WebFilterGatewayApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(WebFilterGatewayApplication.class)
- .profiles("webfilters")
+ .profiles("url-rewrite")
.run(args);
}
diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml
new file mode 100644
index 0000000000..40a52ded0f
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml
@@ -0,0 +1,8 @@
+# Enable this profile to disable security
+spring:
+ autoconfigure:
+ exclude:
+ - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
+ - org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration
+ - org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration
+ - org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml
new file mode 100644
index 0000000000..b2656151db
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml
@@ -0,0 +1,11 @@
+spring:
+ cloud:
+ gateway:
+ routes:
+ - id: rewrite_v1
+ uri: ${rewrite.backend.uri:http://example.com}
+ predicates:
+ - Path=/v1/customer/**
+ filters:
+ - RewritePath=/v1/customer/(?.*),/api/$\{segment}
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java
new file mode 100644
index 0000000000..41fe37045c
--- /dev/null
+++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java
@@ -0,0 +1,109 @@
+package com.baeldung.springcloudgateway.rewrite;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+
+import org.junit.AfterClass;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import com.sun.net.httpserver.HttpServer;
+
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@ActiveProfiles({ "nosecurity", "url-rewrite" })
+class URLRewriteGatewayApplicationLiveTest {
+
+ // NOTE for Eclipse users: By default, Eclipse will complain about com.sun.** classes.
+ // To solve this issue, follow instructions available at the :
+ // https://stackoverflow.com/questions/13155734/eclipse-cant-recognize-com-sun-net-httpserver-httpserver-package
+ private static HttpServer mockServer;
+ private static Logger log = LoggerFactory.getLogger(URLRewriteGatewayApplicationLiveTest.class);
+
+ // Create a running HttpServer that echoes back the request URL.
+ private static HttpServer startTestServer() {
+
+ try {
+ log.info("[I26] Starting mock server");
+ mockServer = HttpServer.create();
+ mockServer.bind(new InetSocketAddress(0), 0);
+ mockServer.createContext("/api", (xchg) -> {
+ String uri = xchg.getRequestURI()
+ .toString();
+ log.info("[I23] Backend called: uri={}", uri);
+ xchg.getResponseHeaders()
+ .add("Content-Type", "text/plain");
+ xchg.sendResponseHeaders(200, 0);
+ OutputStream os = xchg.getResponseBody();
+ os.write(uri.getBytes());
+ os.flush();
+ os.close();
+ });
+
+ mockServer.start();
+ InetSocketAddress localAddr = mockServer.getAddress();
+ log.info("[I36] mock server started: local address={}", localAddr);
+
+ return mockServer;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+
+ }
+
+ // TIP: https://www.baeldung.com/spring-dynamicpropertysource
+ @DynamicPropertySource
+ static void registerBackendServer(DynamicPropertyRegistry registry) {
+ registry.add("rewrite.backend.uri", () -> {
+ HttpServer s = startTestServer();
+ return "http://localhost:" + s.getAddress().getPort();
+ });
+ }
+
+ @AfterClass
+ public static void stopMockBackend() throws Exception {
+ log.info("[I40] Shutdown mock http server");
+ mockServer.stop(5);
+ }
+
+ @LocalServerPort
+ private int localPort;
+
+ @Test
+ void testWhenApiCall_thenRewriteSuccess(@Autowired WebTestClient webClient) {
+ webClient.get()
+ .uri("http://localhost:" + localPort + "/v1/customer/customer1")
+ .exchange()
+ .expectBody()
+ .consumeWith((result) -> {
+ String body = new String(result.getResponseBody());
+ log.info("[I99] body={}", body);
+ assertEquals("/api/customer1", body);
+ });
+ }
+
+ @Test
+ void testWhenDslCall_thenRewriteSuccess(@Autowired WebTestClient webClient) {
+ webClient.get()
+ .uri("http://localhost:" + localPort + "/v2/zip/123456")
+ .exchange()
+ .expectBody()
+ .consumeWith((result) -> {
+ String body = new String(result.getResponseBody());
+ log.info("[I99] body={}", body);
+ assertTrue(body.matches("/api/zip/123456-\\d{3}"));
+ });
+ }
+
+}
From 082d48e291d1799eb84c3cfc431147e71712bd71 Mon Sep 17 00:00:00 2001
From: vunamtien
Date: Tue, 22 Feb 2022 00:35:48 +0700
Subject: [PATCH 139/235] BAEL-5379-create-simple-rock-paper-scissors-game
(#11846)
Co-authored-by: tienvn4
---
.../baeldung/game/RockPaperScissorsGame.java | 66 +++++++++++++++++++
1 file changed, 66 insertions(+)
create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
new file mode 100644
index 0000000000..fc9299f12d
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
@@ -0,0 +1,66 @@
+package com.baeldung.game;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+import java.util.Scanner;
+
+class RockPaperScissorsGame {
+
+ private static Map movesMap = new HashMap() {{
+ put(0, "rock");
+ put(1, "paper");
+ put(2, "scissors");
+ }};
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ int wins = 0;
+ int losses = 0;
+
+ System.out.println("Welcome to Rock-Paper-Scissors! Please enter \"rock\", \"paper\", \"scissors\", or \"quit\" to exit.");
+
+ while (true) {
+ System.out.println("-------------------------");
+ System.out.print("Enter your move: ");
+ String playerMove = scanner.nextLine();
+
+ if (playerMove.equals("quit")) {
+ System.out.println("You won " + wins + " times and lost " + losses + " times.");
+ System.out.println("Thanks for playing! See you again.");
+ break;
+ }
+
+ if (!movesMap.containsValue(playerMove)) {
+ System.out.println("Your move isn't valid!");
+ continue;
+ }
+
+ String computerMove = getComputerMove();
+
+ if (playerMove.equals(computerMove)) {
+ System.out.println("It's a tie!");
+ } else if (isPlayerWin(playerMove, computerMove)) {
+ System.out.println("You won!");
+ wins++;
+ } else {
+ System.out.println("You lost!");
+ losses++;
+ }
+ }
+ }
+
+ private static boolean isPlayerWin(String playerMove, String computerMove) {
+ return playerMove.equals("rock") && computerMove.equals("scissors")
+ || (playerMove.equals("scissors") && computerMove.equals("paper"))
+ || (playerMove.equals("paper") && computerMove.equals("rock"));
+ }
+
+ private static String getComputerMove() {
+ Random random = new Random();
+ int randomNumber = random.nextInt(3);
+ String computerMove = movesMap.get(randomNumber);
+ System.out.println("Computer move: " + computerMove);
+ return computerMove;
+ }
+}
\ No newline at end of file
From 5ee332c6061ab0fb2e99b2aa7ceb418450d181cb Mon Sep 17 00:00:00 2001
From: Eugene Kovko <37694937+eukovko@users.noreply.github.com>
Date: Tue, 22 Feb 2022 02:05:08 +0100
Subject: [PATCH 140/235] BAEL-5349 Example for the difference between map and
hashmap (#11827)
* example for the difference between map and hashmap
* unit tests for the example
* rename unit tests
Co-authored-by: eugene.kovko
---
.../java/com/baeldung/mapandhashmap/Main.java | 25 +++++++
.../mapandhashmap/printer/HashMapPrinter.java | 13 ++++
.../mapandhashmap/printer/MapPrinter.java | 13 ++++
.../mapandhashmap/printer/MapReporter.java | 19 +++++
.../printer/HashMapPrinterUnitTest.java | 56 ++++++++++++++
.../printer/MapPrinterUnitTest.java | 71 ++++++++++++++++++
.../printer/MapReporterUnitTest.java | 74 +++++++++++++++++++
7 files changed, 271 insertions(+)
create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java
diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java
new file mode 100644
index 0000000000..1024399a98
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java
@@ -0,0 +1,25 @@
+package com.baeldung.mapandhashmap;
+
+import com.baeldung.mapandhashmap.printer.HashMapPrinter;
+import com.baeldung.mapandhashmap.printer.MapPrinter;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class Main {
+ public static void main(String[] args) {
+ Map map = new HashMap<>();
+ HashMap hashMap = new HashMap<>();
+ TreeMap treeMap = new TreeMap<>();
+
+ HashMapPrinter hashMapPrinter = new HashMapPrinter();
+ hashMapPrinter.printMap(hashMap);
+// hashMapPrinter.printMap(treeMap); Compile time error
+// hashMapPrinter.printMap(map); Compile time error
+
+ MapPrinter mapPrinter = new MapPrinter();
+ mapPrinter.printMap(hashMap);
+ mapPrinter.printMap(treeMap);
+ mapPrinter.printMap(map);
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java
new file mode 100644
index 0000000000..53c78bfc55
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java
@@ -0,0 +1,13 @@
+package com.baeldung.mapandhashmap.printer;
+
+import java.util.HashMap;
+import java.util.Map.Entry;
+
+public class HashMapPrinter {
+
+ public void printMap(final HashMap, ?> map) {
+ for (final Entry, ?> entry : map.entrySet()) {
+ System.out.println(entry.getKey() + " " + entry.getValue());
+ }
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java
new file mode 100644
index 0000000000..e5c0ab49cd
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java
@@ -0,0 +1,13 @@
+package com.baeldung.mapandhashmap.printer;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class MapPrinter {
+
+ public void printMap(final Map, ?> map) {
+ for (final Entry, ?> entry : map.entrySet()) {
+ System.out.println(entry.getKey() + " " + entry.getValue());
+ }
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java
new file mode 100644
index 0000000000..fd7347c2d1
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java
@@ -0,0 +1,19 @@
+package com.baeldung.mapandhashmap.printer;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class MapReporter {
+
+ private final Map, ?> map;
+
+ public MapReporter(final Map, ?> map) {
+ this.map = map;
+ }
+
+ public void printMap() {
+ for (final Entry, ?> entry : this.map.entrySet()) {
+ System.out.println(entry.getKey() + " " + entry.getValue());
+ }
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java
new file mode 100644
index 0000000000..e1147f6e00
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.mapandhashmap.printer;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class HashMapPrinterUnitTest {
+
+ private final HashMapPrinter mapPrinter = new HashMapPrinter();
+ private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
+
+ @BeforeEach
+ public void setUp() {
+ System.setOut(new PrintStream(outputStreamCaptor));
+ }
+
+ @Test
+ @DisplayName("Test hash map printer with HashMap")
+ void testPrintHashMap() {
+ // given
+ String key = "HashMap";
+ String value = "Main default implementation for the Map interface";
+ String expected = key + " " + value;
+ HashMap map = new HashMap<>();
+ map.put(key, value);
+ // when
+ mapPrinter.printMap(map);
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+
+ }
+
+ @Test
+ @DisplayName("Test hash map printer with LinkedHash")
+ void testPrintLinkedHashMap() {
+ // given
+ String key = "LinkedHashMap";
+ String value = "Use this implementation if you need keep the order of elements";
+ String expected = key + " " + value;
+ LinkedHashMap map = new LinkedHashMap<>();
+ map.put(key, value);
+ // when
+ mapPrinter.printMap(map);
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java
new file mode 100644
index 0000000000..8c45758bdf
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.mapandhashmap.printer;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.TreeMap;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class MapPrinterUnitTest {
+
+ private final MapPrinter mapPrinter = new MapPrinter();
+ private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
+
+ @BeforeEach
+ public void setUp() {
+ System.setOut(new PrintStream(outputStreamCaptor));
+ }
+
+ @Test
+ @DisplayName("Test printer with TreeMap")
+ void testPrintTreeMap() {
+ // given
+ String key = "TreeMap";
+ String value = "Used when sorting is needed";
+ String expected = key + " " + value;
+ TreeMap map = new TreeMap<>();
+ map.put(key, value);
+ // when
+ mapPrinter.printMap(map);
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+
+ @Test
+ @DisplayName("Test printer with HashMap")
+ void testPrintHashMap() {
+ // given
+ String key = "HashMap";
+ String value = "Main default implementation for the Map interface";
+ String expected = key + " " + value;
+ HashMap map = new HashMap<>();
+ map.put(key, value);
+ // when
+ mapPrinter.printMap(map);
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+
+ @Test
+ @DisplayName("Test printer with LinkedHash")
+ void testPrintLinkedHashMap() {
+ // given
+ String key = "LinkedHashMap";
+ String value = "Use this implementation if you need keep the order of elements";
+ String expected = key + " " + value;
+ LinkedHashMap map = new LinkedHashMap<>();
+ map.put(key, value);
+ // when
+ mapPrinter.printMap(map);
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java
new file mode 100644
index 0000000000..8f858a75c4
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.mapandhashmap.printer;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.TreeMap;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class MapReporterUnitTest {
+
+ private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
+
+ @BeforeEach
+ public void setUp() {
+ System.setOut(new PrintStream(outputStreamCaptor));
+ }
+
+ @Test
+ @DisplayName("Test reporter with TreeMap")
+ void testPrintTreeMap() {
+ // given
+ String key = "TreeMap";
+ String value = "Used when sorting is needed";
+ String expected = key + " " + value;
+ TreeMap map = new TreeMap<>();
+ map.put(key, value);
+ // when
+ MapReporter mapReporter = new MapReporter(map);
+ mapReporter.printMap();
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+
+ @Test
+ @DisplayName("Test reporter with HashMap")
+ void testPrintHashMap() {
+ // given
+ String key = "HashMap";
+ String value = "Main default implementation for the Map interface";
+ String expected = key + " " + value;
+ HashMap map = new HashMap<>();
+ map.put(key, value);
+ // when
+ MapReporter mapReporter = new MapReporter(map);
+ mapReporter.printMap();
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+
+ @Test
+ @DisplayName("Test reporter with LinkedHash")
+ void testPrintLinkedHashMap() {
+ // given
+ String key = "LinkedHashMap";
+ String value = "Use this implementation if you need keep the order of elements";
+ String expected = key + " " + value;
+ LinkedHashMap map = new LinkedHashMap<>();
+ map.put(key, value);
+ // when
+ MapReporter mapReporter = new MapReporter(map);
+ mapReporter.printMap();
+ // then
+ String actual = outputStreamCaptor.toString().trim();
+ assertThat(actual).isEqualTo(expected);
+ }
+
+}
\ No newline at end of file
From 26a0093154832f9162df2baabd884d43aabb8884 Mon Sep 17 00:00:00 2001
From: alemoles
Date: Mon, 21 Feb 2022 22:13:41 -0500
Subject: [PATCH 141/235] BAEL-5391 - Java Error "Missing return statement"
(#5) (#11845)
* BAEL-5391 - Java Error "Missing return statement" (#5)
* BAEL-5391 - Java Error "Missing return statement"
---
.../MissingReturnStatement.java | 41 +++++++++++++++++++
.../MissingReturnStatementUnitTest.java | 38 +++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java
create mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java
diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java
new file mode 100644
index 0000000000..d76ae76a0e
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java
@@ -0,0 +1,41 @@
+package com.baeldung.exception.missingreturnstatement;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class MissingReturnStatement {
+ public static void main(String[] args) {
+ int a = -12;
+ int result = pow(a);
+ System.out.println(result);
+ Map dictionary = createDictionary();
+ dictionary.forEach((s, integer) -> System.out.println(s + " " + integer));
+ }
+
+ public static int pow(int number) {
+ int pow = number * number;
+ return pow;
+ }
+
+ public static String checkNumber(int number) {
+ if (number == 0) {
+ return "It's equals to zero";
+ }
+
+ for (int i = 0; i < number; i++) {
+ if (i > 100) {
+ return "It's a big number";
+ }
+ }
+ return "It's a negative number";
+ }
+
+ public static Map createDictionary() {
+ List words = Arrays.asList("Hello", "World");
+ return words.stream()
+ .collect(Collectors.toMap(s -> s, s -> 1));
+ }
+
+}
diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java
new file mode 100644
index 0000000000..97a050a3f0
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.exception.missingreturnstatement;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Map;
+
+import org.junit.Test;
+
+public class MissingReturnStatementUnitTest {
+
+ @Test
+ public void givenANumber_thenReturnItsPow() {
+ int number = 10;
+ int pow = MissingReturnStatement.pow(number);
+ assertEquals(100, pow);
+ }
+
+ @Test
+ public void givenABigNumber_thenReturnItsType() {
+ int number = 200;
+ String type = MissingReturnStatement.checkNumber(number);
+ assertEquals("It's a big number", type);
+ }
+
+ @Test
+ public void givenANegativeNumber_thenReturnItsType() {
+ int number = -10;
+ String type = MissingReturnStatement.checkNumber(number);
+ assertEquals("It's a negative number", type);
+ }
+
+ @Test
+ public void getStringDictionary_thenPrintValues() {
+ Map dictionary = MissingReturnStatement.createDictionary();
+ assertEquals(2, dictionary.size());
+ dictionary.forEach((s, integer) -> System.out.println(s + " - " + integer));
+ }
+}
\ No newline at end of file
From d00308836475c4669916b4506c7251496cf4142f Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Tue, 22 Feb 2022 12:01:06 +0530
Subject: [PATCH 142/235] JAVA-10081 :Create new module hibernate-mapping from
spring-hibernate-5 module
---
.../hibernate-many-to-many/.gitignore | 13 ++
.../hibernate-many-to-many/README.md | 7 +
.../_2.fdt | Bin 0 -> 160 bytes
.../_2.fdx | Bin 0 -> 84 bytes
.../_2.fnm | Bin 0 -> 532 bytes
.../_2.nvd | Bin 0 -> 65 bytes
.../_2.nvm | Bin 0 -> 88 bytes
.../_2.si | Bin 0 -> 514 bytes
.../_2.tvd | Bin 0 -> 392 bytes
.../_2.tvx | Bin 0 -> 79 bytes
.../_2_Lucene50_0.doc | Bin 0 -> 190 bytes
.../_2_Lucene50_0.pos | Bin 0 -> 162 bytes
.../_2_Lucene50_0.tim | Bin 0 -> 914 bytes
.../_2_Lucene50_0.tip | Bin 0 -> 195 bytes
.../_3.cfe | Bin 0 -> 341 bytes
.../_3.cfs | Bin 0 -> 2119 bytes
.../_3.si | Bin 0 -> 371 bytes
.../segments_5 | Bin 0 -> 198 bytes
.../write.lock | 0
.../hibernate-many-to-many/pom.xml | 136 ++++++++++++++
.../hibernate/manytomany/model/Employee.java | 176 +++++++++---------
.../hibernate/manytomany/model/Project.java | 122 ++++++------
.../manytomany/util/HibernateUtil.java | 90 ++++-----
.../manytomany/spring/PersistenceConfig.java | 140 +++++++-------
.../persistence/dao/common/AbstractDao.java | 14 ++
.../dao/common/AbstractHibernateDao.java | 59 ++++++
.../persistence/dao/common/IOperations.java | 20 ++
.../manytomany/dao/IEmployeeDao.java | 16 +-
.../manytomany/dao/IProjectDao.java | 16 +-
.../manytomany/dao/impl/EmployeeDao.java | 32 ++--
.../manytomany/dao/impl/ProjectDao.java | 34 ++--
.../baeldung/spring/PersistenceConfig.java | 75 ++++++++
.../src/main/resources/import.sql | 31 +++
.../src/main/resources/logback.xml | 19 ++
.../src/main/resources/manytomany.cfg.xml | 30 +--
.../main/resources/persistence-h2.properties | 21 +++
.../java/com/baeldung/SpringContextTest.java | 19 ++
...notationJavaConfigMainIntegrationTest.java | 98 +++++-----
...nyToManyAnnotationMainIntegrationTest.java | 160 ++++++++--------
.../src/test/resources/.gitignore | 13 ++
.../hibernate/criteria/model/Item.hbm.xml | 22 +++
.../src/test/resources/import.sql | 21 +++
.../src/test/resources/manytomany.cfg.xml | 0
.../spring-hibernate-5/README.md | 1 -
.../spring-hibernate-5/pom.xml | 20 ++
.../src/test/resources/import.sql | 1 +
46 files changed, 948 insertions(+), 458 deletions(-)
create mode 100644 persistence-modules/hibernate-many-to-many/.gitignore
create mode 100644 persistence-modules/hibernate-many-to-many/README.md
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvd
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvx
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.doc
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.pos
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tim
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5
create mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock
create mode 100644 persistence-modules/hibernate-many-to-many/pom.xml
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java (96%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java (95%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java (97%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java (97%)
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java (96%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java (96%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java (96%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java (96%)
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/main/resources/manytomany.cfg.xml (98%)
create mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
create mode 100644 persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java (97%)
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java (96%)
create mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
create mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
create mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
rename persistence-modules/{spring-hibernate-5 => hibernate-many-to-many}/src/test/resources/manytomany.cfg.xml (100%)
diff --git a/persistence-modules/hibernate-many-to-many/.gitignore b/persistence-modules/hibernate-many-to-many/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/README.md b/persistence-modules/hibernate-many-to-many/README.md
new file mode 100644
index 0000000000..19b865d4e1
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/README.md
@@ -0,0 +1,7 @@
+## Hibernate 5 with Spring
+
+This module contains articles about Hibernate 5 with Spring.
+
+### Relevant articles
+
+- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt
new file mode 100644
index 0000000000000000000000000000000000000000..d71a08150212e0d18327d1491c3687976b1c0d38
GIT binary patch
literal 160
zcmcD&o+B>fQ<|KbmuhMdT#{dun&Ot3nv+uOmRMZkl30?+z`($mbzSAP`{iOo;d#DB
z{fW~w7#bQFnHYE&m>Bf`D==s!=jZArB?2{-=B4XpWG1B+d6=BK3Q
y=miwzr<5j_a4;I`Gf2xDfe2#|VFDsd^%=wiK$2#Rj0ZF(zW`bZ2Af23UjYC|kS^)~
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx
new file mode 100644
index 0000000000000000000000000000000000000000..72359255c620cb440b643215ce0e4a85f205da77
GIT binary patch
literal 84
zcmcD&o+B>nQ<|KbmuhMdT#{dun&Ot3nv+uOmRMZknU|7U!N9=4m~~y{wfp5_L*aS8
hM*WG?G#Ho|fuamnK+Mp`ctB(F3!o}62&>U62LPU67+U}U
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm
new file mode 100644
index 0000000000000000000000000000000000000000..b0143e1ac5e967810feee7771557bca5f71a4922
GIT binary patch
literal 532
zcmcD&o+B>gQ<|KbmuhO@mYJH9;+dD0U(CS3z?gMi<+c0eVngA1zDE6t(=-@Z1>!R@
zlTwTF5=&C!lXDV_iy4@h8U8~7lWah05!i%){Nj?#y!2wX{G!~%61_Aq#R0Pfm$Ks0
zw6x3$MgykI6h;~t%Uw{EpHiA!;+L44%EU;0XLF~d7AF^F7L;V>=P}d3e74-w-29?S
W7A8ijhxh@F$uEEr4hGV{B@6-GbkQ<|KbmuhP4mtT}y?2=fL$N&Uc*HvD-UoJKjp66@SpEyl}p`^5=qP+Zo
P#^e_uX%J`#I_?Dk?LHOl
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm
new file mode 100644
index 0000000000000000000000000000000000000000..19f60a39bcf9a121ca3bc1590ba6df45481bf44a
GIT binary patch
literal 88
zcmcD&o+B>mQ<|KbmuhP4mtT}y?3-GWn37nM$N&Uc*HvD-UoJKjp66@SpEyl}fe9oE
b0_Dt%5C((xe<0vLpfULcRDfZE({vpGz#bVo
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si
new file mode 100644
index 0000000000000000000000000000000000000000..3d537083b422c76bfcef3c42fb25ad1eeb45bf4f
GIT binary patch
literal 514
zcmZWm-AcnS7+u9~xJ_kF@X}p)F_49(cGKM`sGA6z3LSV^LX*u()08Bwdy8ENUivJ)
zgBN=R!3XeC(?5_cA^AAx`_AEzTrB;A<|uMWK)QxaW|Rc-Hkh(fsiZwGkG^j{1#G^L
z%>{aEE3TyfJLTW{1{2jsFTm_Yw4hOYMlk|0QJC-DbL9G@b;WqdIFcR<>Uoeh~}|{1}jVe#N8(yQQWik
zQ)?at(xar1ultt;i?~bl)UlS{L*z=vHCR=Cd9F=p0Ank05)#pH8}_U&JhRM`Qv+J{
zvSWfE#=0uPOMr}VQl?mDXx?y4r+8<_03j2ZhNfddR`BW=X6}kmC0JuZ?Xa-6Rc?ZZ
k9`UglGER{Mlwnf69M}`bei#g{KiaQf$xkNh=X|#K1BMr#*8l(j
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd
new file mode 100644
index 0000000000000000000000000000000000000000..b46c8d109cc2a907cd84fbbf6e87ad51cff7929d
GIT binary patch
literal 392
zcmW-dze`(D6vxlgC=Ftbkz&VE+Y%kb7xR(~f;J6xskBJ7;&$@h$$eMukH@|D5#1c@
zY@rZ05n3p562ZMwXQ6|CK$p@kP90qA)dSxH-w)?}hwt*0n4W%<$D}A)cuz)dQtY&`
zZFC3#!OqpQzpFoOICZ>MJ;Z(mhW4MpC=5S6J3Rp?TztHUHa12|C4al(ec7uGFuV`N
zwtdxl{be0L)M|6li$@3D#^4}aXWR8M+x#~3{HS=hKLx>c1%=gFCMeF0A>~LVU5v?S
znR1r$L}+IvNp1G5MB}nlE2>6yT!fHycnKzVAHu{-D2z5B46Dsq7;C_JiiUB;x<2JC
z{0js+vW_b<#BzbA1vkY!%e3)~^|&EH*1D7{AFu^KP$fq5gc(A&1lJEdWhiiWuVWi1
zZLV0H5@vs(@86~Fa6$8MJKp0e(LK9Ztw#&2BXY@6^4MsryRHdSk84eMcW;8=d*$dQ<|KbmuhMdl3J7-mYQ6WUsUXwmy%k+z`($mbzSAP`{iOo;d#DB{fW~w
c7?>D=q6{WL%lQ<|KbmuhMdkY8MqnU`K1UX)pqTI7lQ<|KbmuhMdkY8MqnU`K1UX)pqS_I@V072GumDlcM>D0O1m)+6Xon>a0yL6Ju
zPB5UIt(}E`f&YVGdMiQjZ}81-E~Sw9*!Mke-tWy$&h(9yN7^KB4lKX{*up(gi6?}x
z*JpSCJpJLeS3f@=zLy_2d(Y|wN*E1Z4#)(+SyRNB1?i()WjRx+P*rY95IW@bkya%{+IS}l
zD2zQ8g_$Z19Sd2lrR}*wTHi$UTwPVhhN?R=Ri|!pY
zU}+~qDjJ_4PtwPPQ1s#)4eVlYj=Dxd(kyhtg(^aYXnj$PsFP(_UTSb9ySE;6O@d^d4#s+OQVVr!snE98D%uaoJ%K^ar7cF
zA>#Ha<=ewOJ{*nN&XA9H2Yfsl(7m=nB9mIqk6AW7hdb7Fq2!f9CDu4|ud%Q3
z)|O}=w*Qa=sf%)2=veIo2S29o{)`q
GU*tdZxy^3?
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip
new file mode 100644
index 0000000000000000000000000000000000000000..9803f1b398829ace933101fbc393ea47807267f3
GIT binary patch
literal 195
zcmcD&o+B>ol#`#F9a5B<8j@O+TkM&al3KyQz`&GsUFEg=&diPJQ=d`gp3
z^HNO>;tlM9+L+yfLx9Ry85o(FA2Bg7FfyQtvaZ7>%C`xdDE~WbqC%6vqUOHImHmuB
VyFg&+0gcHoAWQ~^%eLE20RSolE8PG9
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe
new file mode 100644
index 0000000000000000000000000000000000000000..8fb074f30e754beeb8a030f31d07de2babe63b62
GIT binary patch
literal 341
zcmcD&o+B>qQ<|KbmuhO@oS$2eUz(TVnpaYknOe*M1X
zMK3L-0we_ldJu{sm_;wIECtGGgwodh@i2qq4fG1~!R7(w_CVz$QRGwdlOf`aqEPuf
z6#0_OT&R3Agl1A?(JO&j%De=sX$r_CP?aneP{9bGoAY3T6QJ5fKprW9aM)nl8$o75
heaEf})$WhxkOGJ}J5)2n;R70zUqIC|B=Stl1OR>yJ!${|
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs
new file mode 100644
index 0000000000000000000000000000000000000000..e26078b9e7cfbaca6e06ec3cf3156f48d0b92d08
GIT binary patch
literal 2119
zcmcIl%TE(Q7@wKl?Nj9~Z^TD}V5}4bjIXK?ltcL?Vgcc6Uk_yF1P9Ho&d%ZHikvL|pRoxVQ^K
z83{+s+sl-S$2ZRGxRR1B3lRZvSZ<_#keUvHD~?{6F0vg-IFEoEWVdZrCXvvlaVybO
zd<3xJbWT_UvQ7y;{ItU=wG>lJ+Zr>3Bf$6RRA=Ul2s+O7`|vvMJrf^(q(=FfsB`Js
zdh6tGi|wZ)o5chXa%rs*9YE3nP;9|rzY@LhlP6H+Cg2g^emCA_KJlIwzKdsR=fI@nK?+`vA14I
OvhREg-uJeq`PhGT-i
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si
new file mode 100644
index 0000000000000000000000000000000000000000..f2d6b6a030c291e9fdddf28b924e5caad9a02f57
GIT binary patch
literal 371
zcmcD&o+B>oQ<|KbmuhMdoSL4SnpfhPmzK}Kz`&SwUFEg=&diPN-zVhpTE
zn30i-DZiL2JTosPzr0w%(11HDu`E%qEEUKv67nxfOwLJFaLz9($S+DP$;{8=fl3z@
z13B!5hI$5ihKBqQ!Cas=u(%*pT-#FDCnQ+c(9(o22kbnU0#;K!AY{)k)=Ml(&R|W<
zO))bO0UJ_OnpcvUn+j8iX%bs;erZv1Dr;I!X>kS@&;+QREQSVp2Am+h#U+Wk1-yo4
zCZ>iKCPv2Q#-`@XtntQr#hGkCGC8dnLZvdw!^5m3zbG}uEi*MIrPwXMC^xZ0FE>9W
cmCMOBI3zwez}3~|fX3t(pr8YRcS#F10cJaIr~m)}
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5 b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5
new file mode 100644
index 0000000000000000000000000000000000000000..66a4c385a5adac5ff16e505da6de875fcd295c3d
GIT binary patch
literal 198
zcmcD&o+HjtoSL4SnpaZHz`($kbzSAP`{iOo;d#DB{fX1G8BJMPS%DHDAOOTHK+FUb
zVv09nL{qE5;ZvHNnwM&7@*fI7nqX`g4H9EuiZ@2rtwp?Uh65UtUx3X45?V&3b^sz|
BR7L;*
literal 0
HcmV?d00001
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/persistence-modules/hibernate-many-to-many/pom.xml b/persistence-modules/hibernate-many-to-many/pom.xml
new file mode 100644
index 0000000000..6f1abb6a7a
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/pom.xml
@@ -0,0 +1,136 @@
+
+
+ 4.0.0
+ hibernate-many-to-many
+ 0.1-SNAPSHOT
+ hibernate-many-to-many
+
+
+ com.baeldung
+ persistence-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+ org.springframework
+ spring-context
+ ${org.springframework.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.springframework
+ spring-aspects
+ ${org.springframework.version}
+
+
+
+ org.springframework
+ spring-orm
+ ${org.springframework.version}
+
+
+ org.springframework.data
+ spring-data-jpa
+ ${org.springframework.data.version}
+
+
+ org.hibernate
+ hibernate-core
+ ${hibernate.version}
+
+
+ javax.transaction
+ jta
+ ${jta.version}
+
+
+ org.hibernate
+ hibernate-search-orm
+ ${hibernatesearch.version}
+
+
+ org.apache.tomcat
+ tomcat-dbcp
+ ${tomcat-dbcp.version}
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+ test
+
+
+ org.springframework
+ spring-test
+ ${org.springframework.version}
+ test
+
+
+ org.springframework.security
+ spring-security-test
+ ${org.springframework.security.version}
+ test
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+
+
+ com.h2database
+ h2
+ ${h2.version}
+
+
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 2.3.2
+
+
+ com.sun.xml.bind
+ jaxb-core
+ 2.3.0.1
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.1
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ 2.3.1
+
+
+
+
+
+ 5.0.2.RELEASE
+ 1.10.6.RELEASE
+ 4.2.1.RELEASE
+
+ 5.2.10.Final
+ 5.8.2.Final
+ 9.0.0.M26
+ 1.1
+ 2.3.4
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
index 8157945e2c..bfe1b5ad29 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
@@ -1,88 +1,88 @@
-package com.baeldung.hibernate.manytomany.model;
-
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
-
-@Entity
-@Table(name = "Employee")
-public class Employee implements Serializable {
- @Id
- @Column(name = "employee_id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long employeeId;
-
- @Column(name = "first_name")
- private String firstName;
-
- @Column(name = "last_name")
- private String lastName;
-
- @ManyToMany(cascade = { CascadeType.ALL })
- @JoinTable(
- name = "Employee_Project",
- joinColumns = { @JoinColumn(name = "employee_id") },
- inverseJoinColumns = { @JoinColumn(name = "project_id") }
- )
- Set projects = new HashSet();
-
-
- public Employee() {
- super();
- }
-
- public Employee(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- public Employee(String firstName, String lastName, Set projects) {
- this.firstName = firstName;
- this.lastName = lastName;
- this.projects = projects;
- }
-
-
- public Long getEmployeeId() {
- return employeeId;
- }
-
- public void setEmployeeId(Long employeeId) {
- this.employeeId = employeeId;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public Set getProjects() {
- return projects;
- }
-
- public void setProjects(Set projects) {
- this.projects = projects;
- }
-}
+package com.baeldung.hibernate.manytomany.model;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "Employee")
+public class Employee implements Serializable {
+ @Id
+ @Column(name = "employee_id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long employeeId;
+
+ @Column(name = "first_name")
+ private String firstName;
+
+ @Column(name = "last_name")
+ private String lastName;
+
+ @ManyToMany(cascade = { CascadeType.ALL })
+ @JoinTable(
+ name = "Employee_Project",
+ joinColumns = { @JoinColumn(name = "employee_id") },
+ inverseJoinColumns = { @JoinColumn(name = "project_id") }
+ )
+ Set projects = new HashSet();
+
+
+ public Employee() {
+ super();
+ }
+
+ public Employee(String firstName, String lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ }
+
+ public Employee(String firstName, String lastName, Set projects) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.projects = projects;
+ }
+
+
+ public Long getEmployeeId() {
+ return employeeId;
+ }
+
+ public void setEmployeeId(Long employeeId) {
+ this.employeeId = employeeId;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public Set getProjects() {
+ return projects;
+ }
+
+ public void setProjects(Set projects) {
+ this.projects = projects;
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
similarity index 95%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
index d6c049f33e..c291d7d7af 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
@@ -1,61 +1,61 @@
-package com.baeldung.hibernate.manytomany.model;
-
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
-
-@Entity
-@Table(name = "Project")
-public class Project implements Serializable {
-
- @Id
- @Column(name = "project_id")
- @GeneratedValue
- private Long projectId;
-
- @Column(name = "title")
- private String title;
-
- @ManyToMany(mappedBy = "projects")
- private Set employees = new HashSet();
-
- public Project() {
- super();
- }
-
- public Project(String title) {
- this.title = title;
- }
-
- public Long getProjectId() {
- return projectId;
- }
-
- public void setProjectId(Long projectId) {
- this.projectId = projectId;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Set getEmployees() {
- return employees;
- }
-
- public void setEmployees(Set employees) {
- this.employees = employees;
- }
-
-
-}
+package com.baeldung.hibernate.manytomany.model;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "Project")
+public class Project implements Serializable {
+
+ @Id
+ @Column(name = "project_id")
+ @GeneratedValue
+ private Long projectId;
+
+ @Column(name = "title")
+ private String title;
+
+ @ManyToMany(mappedBy = "projects")
+ private Set employees = new HashSet();
+
+ public Project() {
+ super();
+ }
+
+ public Project(String title) {
+ this.title = title;
+ }
+
+ public Long getProjectId() {
+ return projectId;
+ }
+
+ public void setProjectId(Long projectId) {
+ this.projectId = projectId;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Set getEmployees() {
+ return employees;
+ }
+
+ public void setEmployees(Set employees) {
+ this.employees = employees;
+ }
+
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
similarity index 97%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
index 29e8d7515a..ff035c0c37 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
@@ -1,45 +1,45 @@
-package com.baeldung.hibernate.manytomany.util;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.service.ServiceRegistry;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HibernateUtil {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
- private static SessionFactory sessionFactory;
-
- private static SessionFactory buildSessionFactory() {
- try {
- // Create the SessionFactory from hibernate-annotation.cfg.xml
- Configuration configuration = new Configuration();
- configuration.addAnnotatedClass(Employee.class);
- configuration.addAnnotatedClass(Project.class);
- configuration.configure("manytomany.cfg.xml");
- LOGGER.debug("Hibernate Annotation Configuration loaded");
-
- ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
- .build();
- LOGGER.debug("Hibernate Annotation serviceRegistry created");
-
- SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
-
- return sessionFactory;
- } catch (Throwable ex) {
- LOGGER.error("Initial SessionFactory creation failed.", ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- public static SessionFactory getSessionFactory() {
- if (sessionFactory == null) {
- sessionFactory = buildSessionFactory();
- }
- return sessionFactory;
- }
-}
+package com.baeldung.hibernate.manytomany.util;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.service.ServiceRegistry;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HibernateUtil {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
+ private static SessionFactory sessionFactory;
+
+ private static SessionFactory buildSessionFactory() {
+ try {
+ // Create the SessionFactory from hibernate-annotation.cfg.xml
+ Configuration configuration = new Configuration();
+ configuration.addAnnotatedClass(Employee.class);
+ configuration.addAnnotatedClass(Project.class);
+ configuration.configure("manytomany.cfg.xml");
+ LOGGER.debug("Hibernate Annotation Configuration loaded");
+
+ ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
+ .build();
+ LOGGER.debug("Hibernate Annotation serviceRegistry created");
+
+ SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
+
+ return sessionFactory;
+ } catch (Throwable ex) {
+ LOGGER.error("Initial SessionFactory creation failed.", ex);
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
+
+ public static SessionFactory getSessionFactory() {
+ if (sessionFactory == null) {
+ sessionFactory = buildSessionFactory();
+ }
+ return sessionFactory;
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
similarity index 97%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
index b8e7e1b2fd..f7179b07e5 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
@@ -1,70 +1,70 @@
-package com.baeldung.manytomany.spring;
-
-import java.util.Properties;
-import javax.sql.DataSource;
-import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.core.env.Environment;
-import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.orm.hibernate5.HibernateTransactionManager;
-import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-
-
-@Configuration
-@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.hibernate.manytomany" })
-public class PersistenceConfig {
-
- @Autowired
- private Environment env;
-
- @Bean
- public LocalSessionFactoryBean sessionFactory() {
- final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
- sessionFactory.setDataSource(restDataSource());
- sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
- sessionFactory.setHibernateProperties(hibernateProperties());
-
- return sessionFactory;
- }
-
- @Bean
- public DataSource restDataSource() {
- final BasicDataSource dataSource = new BasicDataSource();
- dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
- dataSource.setUrl(env.getProperty("jdbc.url"));
- dataSource.setUsername(env.getProperty("jdbc.user"));
- dataSource.setPassword(env.getProperty("jdbc.pass"));
-
- return dataSource;
- }
-
- @Bean
- public PlatformTransactionManager hibernateTransactionManager() {
- final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
- transactionManager.setSessionFactory(sessionFactory().getObject());
- return transactionManager;
- }
-
- @Bean
- public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
- return new PersistenceExceptionTranslationPostProcessor();
- }
-
- private final Properties hibernateProperties() {
- final Properties hibernateProperties = new Properties();
- hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
- hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
- hibernateProperties.setProperty("hibernate.show_sql", "false");
-
- return hibernateProperties;
- }
-}
+package com.baeldung.manytomany.spring;
+
+import java.util.Properties;
+import javax.sql.DataSource;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-h2.properties" })
+@ComponentScan({ "com.baeldung.hibernate.manytomany" })
+public class PersistenceConfig {
+
+ @Autowired
+ private Environment env;
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(restDataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public DataSource restDataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
+ dataSource.setUrl(env.getProperty("jdbc.url"));
+ dataSource.setUsername(env.getProperty("jdbc.user"));
+ dataSource.setPassword(env.getProperty("jdbc.pass"));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+ hibernateProperties.setProperty("hibernate.show_sql", "false");
+
+ return hibernateProperties;
+ }
+}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
new file mode 100644
index 0000000000..5a6c76a93a
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
@@ -0,0 +1,14 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+
+import com.google.common.base.Preconditions;
+
+public abstract class AbstractDao implements IOperations {
+
+ protected Class clazz;
+
+ protected final void setClazz(final Class clazzToSet) {
+ clazz = Preconditions.checkNotNull(clazzToSet);
+ }
+}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
new file mode 100644
index 0000000000..f34866d883
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
@@ -0,0 +1,59 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.common.base.Preconditions;
+
+@SuppressWarnings("unchecked")
+public abstract class AbstractHibernateDao extends AbstractDao implements IOperations {
+
+ @Autowired
+ protected SessionFactory sessionFactory;
+
+ // API
+
+ @Override
+ public T findOne(final long id) {
+ return (T) getCurrentSession().get(clazz, id);
+ }
+
+ @Override
+ public List findAll() {
+ return getCurrentSession().createQuery("from " + clazz.getName()).getResultList();
+ }
+
+ @Override
+ public void create(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().saveOrUpdate(entity);
+ }
+
+ @Override
+ public T update(final T entity) {
+ Preconditions.checkNotNull(entity);
+ return (T) getCurrentSession().merge(entity);
+ }
+
+ @Override
+ public void delete(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().delete(entity);
+ }
+
+ @Override
+ public void deleteById(final long entityId) {
+ final T entity = findOne(entityId);
+ Preconditions.checkState(entity != null);
+ delete(entity);
+ }
+
+ protected Session getCurrentSession() {
+ return sessionFactory.getCurrentSession();
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
new file mode 100644
index 0000000000..4ef99221ab
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
@@ -0,0 +1,20 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+import java.util.List;
+
+public interface IOperations {
+
+ T findOne(final long id);
+
+ List findAll();
+
+ void create(final T entity);
+
+ T update(final T entity);
+
+ void delete(final T entity);
+
+ void deleteById(final long entityId);
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
index d619807b64..5ba018dc52 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
@@ -1,8 +1,8 @@
-package com.baeldung.persistence.manytomany.dao;
-
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.persistence.dao.common.IOperations;
-
-public interface IEmployeeDao extends IOperations{
-
-}
+package com.baeldung.persistence.manytomany.dao;
+
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.persistence.dao.common.IOperations;
+
+public interface IEmployeeDao extends IOperations{
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
index 4a55714f8d..48fbb8bf6b 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
@@ -1,8 +1,8 @@
-package com.baeldung.persistence.manytomany.dao;
-
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.persistence.dao.common.IOperations;
-
-public interface IProjectDao extends IOperations{
-
-}
+package com.baeldung.persistence.manytomany.dao;
+
+import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.persistence.dao.common.IOperations;
+
+public interface IProjectDao extends IOperations{
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
index b062c00ff9..25fee8c379 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
@@ -1,16 +1,16 @@
-package com.baeldung.persistence.manytomany.dao.impl;
-
-import org.springframework.stereotype.Repository;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.persistence.dao.common.AbstractHibernateDao;
-import com.baeldung.persistence.manytomany.dao.IEmployeeDao;
-
-@Repository
-public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao {
-
- public EmployeeDao() {
- super();
-
- setClazz(Employee.class);
- }
-}
+package com.baeldung.persistence.manytomany.dao.impl;
+
+import org.springframework.stereotype.Repository;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.persistence.dao.common.AbstractHibernateDao;
+import com.baeldung.persistence.manytomany.dao.IEmployeeDao;
+
+@Repository
+public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao {
+
+ public EmployeeDao() {
+ super();
+
+ setClazz(Employee.class);
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
rename to persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
index 772026fbc1..8fc29a5de3 100644
--- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
@@ -1,17 +1,17 @@
-package com.baeldung.persistence.manytomany.dao.impl;
-
-import org.springframework.stereotype.Repository;
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.persistence.dao.common.AbstractHibernateDao;
-import com.baeldung.persistence.manytomany.dao.IProjectDao;
-
-
-@Repository
-public class ProjectDao extends AbstractHibernateDao implements IProjectDao {
-
- public ProjectDao() {
- super();
-
- setClazz(Project.class);
- }
-}
+package com.baeldung.persistence.manytomany.dao.impl;
+
+import org.springframework.stereotype.Repository;
+import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.persistence.dao.common.AbstractHibernateDao;
+import com.baeldung.persistence.manytomany.dao.IProjectDao;
+
+
+@Repository
+public class ProjectDao extends AbstractHibernateDao implements IProjectDao {
+
+ public ProjectDao() {
+ super();
+
+ setClazz(Project.class);
+ }
+}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
new file mode 100644
index 0000000000..e1ea3e2024
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
@@ -0,0 +1,75 @@
+package com.baeldung.spring;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-h2.properties" })
+@ComponentScan({ "com.baeldung.persistence" })
+public class PersistenceConfig {
+
+ @Autowired
+ private Environment env;
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(dataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+
+ hibernateProperties.setProperty("hibernate.show_sql", "false");
+
+ // Envers properties
+ hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
+
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql b/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
new file mode 100644
index 0000000000..ae008f29bc
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
@@ -0,0 +1,31 @@
+insert into item (item_id, item_name, item_desc, item_price)
+values(1,'item One', 'test 1', 35.12);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(2,'Pogo stick', 'Pogo stick', 466.12);
+insert into item (item_id, item_name, item_desc, item_price)
+values(3,'Raft', 'Raft', 345.12);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(4,'Skate Board', 'Skating', 135.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(5,'Umbrella', 'Umbrella for Rain', 619.25);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(6,'Glue', 'Glue for home', 432.73);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(7,'Paint', 'Paint for Room', 1311.40);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(8,'Red paint', 'Red paint for room', 1135.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(9,'Household Chairs', 'Chairs for house', 25.71);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(10,'Office Chairs', 'Chairs for office', 395.98);
+
+insert into item (item_id, item_name, item_desc, item_price)
+values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml b/persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml
new file mode 100644
index 0000000000..ec0dc2469a
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml b/persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
similarity index 98%
rename from persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml
rename to persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
index 315e2e3118..d7c8f24fb0 100644
--- a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml
+++ b/persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
@@ -1,15 +1,15 @@
-
-
-
-
- com.mysql.jdbc.Driver
- tutorialmy5ql
- jdbc:mysql://localhost:3306/spring_hibernate_many_to_many
- tutorialuser
- org.hibernate.dialect.MySQLDialect
- thread
- false
-
-
+
+
+
+
+ com.mysql.jdbc.Driver
+ tutorialmy5ql
+ jdbc:mysql://localhost:3306/spring_hibernate_many_to_many
+ tutorialuser
+ org.hibernate.dialect.MySQLDialect
+ thread
+ false
+
+
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties b/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
new file mode 100644
index 0000000000..e3544d354a
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
@@ -0,0 +1,21 @@
+# jdbc.X
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+jdbc.eventGeneratedId=sa
+jdbc.user=sa
+jdbc.pass=
+
+# hibernate.X
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=false
+hibernate.hbm2ddl.auto=create-drop
+hibernate.cache.use_second_level_cache=true
+hibernate.cache.use_query_cache=true
+hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
+
+# hibernate.search.X
+hibernate.search.default.directory_provider = filesystem
+hibernate.search.default.indexBase = /data/index/default
+
+# envers.X
+envers.audit_table_suffix=_audit_log
diff --git a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java
new file mode 100644
index 0000000000..24c038aeb6
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java
@@ -0,0 +1,19 @@
+package com.baeldung;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+
+import com.baeldung.spring.PersistenceConfig;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+public class SpringContextTest {
+
+ @Test
+ public void whenSpringContextIsBootstrapped_thenNoExceptions() {
+ }
+}
diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
similarity index 97%
rename from persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
rename to persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
index 614de6d3ad..797d3384a0 100644
--- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
+++ b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
@@ -1,49 +1,49 @@
-package com.baeldung.hibernate.manytomany;
-
-import java.util.HashSet;
-import java.util.Set;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.manytomany.spring.PersistenceConfig;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
-public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest {
-
- @Autowired
- private SessionFactory sessionFactory;
-
- private Session session;
-
- @Before
- public final void before() {
- session = sessionFactory.openSession();
- session.beginTransaction();
- }
-
- @After
- public final void after() {
- session.getTransaction().commit();
- session.close();
- }
-
- @Test
- public final void whenEntitiesAreCreated_thenNoExceptions() {
- Set projects = new HashSet();
- projects.add(new Project("IT Project"));
- projects.add(new Project("Networking Project"));
- session.persist(new Employee("Peter", "Oven", projects));
- session.persist(new Employee("Allan", "Norman", projects));
- }
-
-}
+package com.baeldung.hibernate.manytomany;
+
+import java.util.HashSet;
+import java.util.Set;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.manytomany.spring.PersistenceConfig;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
+public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ private Session session;
+
+ @Before
+ public final void before() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ }
+
+ @After
+ public final void after() {
+ session.getTransaction().commit();
+ session.close();
+ }
+
+ @Test
+ public final void whenEntitiesAreCreated_thenNoExceptions() {
+ Set projects = new HashSet();
+ projects.add(new Project("IT Project"));
+ projects.add(new Project("Networking Project"));
+ session.persist(new Employee("Peter", "Oven", projects));
+ session.persist(new Employee("Allan", "Norman", projects));
+ }
+
+}
diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
similarity index 96%
rename from persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
rename to persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
index 0073e181cc..d09b2888df 100644
--- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
+++ b/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
@@ -1,80 +1,80 @@
-package com.baeldung.hibernate.manytomany;
-
-import static org.junit.Assert.assertNotNull;
-import static junit.framework.TestCase.assertEquals;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import com.baeldung.hibernate.manytomany.util.HibernateUtil;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
-
-/**
- * Configured in: manytomany.cfg.xml
- */
-public class HibernateManyToManyAnnotationMainIntegrationTest {
- private static SessionFactory sessionFactory;
-
- private Session session;
-
- @BeforeClass
- public static void beforeTests() {
- sessionFactory = HibernateUtil.getSessionFactory();
- }
-
- @Before
- public void setUp() {
- session = sessionFactory.openSession();
- session.beginTransaction();
- }
-
- @Test
- public void givenData_whenInsert_thenCreatesMtoMrelationship() {
- String[] employeeData = { "Peter Oven", "Allan Norman" };
- String[] projectData = { "IT Project", "Networking Project" };
- Set projects = new HashSet();
-
- for (String proj : projectData) {
- projects.add(new Project(proj));
- }
-
- for (String emp : employeeData) {
- Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
- assertEquals(0, employee.getProjects().size());
- employee.setProjects(projects);
- session.persist(employee);
- assertNotNull(employee);
- }
- }
-
- @Test
- public void givenSession_whenRead_thenReturnsMtoMdata() {
- @SuppressWarnings("unchecked")
- List employeeList = session.createQuery("FROM Employee").list();
- assertNotNull(employeeList);
- for(Employee employee : employeeList) {
- assertNotNull(employee.getProjects());
- }
- }
-
- @After
- public void tearDown() {
- session.getTransaction()
- .commit();
- session.close();
- }
-
- @AfterClass
- public static void afterTests() {
- sessionFactory.close();
- }
-
-}
+package com.baeldung.hibernate.manytomany;
+
+import static org.junit.Assert.assertNotNull;
+import static junit.framework.TestCase.assertEquals;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.baeldung.hibernate.manytomany.util.HibernateUtil;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
+
+/**
+ * Configured in: manytomany.cfg.xml
+ */
+public class HibernateManyToManyAnnotationMainIntegrationTest {
+ private static SessionFactory sessionFactory;
+
+ private Session session;
+
+ @BeforeClass
+ public static void beforeTests() {
+ sessionFactory = HibernateUtil.getSessionFactory();
+ }
+
+ @Before
+ public void setUp() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ }
+
+ @Test
+ public void givenData_whenInsert_thenCreatesMtoMrelationship() {
+ String[] employeeData = { "Peter Oven", "Allan Norman" };
+ String[] projectData = { "IT Project", "Networking Project" };
+ Set projects = new HashSet();
+
+ for (String proj : projectData) {
+ projects.add(new Project(proj));
+ }
+
+ for (String emp : employeeData) {
+ Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
+ assertEquals(0, employee.getProjects().size());
+ employee.setProjects(projects);
+ session.persist(employee);
+ assertNotNull(employee);
+ }
+ }
+
+ @Test
+ public void givenSession_whenRead_thenReturnsMtoMdata() {
+ @SuppressWarnings("unchecked")
+ List employeeList = session.createQuery("FROM Employee").list();
+ assertNotNull(employeeList);
+ for(Employee employee : employeeList) {
+ assertNotNull(employee.getProjects());
+ }
+ }
+
+ @After
+ public void tearDown() {
+ session.getTransaction()
+ .commit();
+ session.close();
+ }
+
+ @AfterClass
+ public static void afterTests() {
+ sessionFactory.close();
+ }
+
+}
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore b/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
new file mode 100644
index 0000000000..9e0109aae2
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql b/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
new file mode 100644
index 0000000000..087d62d331
--- /dev/null
+++ b/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
@@ -0,0 +1,21 @@
+insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(3,'Raft', 'Raft', 345.12);
+
+insert into item (item_id, item_name, item_desc, item_price) values(4,'Skate Board', 'Skating', 135.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(5,'Umbrella', 'Umbrella for Rain', 619.25);
+
+insert into item (item_id, item_name, item_desc, item_price) values(6,'Glue', 'Glue for home', 432.73);
+
+insert into item (item_id, item_name, item_desc, item_price) values(7,'Paint', 'Paint for Room', 1311.40);
+
+insert into item (item_id, item_name, item_desc, item_price) values(8,'Red paint', 'Red paint for room', 1135.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(9,'Household Chairs', 'Chairs for house', 25.71);
+
+insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98);
+
+insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/hibernate-many-to-many/src/test/resources/manytomany.cfg.xml
similarity index 100%
rename from persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml
rename to persistence-modules/hibernate-many-to-many/src/test/resources/manytomany.cfg.xml
diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md
index eff59a0362..9770fe95af 100644
--- a/persistence-modules/spring-hibernate-5/README.md
+++ b/persistence-modules/spring-hibernate-5/README.md
@@ -4,7 +4,6 @@ This module contains articles about Hibernate 5 with Spring.
### Relevant articles
-- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries)
- [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search)
diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml
index d0fa23504c..bb8c4e8228 100644
--- a/persistence-modules/spring-hibernate-5/pom.xml
+++ b/persistence-modules/spring-hibernate-5/pom.xml
@@ -108,6 +108,26 @@
h2
${h2.version}
+
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 2.3.2
+
+
+ com.sun.xml.bind
+ jaxb-core
+ 2.3.0.1
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.1
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ 2.3.1
+
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql
index 087d62d331..52c800f6b4 100644
--- a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql
+++ b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql
@@ -1,3 +1,4 @@
+
insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12);
insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);
From c8231b7c60ee610934afd4f91dcf5d5c17c6f5ee Mon Sep 17 00:00:00 2001
From: Swapan Pramanick
Date: Tue, 22 Feb 2022 10:19:48 +0100
Subject: [PATCH 143/235] BAEL-4316 Sample apps to showcase how to add files
from outside docker context (#11606)
* BAEL-4316 Sample apps to showcase how to add files from outside docker context
* BAEL-4316 update README content
* BAEL-4316 change example
* BAEL-4316 update docker file
* BAEL-4316 revert the README changes
* BAEL-4316 change directory structure
* BAEL-4316 deleted old files
Co-authored-by: Swapan Pramanick
---
.../projects/config/Dockerfile | 2 ++
.../projects/config/nginx.conf | 8 ++++++++
.../projects/sample-site/docker/Dockerfile | 3 +++
.../projects/sample-site/docker/Dockerfile-from-base | 2 ++
.../projects/sample-site/docker/Dockerfile-script | 3 +++
.../projects/sample-site/docker/build-docker.sh | 6 ++++++
.../projects/sample-site/html/index.html | 10 ++++++++++
7 files changed, 34 insertions(+)
create mode 100644 docker/docker-include-outside-build-context/projects/config/Dockerfile
create mode 100644 docker/docker-include-outside-build-context/projects/config/nginx.conf
create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile
create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base
create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script
create mode 100755 docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh
create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/html/index.html
diff --git a/docker/docker-include-outside-build-context/projects/config/Dockerfile b/docker/docker-include-outside-build-context/projects/config/Dockerfile
new file mode 100644
index 0000000000..754f9f9be3
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/config/Dockerfile
@@ -0,0 +1,2 @@
+FROM nginx:latest
+COPY nginx.conf /etc/nginx/nginx.conf
diff --git a/docker/docker-include-outside-build-context/projects/config/nginx.conf b/docker/docker-include-outside-build-context/projects/config/nginx.conf
new file mode 100644
index 0000000000..944da2f112
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/config/nginx.conf
@@ -0,0 +1,8 @@
+events {}
+
+http {
+ server {
+ listen 80;
+ index index.html;
+ }
+}
diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile
new file mode 100644
index 0000000000..bda0bbe257
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile
@@ -0,0 +1,3 @@
+FROM nginx:latest
+COPY sample-site/html/* /etc/nginx/html/
+COPY config/nginx.conf /etc/nginx/nginx.conf
diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base
new file mode 100644
index 0000000000..1b72414bc0
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base
@@ -0,0 +1,2 @@
+FROM sample-site-base:latest
+COPY html/* /etc/nginx/html/
diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script
new file mode 100644
index 0000000000..572028f19f
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script
@@ -0,0 +1,3 @@
+FROM nginx:latest
+COPY html/* /etc/nginx/html/
+COPY config/nginx.conf /etc/nginx/nginx.conf
diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh b/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh
new file mode 100755
index 0000000000..e84687b7b7
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh
@@ -0,0 +1,6 @@
+mkdir tmp-context
+cp -R ../html tmp-context/
+cp -R ../../config tmp-context/
+cp Dockerfile-script tmp-context/Dockerfile
+docker build -t sample-site:latest tmp-context
+rm -rf tmp-context
diff --git a/docker/docker-include-outside-build-context/projects/sample-site/html/index.html b/docker/docker-include-outside-build-context/projects/sample-site/html/index.html
new file mode 100644
index 0000000000..85f287fad7
--- /dev/null
+++ b/docker/docker-include-outside-build-context/projects/sample-site/html/index.html
@@ -0,0 +1,10 @@
+
+
+
+
+ Sample Site
+
+
+ Welcome to the first page of the site
+
+
From 74b2b2e910eaf521494d377dd55f3b3699ffc76c Mon Sep 17 00:00:00 2001
From: Muhammad Abdullah Azam Khan
Date: Tue, 22 Feb 2022 13:28:27 +0400
Subject: [PATCH 144/235] Bael 5303 graphqlvs rest (#11715)
* GraphQL and REST Comparison
* Updating README
* Reformatting code
---
spring-boot-modules/pom.xml | 1 +
.../README.md | 7 ++
.../spring-boot-libraries-comparison/pom.xml | 46 +++++++
.../GraphqlVsRestApplication.java | 19 +++
.../configuration/GraphqlConfiguration.java | 35 ++++++
.../controller/OrderController.java | 25 ++++
.../controller/ProductController.java | 38 ++++++
.../baeldung/graphqlvsrest/entity/Order.java | 58 +++++++++
.../graphqlvsrest/entity/Product.java | 115 ++++++++++++++++++
.../graphqlvsrest/model/ProductModel.java | 92 ++++++++++++++
.../repository/OrderRepository.java | 11 ++
.../repository/ProductRepository.java | 14 +++
.../repository/impl/OrderRepositoryImpl.java | 36 ++++++
.../impl/ProductRepositoryImpl.java | 74 +++++++++++
.../graphqlvsrest/resolver/Mutation.java | 22 ++++
.../resolver/ProductResolver.java | 18 +++
.../graphqlvsrest/resolver/Query.java | 27 ++++
.../src/main/resources/application.properties | 0
.../main/resources/graphql/schema.graphqls | 57 +++++++++
19 files changed, 695 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/README.md
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/pom.xml
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties
create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index 4925530a35..c1a96a0604 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -51,6 +51,7 @@
spring-boot-libraries
spring-boot-libraries-2
+ spring-boot-libraries-comparison
spring-boot-logging-log4j2
spring-boot-multiple-datasources
spring-boot-mvc
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/README.md b/spring-boot-modules/spring-boot-libraries-comparison/README.md
new file mode 100644
index 0000000000..3efdac2a4c
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/README.md
@@ -0,0 +1,7 @@
+## Spring Boot Libraries
+
+This module contains articles about various Spring Boot libraries Comparison
+
+### Relevant Articles:
+
+- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest/)
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/pom.xml b/spring-boot-modules/spring-boot-libraries-comparison/pom.xml
new file mode 100644
index 0000000000..59d0e75be3
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/pom.xml
@@ -0,0 +1,46 @@
+
+
+ 4.0.0
+ spring-boot-libraries-comparison
+
+
+ com.baeldung.spring-boot-modules
+ spring-boot-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.data
+ spring-data-jpa
+
+
+ com.graphql-java
+ graphql-spring-boot-starter
+ ${graphql-spring-boot-starter.version}
+
+
+ com.graphql-java
+ graphql-java-tools
+ ${graphql-java-tools.version}
+
+
+ com.graphql-java
+ graphiql-spring-boot-starter
+ ${graphql-spring-boot-starter.version}
+
+
+
+
+
+ 5.0.2
+ 5.2.4
+
+
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java
new file mode 100644
index 0000000000..29a3ef1e0f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java
@@ -0,0 +1,19 @@
+package com.baeldung.graphqlvsrest;
+
+import com.baeldung.graphqlvsrest.configuration.GraphqlConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
+import org.springframework.context.annotation.Import;
+
+@SpringBootApplication
+@Import(GraphqlConfiguration.class)
+@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
+public class GraphqlVsRestApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(GraphqlVsRestApplication.class, args);
+ }
+
+}
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java
new file mode 100644
index 0000000000..c100a03143
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java
@@ -0,0 +1,35 @@
+package com.baeldung.graphqlvsrest.configuration;
+
+import com.baeldung.graphqlvsrest.repository.OrderRepository;
+import com.baeldung.graphqlvsrest.resolver.Mutation;
+import com.baeldung.graphqlvsrest.resolver.ProductResolver;
+import com.baeldung.graphqlvsrest.resolver.Query;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class GraphqlConfiguration {
+
+ @Autowired
+ ProductRepository productRepository;
+
+ @Autowired
+ OrderRepository orderRepository;
+
+ @Bean
+ public Query query() {
+ return new Query(productRepository);
+ }
+
+ @Bean
+ public ProductResolver productResolver(){
+ return new ProductResolver(orderRepository);
+ }
+
+ @Bean
+ public Mutation mutation() {
+ return new Mutation(productRepository);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java
new file mode 100644
index 0000000000..14f0468bbd
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java
@@ -0,0 +1,25 @@
+package com.baeldung.graphqlvsrest.controller;
+
+import com.baeldung.graphqlvsrest.entity.Order;
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+import com.baeldung.graphqlvsrest.repository.OrderRepository;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Pageable;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("order")
+public class OrderController {
+
+ @Autowired
+ OrderRepository orderRepository;
+
+ @GetMapping()
+ public List getOrders(@RequestParam("product-id") Integer productId){
+ return orderRepository.getOrdersByProduct(productId);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java
new file mode 100644
index 0000000000..2fdee8765a
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java
@@ -0,0 +1,38 @@
+package com.baeldung.graphqlvsrest.controller;
+
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Pageable;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("product")
+public class ProductController {
+
+ @Autowired
+ ProductRepository productRepository;
+
+ @GetMapping
+ public List getProducts(Pageable pageable){
+ return productRepository.getProducts(pageable.getPageSize(), pageable.getPageNumber());
+ }
+
+ @GetMapping("/{product-id}")
+ public Product getProducts(@PathVariable("product-id") Integer productId){
+ return productRepository.getProduct(productId);
+ }
+
+ @PostMapping
+ public Product save(@RequestBody ProductModel productModel){
+ return productRepository.save(productModel);
+ }
+
+ @PutMapping("/{product-id}")
+ public Product update(@PathVariable("product-id") Integer productId, @RequestBody ProductModel productModel){
+ return productRepository.update(productId, productModel);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java
new file mode 100644
index 0000000000..89606e9897
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java
@@ -0,0 +1,58 @@
+package com.baeldung.graphqlvsrest.entity;
+
+public class Order {
+ private Integer id;
+ private Integer product_id;
+ private String customer_uuid;
+ private String status;
+ private String address;
+ private String creation_date;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Integer getProduct_id() {
+ return product_id;
+ }
+
+ public void setProduct_id(Integer product_id) {
+ this.product_id = product_id;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getCustomer_uuid() {
+ return customer_uuid;
+ }
+
+ public void setCustomer_uuid(String customer_uuid) {
+ this.customer_uuid = customer_uuid;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public String getCreation_date() {
+ return creation_date;
+ }
+
+ public void setCreation_date(String creation_date) {
+ this.creation_date = creation_date;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java
new file mode 100644
index 0000000000..2da9244c92
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java
@@ -0,0 +1,115 @@
+package com.baeldung.graphqlvsrest.entity;
+
+import com.baeldung.graphqlvsrest.model.ProductModel;
+
+import java.util.List;
+
+public class Product {
+ private Integer id;
+ private String name;
+ private String description;
+ private String status;
+ private String currency;
+ private Double price;
+ private List image_url;
+ private List video_url;
+ private Integer stock;
+ private Float average_rating;
+
+ public Product(Integer id, ProductModel productModel) {
+ this.id = id;
+ this.name = productModel.getName();
+ this.description = productModel.getDescription();
+ this.currency = productModel.getCurrency();
+ this.price = productModel.getPrice();
+ this.stock = productModel.getStock();
+ this.image_url = productModel.getImage_url();
+ this.video_url = productModel.getVideo_url();
+ this.average_rating = 0F;
+ this.status = productModel.getStatus();
+ }
+
+ public Product(){
+
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(String currency) {
+ this.currency = currency;
+ }
+
+ public Double getPrice() {
+ return price;
+ }
+
+ public void setPrice(Double price) {
+ this.price = price;
+ }
+
+ public List getImage_url() {
+ return image_url;
+ }
+
+ public void setImage_url(List image_url) {
+ this.image_url = image_url;
+ }
+
+ public List getVideo_url() {
+ return video_url;
+ }
+
+ public void setVideo_url(List video_url) {
+ this.video_url = video_url;
+ }
+
+ public Integer getStock() {
+ return stock;
+ }
+
+ public void setStock(Integer stock) {
+ this.stock = stock;
+ }
+
+ public Float getAverage_rating() {
+ return average_rating;
+ }
+
+ public void setAverage_rating(Float average_rating) {
+ this.average_rating = average_rating;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java
new file mode 100644
index 0000000000..db7a3ba54e
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java
@@ -0,0 +1,92 @@
+package com.baeldung.graphqlvsrest.model;
+
+import java.util.List;
+
+public class ProductModel {
+ private String name;
+ private String description;
+ private String status;
+ private String currency;
+ private Double price;
+ private List image_url;
+ private List video_url;
+ private Integer stock;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(String currency) {
+ this.currency = currency;
+ }
+
+ public Double getPrice() {
+ return price;
+ }
+
+ public void setPrice(Double price) {
+ this.price = price;
+ }
+
+ public List getImage_url() {
+ return image_url;
+ }
+
+ public void setImage_url(List image_url) {
+ this.image_url = image_url;
+ }
+
+ public List getVideo_url() {
+ return video_url;
+ }
+
+ public void setVideo_url(List video_url) {
+ this.video_url = video_url;
+ }
+
+ public Integer getStock() {
+ return stock;
+ }
+
+ public void setStock(Integer stock) {
+ this.stock = stock;
+ }
+
+ @Override
+ public String toString() {
+ return "ProductModel{" +
+ "name='" + name + '\'' +
+ ", description='" + description + '\'' +
+ ", status='" + status + '\'' +
+ ", currency='" + currency + '\'' +
+ ", price=" + price +
+ ", image_url=" + image_url +
+ ", video_url=" + video_url +
+ ", stock=" + stock +
+ '}';
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java
new file mode 100644
index 0000000000..92cc288426
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java
@@ -0,0 +1,11 @@
+package com.baeldung.graphqlvsrest.repository;
+
+import com.baeldung.graphqlvsrest.entity.Order;
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+
+import java.util.List;
+
+public interface OrderRepository {
+ List getOrdersByProduct(Integer productId);
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java
new file mode 100644
index 0000000000..c0fb12327f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java
@@ -0,0 +1,14 @@
+package com.baeldung.graphqlvsrest.repository;
+
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+
+import java.util.List;
+
+public interface ProductRepository {
+ List getProducts(Integer pageSize, Integer pageNumber);
+ Product getProduct(Integer id);
+ Product save(ProductModel productModel);
+ Product update(Integer productId, ProductModel productModel);
+
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java
new file mode 100644
index 0000000000..e4f316c865
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java
@@ -0,0 +1,36 @@
+package com.baeldung.graphqlvsrest.repository.impl;
+
+import com.baeldung.graphqlvsrest.entity.Order;
+import com.baeldung.graphqlvsrest.repository.OrderRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+@Repository
+public class OrderRepositoryImpl implements OrderRepository {
+
+ private static List orderList = new ArrayList<>();
+
+ public OrderRepositoryImpl() {
+ for (int i = 1; i <= 100; i++){
+ Order order = new Order();
+ order.setId(i);
+ order.setProduct_id(i%10);
+ order.setAddress(UUID.randomUUID().toString());
+ order.setCustomer_uuid(UUID.randomUUID().toString());
+ order.setCreation_date(new Date(System.currentTimeMillis()).toString());
+ order.setStatus("Delivered");
+ orderList.add(order);
+ }
+ }
+
+
+ @Override
+ public List getOrdersByProduct(Integer productId) {
+ return orderList.stream().filter(order -> order.getProduct_id().equals(productId)).collect(Collectors.toList());
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java
new file mode 100644
index 0000000000..845472faea
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java
@@ -0,0 +1,74 @@
+package com.baeldung.graphqlvsrest.repository.impl;
+
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+@Repository
+public class ProductRepositoryImpl implements ProductRepository {
+
+ private static List productList = new ArrayList<>();
+
+ public ProductRepositoryImpl() {
+ for (int i = 1; i <= 10; i++){
+ Product product = new Product();
+ product.setId(i);
+ product.setName(String.format("Product %d", i));
+ product.setDescription(String.format("Product %d description", i));
+ product.setCurrency(String.format("Product %d currency", i));
+ product.setPrice(Double.valueOf(i^2));
+ product.setStock(10);
+ product.setAverage_rating(0F);
+ product.setImage_url(Arrays.asList(String.format("www.baeldung.com/imageurl/%d", i)));
+ product.setVideo_url(Arrays.asList(String.format("www.baeldung.com/videourl/%d", i)));
+ productList.add(product);
+ }
+ }
+
+ @Override
+ public List getProducts(Integer pageSize, Integer pageNumber) {
+ return productList.stream().skip(pageSize*pageNumber).limit(pageSize).collect(Collectors.toList());
+ }
+
+ @Override
+ public Product getProduct(Integer id) {
+ return productList.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null);
+ }
+
+ @Override
+ public Product save(ProductModel productModel) {
+ Product product = new Product(productList.size()+1, productModel);
+ productList.add(product);
+ return product;
+ }
+
+ @Override
+ public Product update(Integer productId, ProductModel productModel) {
+ Product product = getProduct(productId);
+ if (product != null){
+ update(product, productModel);
+ }
+ return product;
+ }
+
+ private void update(Product product, ProductModel productModel){
+ if (productModel != null) {
+ System.out.println(productModel.toString());
+ Optional.ofNullable(productModel.getName()).ifPresent(product::setName);
+ Optional.ofNullable(productModel.getDescription()).ifPresent(product::setDescription);
+ Optional.ofNullable(productModel.getCurrency()).ifPresent(product::setCurrency);
+ Optional.ofNullable(productModel.getImage_url()).ifPresent(product::setImage_url);
+ Optional.ofNullable(productModel.getStock()).ifPresent(product::setStock);
+ Optional.ofNullable(productModel.getStatus()).ifPresent(product::setStatus);
+ Optional.ofNullable(productModel.getVideo_url()).ifPresent(product::setVideo_url);
+ Optional.ofNullable(productModel.getPrice()).ifPresent(product::setPrice);
+ }
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java
new file mode 100644
index 0000000000..3d643f97e6
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java
@@ -0,0 +1,22 @@
+package com.baeldung.graphqlvsrest.resolver;
+
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.model.ProductModel;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import com.coxautodev.graphql.tools.GraphQLMutationResolver;
+
+public class Mutation implements GraphQLMutationResolver {
+
+ private ProductRepository productRepository;
+ public Mutation(ProductRepository productRepository){
+ this.productRepository = productRepository;
+ }
+
+ public Product saveProduct(ProductModel productModel) {
+ return productRepository.save(productModel);
+ }
+
+ public Product updateProduct(Integer productId, ProductModel productModel) {
+ return productRepository.update(productId, productModel);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java
new file mode 100644
index 0000000000..f20b8d5920
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java
@@ -0,0 +1,18 @@
+package com.baeldung.graphqlvsrest.resolver;
+
+import com.baeldung.graphqlvsrest.entity.Order;
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.repository.OrderRepository;
+import com.coxautodev.graphql.tools.GraphQLResolver;
+
+import java.util.List;
+
+public class ProductResolver implements GraphQLResolver {
+ private OrderRepository orderRepository;
+ public ProductResolver(OrderRepository orderRepository){
+ this.orderRepository = orderRepository;
+ }
+ public List getOrders(Product product){
+ return orderRepository.getOrdersByProduct(product.getId());
+ }
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java
new file mode 100644
index 0000000000..0d218261b2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java
@@ -0,0 +1,27 @@
+package com.baeldung.graphqlvsrest.resolver;
+
+import com.baeldung.graphqlvsrest.entity.Order;
+import com.baeldung.graphqlvsrest.entity.Product;
+import com.baeldung.graphqlvsrest.repository.OrderRepository;
+import com.baeldung.graphqlvsrest.repository.ProductRepository;
+import com.coxautodev.graphql.tools.GraphQLQueryResolver;
+
+import java.util.List;
+
+public class Query implements GraphQLQueryResolver {
+
+ private ProductRepository productRepository;
+ public Query(ProductRepository productRepository){
+ this.productRepository = productRepository;
+ }
+
+ public List getProducts(int pageSize, int pageNumber) {
+ return productRepository.getProducts(pageSize, pageNumber);
+ }
+
+ public Product getProduct(int id) {
+ return productRepository.getProduct(id);
+ }
+
+
+}
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls
new file mode 100644
index 0000000000..2709510d72
--- /dev/null
+++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls
@@ -0,0 +1,57 @@
+type Product {
+ id: ID
+ name: String!
+ description: String
+ status: String
+ currency: String!
+ price: Float
+ image_url: [String]
+ video_url: [String]
+ stock: Int
+ average_rating: Float
+ orders:[Order]
+}
+
+type Order{
+ id:ID
+ product_id:Int
+ customer_uuid:String
+ address:String
+ status:String
+ creation_date:String
+}
+
+input ProductModel {
+ name: String!
+ description: String
+ status: String
+ currency: String!
+ price: Float
+ image_url: [String]
+ video_url: [String]
+ stock: Int
+}
+
+input ProductUpdateModel {
+ name: String
+ description: String
+ status: String
+ currency: String
+ price: Float
+ image_url: [String]
+ video_url: [String]
+ stock: Int
+}
+
+
+# The Root Query for the application
+type Query {
+ products(size: Int, page: Int): [Product]!
+ product(id: Int): Product!
+}
+
+# The Root Mutation for the application
+type Mutation {
+ saveProduct(product: ProductModel) : Product!
+ updateProduct(id: Int, product: ProductUpdateModel) : Product!
+}
From 920d09bcea946477049a5592cd24f0423835d56d Mon Sep 17 00:00:00 2001
From: kwoyke
Date: Tue, 22 Feb 2022 14:27:58 +0100
Subject: [PATCH 145/235] JAVA-9960: Upgrade parent-spring-5 to 5.3.16 (#11848)
---
parent-spring-5/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml
index 175e8d58f9..b2d581c9c1 100644
--- a/parent-spring-5/pom.xml
+++ b/parent-spring-5/pom.xml
@@ -24,7 +24,7 @@
- 5.3.13
+ 5.3.16
5.6.0
1.5.10.RELEASE
From 9d191600435a8812a8ed50bcbe1cfb595dd0f148 Mon Sep 17 00:00:00 2001
From: sampadawagde
Date: Tue, 22 Feb 2022 21:53:39 +0530
Subject: [PATCH 146/235] JAVA-9824: Identify boot modules not using
parent-boot-2 as parent and upgrade log4j for them
---
jta/pom.xml | 13 +++++++++++++
maven-modules/maven-generate-war/pom.xml | 1 +
patterns/enterprise-patterns/pom.xml | 8 ++++++++
persistence-modules/spring-data-dynamodb/pom.xml | 8 ++++++++
quarkus-vs-springboot/spring-project/pom.xml | 1 +
spring-5-data-reactive/pom.xml | 13 +++++++++++++
spring-activiti/pom.xml | 13 +++++++++++++
spring-boot-modules/spring-boot-2/pom.xml | 2 +-
.../spring-boot-logging-log4j2/pom.xml | 1 +
spring-boot-modules/spring-boot-mvc-birt/pom.xml | 1 +
spring-boot-modules/spring-boot-react/pom.xml | 13 +++++++++++++
.../spring-boot-swagger-keycloak/pom.xml | 8 ++++++++
spring-boot-modules/spring-boot-testing/pom.xml | 13 +++++++++++++
spring-cloud/spring-cloud-contract/pom.xml | 8 ++++++++
.../spring-cloud-eureka-self-preservation/pom.xml | 13 +++++++++++++
spring-cloud/spring-cloud-eureka/pom.xml | 13 +++++++++++++
spring-cloud/spring-cloud-load-balancer/pom.xml | 13 +++++++++++++
.../twitterhdfs/pom.xml | 1 +
.../eureka-client/pom.xml | 11 +++++++++++
.../eureka-server/pom.xml | 11 +++++++++++
.../zuul-server/pom.xml | 11 +++++++++++
.../spring-zuul-rate-limiting/pom.xml | 13 +++++++++++++
spring-di-2/pom.xml | 8 ++++++++
spring-di-3/pom.xml | 8 ++++++++
spring-native/pom.xml | 1 +
spring-roo/pom.xml | 1 +
.../spring-5-security-oauth/pom.xml | 14 ++++++++++++++
.../spring-security-legacy-oidc/pom.xml | 13 +++++++++++++
.../custom-validations-opeanpi-codegen/pom.xml | 1 +
spring-web-modules/spring-boot-jsp/pom.xml | 8 ++++++++
30 files changed, 242 insertions(+), 1 deletion(-)
diff --git a/jta/pom.xml b/jta/pom.xml
index e9f9364646..e62c480c81 100644
--- a/jta/pom.xml
+++ b/jta/pom.xml
@@ -15,6 +15,18 @@
0.0.1-SNAPSHOT
../parent-boot-2
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -37,6 +49,7 @@
2.4.7
+ 2.17.1
\ No newline at end of file
diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml
index 56256f58ea..b388cfdadd 100644
--- a/maven-modules/maven-generate-war/pom.xml
+++ b/maven-modules/maven-generate-war/pom.xml
@@ -63,6 +63,7 @@
11
+ 2.17.1
\ No newline at end of file
diff --git a/patterns/enterprise-patterns/pom.xml b/patterns/enterprise-patterns/pom.xml
index 10c07d6d05..999b359170 100644
--- a/patterns/enterprise-patterns/pom.xml
+++ b/patterns/enterprise-patterns/pom.xml
@@ -48,6 +48,13 @@
pom
import
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
@@ -63,6 +70,7 @@
3.7.4
2.2.2.RELEASE
+ 2.17.1
\ No newline at end of file
diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml
index 148215b68a..0e990c69f3 100644
--- a/persistence-modules/spring-data-dynamodb/pom.xml
+++ b/persistence-modules/spring-data-dynamodb/pom.xml
@@ -24,6 +24,13 @@
pom
import
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
@@ -184,6 +191,7 @@
https://s3-us-west-2.amazonaws.com/dynamodb-local/release
3.1.1
2.4.7
+ 2.17.1
\ No newline at end of file
diff --git a/quarkus-vs-springboot/spring-project/pom.xml b/quarkus-vs-springboot/spring-project/pom.xml
index bf524cd550..7f0fa4c8c6 100644
--- a/quarkus-vs-springboot/spring-project/pom.xml
+++ b/quarkus-vs-springboot/spring-project/pom.xml
@@ -187,6 +187,7 @@
11
0.11.0-RC1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml
index c145992737..023eda856b 100644
--- a/spring-5-data-reactive/pom.xml
+++ b/spring-5-data-reactive/pom.xml
@@ -13,6 +13,18 @@
0.0.1-SNAPSHOT
../parent-boot-2
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -138,6 +150,7 @@
3.3.1.RELEASE
2.2.6.RELEASE
+ 2.17.1
\ No newline at end of file
diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml
index c685207cc4..2ede13a152 100644
--- a/spring-activiti/pom.xml
+++ b/spring-activiti/pom.xml
@@ -16,6 +16,18 @@
0.0.1-SNAPSHOT
../parent-boot-1
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -59,6 +71,7 @@
6.0.0
+ 2.17.1
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-2/pom.xml b/spring-boot-modules/spring-boot-2/pom.xml
index 08dc517fa0..0da07eaf00 100644
--- a/spring-boot-modules/spring-boot-2/pom.xml
+++ b/spring-boot-modules/spring-boot-2/pom.xml
@@ -62,7 +62,7 @@
- 2.14.1
+ 2.17.1
5.3.15
11
11
diff --git a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml
index 8cf052deb3..036df19887 100644
--- a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml
+++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml
@@ -102,6 +102,7 @@
4.13.2
5.8.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-mvc-birt/pom.xml b/spring-boot-modules/spring-boot-mvc-birt/pom.xml
index 16b07000f8..8f1c770bbe 100644
--- a/spring-boot-modules/spring-boot-mvc-birt/pom.xml
+++ b/spring-boot-modules/spring-boot-mvc-birt/pom.xml
@@ -70,6 +70,7 @@
1.8
4.8.0
1.2.17
+ 2.17.1
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-react/pom.xml b/spring-boot-modules/spring-boot-react/pom.xml
index d515aed6ce..dc0c6914c9 100644
--- a/spring-boot-modules/spring-boot-react/pom.xml
+++ b/spring-boot-modules/spring-boot-react/pom.xml
@@ -11,6 +11,18 @@
1.0.0-SNAPSHOT
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
+
org.springframework.boot
@@ -128,6 +140,7 @@
v1.12.1
2.4.4
1.0.2
+ 2.17.1
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
index 82e1951b8e..a7f3e01014 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
@@ -24,6 +24,13 @@
pom
import
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
@@ -62,6 +69,7 @@
2.4.5
3.0.0
15.0.2
+ 2.17.1
diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml
index 658eb7728e..fcfc2364ba 100644
--- a/spring-boot-modules/spring-boot-testing/pom.xml
+++ b/spring-boot-modules/spring-boot-testing/pom.xml
@@ -14,6 +14,18 @@
1.0.0-SNAPSHOT
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
+
org.springframework.boot
@@ -131,6 +143,7 @@
1.6
0.7.2
2.5.0
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml
index 8546e76586..6e8b130ed1 100644
--- a/spring-cloud/spring-cloud-contract/pom.xml
+++ b/spring-cloud/spring-cloud-contract/pom.xml
@@ -21,6 +21,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.boot
spring-boot-starter-web
@@ -55,6 +62,7 @@
2.1.1.RELEASE
2.1.4.RELEASE
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml b/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
index 0b7da2ce4a..e22ad6b7c9 100644
--- a/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
+++ b/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
@@ -14,6 +14,18 @@
spring-cloud
1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
spring-cloud-eureka-server
@@ -32,6 +44,7 @@
2.1.3.RELEASE
Greenwich.SR3
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml
index e5327d4530..795eab7d6e 100644
--- a/spring-cloud/spring-cloud-eureka/pom.xml
+++ b/spring-cloud/spring-cloud-eureka/pom.xml
@@ -14,6 +14,18 @@
spring-cloud
1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
spring-cloud-eureka-server
@@ -34,6 +46,7 @@
2.1.2.RELEASE
Greenwich.RELEASE
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-load-balancer/pom.xml b/spring-cloud/spring-cloud-load-balancer/pom.xml
index 9c650565ed..65cf83de09 100644
--- a/spring-cloud/spring-cloud-load-balancer/pom.xml
+++ b/spring-cloud/spring-cloud-load-balancer/pom.xml
@@ -19,6 +19,18 @@
spring-cloud-loadbalancer-server
spring-cloud-loadbalancer-client
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -32,6 +44,7 @@
2.6.1
2021.0.0
+ 2.17.1
diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml
index 1c8fa4e694..73d6e62d37 100644
--- a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml
+++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml
@@ -78,6 +78,7 @@
4.13.2
5.8.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
index 3514924198..b2cb66744b 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
@@ -17,6 +17,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.cloud
spring-cloud-starter-parent
@@ -45,5 +52,9 @@
test
+
+
+ 2.17.1
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
index dcd912df07..466291650c 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
@@ -17,6 +17,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.cloud
spring-cloud-starter-parent
@@ -45,5 +52,9 @@
test
+
+
+ 2.17.1
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
index bb38ec1351..27afc3eb69 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
@@ -14,6 +14,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.cloud
spring-cloud-starter-parent
@@ -53,5 +60,9 @@
test
+
+
+ 2.17.1
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
index 2969b5eed9..4727859ea2 100644
--- a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
@@ -13,6 +13,18 @@
spring-cloud-zuul
0.0.1-SNAPSHOT
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -44,6 +56,7 @@
2.2.0.RELEASE
2.4.7
2020.0.4
+ 2.17.1
\ No newline at end of file
diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml
index d3be846424..1207506d17 100644
--- a/spring-di-2/pom.xml
+++ b/spring-di-2/pom.xml
@@ -16,6 +16,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.boot
spring-boot-dependencies
@@ -80,6 +87,7 @@
2.6.1
1.11
1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-di-3/pom.xml b/spring-di-3/pom.xml
index 0d4bbd01af..c6a2687606 100644
--- a/spring-di-3/pom.xml
+++ b/spring-di-3/pom.xml
@@ -16,6 +16,13 @@
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.boot
spring-boot-dependencies
@@ -40,6 +47,7 @@
2.6.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-native/pom.xml b/spring-native/pom.xml
index 4455e050f2..f54d7b5308 100644
--- a/spring-native/pom.xml
+++ b/spring-native/pom.xml
@@ -75,6 +75,7 @@
1.8
1.8
1.8
+ 2.17.1
\ No newline at end of file
diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml
index b55a334256..ea42095d92 100644
--- a/spring-roo/pom.xml
+++ b/spring-roo/pom.xml
@@ -625,6 +625,7 @@
1.0.3
2.0.0.RELEASE
1.2.0
+ 2.17.1
\ No newline at end of file
diff --git a/spring-security-modules/spring-5-security-oauth/pom.xml b/spring-security-modules/spring-5-security-oauth/pom.xml
index aa4958ae47..706cdb3082 100644
--- a/spring-security-modules/spring-5-security-oauth/pom.xml
+++ b/spring-security-modules/spring-5-security-oauth/pom.xml
@@ -15,6 +15,19 @@
0.0.1-SNAPSHOT
../../parent-boot-2
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
+
@@ -72,6 +85,7 @@
is available -->
2.5.2
com.baeldung.oauth2.SpringOAuthApplication
+ 2.17.1
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-legacy-oidc/pom.xml b/spring-security-modules/spring-security-legacy-oidc/pom.xml
index ca54a6765d..9dd898f9dd 100644
--- a/spring-security-modules/spring-security-legacy-oidc/pom.xml
+++ b/spring-security-modules/spring-security-legacy-oidc/pom.xml
@@ -14,6 +14,18 @@
0.0.1-SNAPSHOT
../../parent-boot-2
+
+
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
@@ -50,6 +62,7 @@
1.0.9.RELEASE
0.3.0
2.4.7
+ 2.17.1
\ No newline at end of file
diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml
index 336cb0da74..9add9ae494 100644
--- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml
+++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml
@@ -100,6 +100,7 @@
11
3.0.0
+ 2.17.1
\ No newline at end of file
diff --git a/spring-web-modules/spring-boot-jsp/pom.xml b/spring-web-modules/spring-boot-jsp/pom.xml
index b9b4a97e6b..d2a363bafa 100644
--- a/spring-web-modules/spring-boot-jsp/pom.xml
+++ b/spring-web-modules/spring-boot-jsp/pom.xml
@@ -23,6 +23,13 @@
pom
import
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
org.springframework.boot
spring-boot-dependencies
@@ -92,6 +99,7 @@
1.2
2.4.4
+ 2.17.1
\ No newline at end of file
From fe0f83b4a23fd8d6bd554ca9ead4de39043e0397 Mon Sep 17 00:00:00 2001
From: Jonathan Cook
Date: Tue, 22 Feb 2022 21:16:38 +0100
Subject: [PATCH 147/235] BAEL-5408 - Update Camel version in spring-boot-camel
module (#11851)
* BAEL-4706 - Spring Boot with Spring Batch
* BAEL-3948 - Fix test(s) in spring-batch which leaves repository.sqlite
changed
* BAEL-4736 - Convert JSONArray to List of Object using camel-jackson
* BAEL-4756 - Mockito MockSettings
* BAEL-4756 - Mockito MockSettings - fix spelling
* BAEL-2674 - Upgrade the Okhttp article
* BAEL-4204 - Adding Interceptors in OkHTTP
* BAEL-4836 - Mocking Static Methods with Mockito
* BAEL-4205 - A Guide to Events in OkHTTP
* BAEL-5408 - Update Camel version in spring-boot-camel module
Co-authored-by: Jonathan Cook
---
pom.xml | 6 ++++--
spring-boot-modules/pom.xml | 1 -
spring-boot-modules/spring-boot-camel/pom.xml | 11 ++++++-----
3 files changed, 10 insertions(+), 8 deletions(-)
diff --git a/pom.xml b/pom.xml
index f5378f9961..99217774e9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1343,7 +1343,8 @@
persistence-modules/spring-data-cassandra-2
quarkus-vs-springboot
quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
testing-modules/testing-assertions
@@ -1400,7 +1401,8 @@
persistence-modules/spring-data-cassandra-2
quarkus-vs-springboot
quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
testing-modules/testing-assertions
diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml
index c1a96a0604..fabd54aa92 100644
--- a/spring-boot-modules/pom.xml
+++ b/spring-boot-modules/pom.xml
@@ -36,7 +36,6 @@
spring-boot-deployment
spring-boot-di
spring-boot-disable-logging
- spring-boot-camel
spring-boot-ci-cd
spring-boot-custom-starter
diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml
index 5d5e2ce6bd..5bda1b2351 100644
--- a/spring-boot-modules/spring-boot-camel/pom.xml
+++ b/spring-boot-modules/spring-boot-camel/pom.xml
@@ -16,22 +16,22 @@
- org.apache.camel
+ org.apache.camel.springboot
camel-servlet-starter
${camel.version}
- org.apache.camel
+ org.apache.camel.springboot
camel-jackson-starter
${camel.version}
- org.apache.camel
+ org.apache.camel.springboot
camel-swagger-java-starter
${camel.version}
- org.apache.camel
+ org.apache.camel.springboot
camel-spring-boot-starter
${camel.version}
@@ -64,7 +64,8 @@
- 3.0.0-M4
+ 11
+ 3.15.0
\ No newline at end of file
From 23c72d2063f8f1495b3f9770fc4d5cdd20a25adc Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 04:19:38 +0800
Subject: [PATCH 148/235] Create README.md
---
spring-5-autowiring-beans/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 spring-5-autowiring-beans/README.md
diff --git a/spring-5-autowiring-beans/README.md b/spring-5-autowiring-beans/README.md
new file mode 100644
index 0000000000..dc8751325e
--- /dev/null
+++ b/spring-5-autowiring-beans/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Spring @Autowired Field Null – Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null)
From 32813cbc3e8d61a542e36d02168f0c182b534d87 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:01:47 +0800
Subject: [PATCH 149/235] Update README.md
---
core-java-modules/core-java-security-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-security-3/README.md b/core-java-modules/core-java-security-3/README.md
index 31969cd270..9d82e829e2 100644
--- a/core-java-modules/core-java-security-3/README.md
+++ b/core-java-modules/core-java-security-3/README.md
@@ -10,4 +10,5 @@ This module contains articles about core Java Security
- [HMAC in Java](https://www.baeldung.com/java-hmac)
- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
- [Computing an X509 Certificate’s Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
+- [Error: “trustAnchors parameter must be non-empty”](https://www.baeldung.com/java-trustanchors-parameter-must-be-non-empty)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
From 07cd27a9b29b2601383170a542089f16b5555737 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:03:19 +0800
Subject: [PATCH 150/235] Create README.md
---
gradle/gradle-source-vs-target-compatibility/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 gradle/gradle-source-vs-target-compatibility/README.md
diff --git a/gradle/gradle-source-vs-target-compatibility/README.md b/gradle/gradle-source-vs-target-compatibility/README.md
new file mode 100644
index 0000000000..cc3157fde3
--- /dev/null
+++ b/gradle/gradle-source-vs-target-compatibility/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Gradle: sourceCompatiblity vs targetCompatibility](https://www.baeldung.com/gradle-sourcecompatiblity-vs-targetcompatibility)
From 3b0151e731fd53fd26f80a6dbb68de7ba2142693 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:09:35 +0800
Subject: [PATCH 151/235] Update README.md
---
spring-cloud/spring-cloud-openfeign/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-cloud/spring-cloud-openfeign/README.md b/spring-cloud/spring-cloud-openfeign/README.md
index 5d3dc060c7..44f4d15b16 100644
--- a/spring-cloud/spring-cloud-openfeign/README.md
+++ b/spring-cloud/spring-cloud-openfeign/README.md
@@ -4,3 +4,4 @@
- [Differences Between Netflix Feign and OpenFeign](https://www.baeldung.com/netflix-feign-vs-openfeign)
- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload)
- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging)
+- [Provide an OAuth2 Token to a Feign Client](https://www.baeldung.com/spring-cloud-feign-oauth-token)
From 2ef9f3c02672464c8aa7e9126691da4f567dea6f Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:16:19 +0800
Subject: [PATCH 152/235] Update README.md
---
spring-di-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-di-3/README.md b/spring-di-3/README.md
index 9ab7789f37..4246069616 100644
--- a/spring-di-3/README.md
+++ b/spring-di-3/README.md
@@ -5,4 +5,5 @@ This module contains articles about dependency injection with Spring
### Relevant Articles
- [@Lookup Annotation in Spring](https://www.baeldung.com/spring-lookup)
+- [Spring @Autowired Field Null – Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null)
- More articles: [[<-- prev]](../spring-di-2)
From ca061932b3496b239fe19f7822da0162d7910c3c Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:18:05 +0800
Subject: [PATCH 153/235] Update README.md
---
spring-boot-modules/spring-boot-swagger/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-boot-modules/spring-boot-swagger/README.md b/spring-boot-modules/spring-boot-swagger/README.md
index 174bfe626d..a09df23a80 100644
--- a/spring-boot-modules/spring-boot-swagger/README.md
+++ b/spring-boot-modules/spring-boot-swagger/README.md
@@ -5,3 +5,4 @@
- [Generate PDF from Swagger API Documentation](https://www.baeldung.com/swagger-generate-pdf)
- [Remove Basic Error Controller In SpringFox Swagger-UI](https://www.baeldung.com/spring-swagger-remove-error-controller)
- [Setting Example and Description with Swagger](https://www.baeldung.com/swagger-set-example-description)
+- [Document Enum in Swagger](https://www.baeldung.com/swagger-enum)
From b113c42902efcca7f8a1bc748d97d830ee99858e Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:19:46 +0800
Subject: [PATCH 154/235] Update README.md
---
java-native/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/java-native/README.md b/java-native/README.md
index 4f85342a38..2aa02c03d5 100644
--- a/java-native/README.md
+++ b/java-native/README.md
@@ -7,3 +7,4 @@ This module contains articles about the Java Native Interface (JNI).
- [Guide to JNI (Java Native Interface)](https://www.baeldung.com/jni)
- [Using JNA to Access Native Dynamic Libraries](https://www.baeldung.com/java-jna-dynamic-libraries)
- [Check if a Java Program Is Running in 64-Bit or 32-Bit JVM](https://www.baeldung.com/java-detect-jvm-64-or-32-bit)
+- [How to use JNI’s RegisterNatives() method?](https://www.baeldung.com/jni-registernatives)
From 9fd7fb2c0f955d8f58e383931f071a2928eeb15d Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:45:17 +0800
Subject: [PATCH 155/235] Update README.md
---
persistence-modules/hibernate-queries/README.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md
index 61d94e32de..58ca74cd24 100644
--- a/persistence-modules/hibernate-queries/README.md
+++ b/persistence-modules/hibernate-queries/README.md
@@ -7,4 +7,5 @@ This module contains articles about use of Queries in Hibernate.
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
-- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
\ No newline at end of file
+- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
+- [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar)
From 5c33e8c30ca8afc72f004041d25d37227b52d5d7 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:46:49 +0800
Subject: [PATCH 156/235] Update README.md
---
spring-boot-modules/spring-boot-security/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-boot-modules/spring-boot-security/README.md b/spring-boot-modules/spring-boot-security/README.md
index b9966709cb..d848f798ba 100644
--- a/spring-boot-modules/spring-boot-security/README.md
+++ b/spring-boot-modules/spring-boot-security/README.md
@@ -10,6 +10,7 @@ This module contains articles about Spring Boot Security
- [Guide to @CurrentSecurityContext in Spring Security](https://www.baeldung.com/spring-currentsecuritycontext)
- [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile)
- [Spring @EnableWebSecurity vs. @EnableGlobalMethodSecurity](https://www.baeldung.com/spring-enablewebsecurity-vs-enableglobalmethodsecurity)
+- [Spring Security – Configuring Different URLs](https://www.baeldung.com/spring-security-configuring-urls)
### Spring Boot Security Auto-Configuration
From cf98dad5db819aee692d575a44eb95e1d70ad5b2 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:51:34 +0800
Subject: [PATCH 157/235] Update README.md
---
core-java-modules/core-java-collections-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-collections-4/README.md b/core-java-modules/core-java-collections-4/README.md
index 0e14f407c4..cbca44d372 100644
--- a/core-java-modules/core-java-collections-4/README.md
+++ b/core-java-modules/core-java-collections-4/README.md
@@ -7,3 +7,4 @@
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)
- [Collection.toArray(new T[0]) or .toArray(new T[size])](https://www.baeldung.com/java-collection-toarray-methods)
+- [Create an Empty Map in Java](https://www.baeldung.com/java-create-empty-map)
From 9011fdc4f5be943d447878765c7ff3e47e69e190 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:52:51 +0800
Subject: [PATCH 158/235] Update README.md
---
core-java-modules/core-java-8-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md
index 7f2245ccc0..12a060ccfe 100644
--- a/core-java-modules/core-java-8-2/README.md
+++ b/core-java-modules/core-java-8-2/README.md
@@ -8,4 +8,5 @@ This module contains articles about Java 8 core features
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
+- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [[<-- Prev]](/core-java-modules/core-java-8)
From 7e6df12a3fa70c15950163949cef1b019986d1c8 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:54:30 +0800
Subject: [PATCH 159/235] Update README.md
---
docker/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/docker/README.md b/docker/README.md
index 0de3694215..0adf1c9b51 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -6,3 +6,4 @@
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)
- [Dockerfile Strategies for Git](https://www.baeldung.com/ops/dockerfile-git-strategies)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
+- [How to Include Files Outside of Docker’s Build Context](https://www.baeldung.com/ops/docker-include-files-outside-build-context)
From 9c5f0cdaf0c875f455a3489fc868e9e111d49980 Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:56:08 +0800
Subject: [PATCH 160/235] Update README.md
---
spring-boot-modules/spring-boot-libraries-comparison/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/spring-boot-modules/spring-boot-libraries-comparison/README.md b/spring-boot-modules/spring-boot-libraries-comparison/README.md
index 3efdac2a4c..d373f91b3b 100644
--- a/spring-boot-modules/spring-boot-libraries-comparison/README.md
+++ b/spring-boot-modules/spring-boot-libraries-comparison/README.md
@@ -4,4 +4,4 @@ This module contains articles about various Spring Boot libraries Comparison
### Relevant Articles:
-- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest/)
\ No newline at end of file
+- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest)
From e2abcfc461dcf97e65b11fce40ba8c4dac2404ae Mon Sep 17 00:00:00 2001
From: johnA1331 <53036378+johnA1331@users.noreply.github.com>
Date: Wed, 23 Feb 2022 19:58:10 +0800
Subject: [PATCH 161/235] Update README.md
---
java-collections-maps-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md
index 75842c85a4..e2e0a56489 100644
--- a/java-collections-maps-3/README.md
+++ b/java-collections-maps-3/README.md
@@ -7,3 +7,4 @@
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map – keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
+- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)
From bb7b461a495e8dae1ca592510d4d1670d1a4a1bd Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Wed, 23 Feb 2022 19:54:43 +0530
Subject: [PATCH 162/235] JAVA-10081: Removed unused files and updated pom.xml
---
.../_2.fdt | Bin 160 -> 0 bytes
.../_2.fdx | Bin 84 -> 0 bytes
.../_2.fnm | Bin 532 -> 0 bytes
.../_2.nvd | Bin 65 -> 0 bytes
.../_2.nvm | Bin 88 -> 0 bytes
.../_2.si | Bin 514 -> 0 bytes
.../_2.tvd | Bin 392 -> 0 bytes
.../_2.tvx | Bin 79 -> 0 bytes
.../_2_Lucene50_0.doc | Bin 190 -> 0 bytes
.../_2_Lucene50_0.pos | Bin 162 -> 0 bytes
.../_2_Lucene50_0.tim | Bin 914 -> 0 bytes
.../_2_Lucene50_0.tip | Bin 195 -> 0 bytes
.../_3.cfe | Bin 341 -> 0 bytes
.../_3.cfs | Bin 2119 -> 0 bytes
.../_3.si | Bin 371 -> 0 bytes
.../segments_5 | Bin 198 -> 0 bytes
.../write.lock | 0
.../manytomany/dao/IEmployeeDao.java | 8 --
.../manytomany/dao/IProjectDao.java | 8 --
.../baeldung/spring/PersistenceConfig.java | 75 ------------------
.../src/main/resources/import.sql | 31 --------
.../src/main/resources/manytomany.cfg.xml | 15 ----
.../main/resources/persistence-h2.properties | 21 -----
.../src/test/resources/.gitignore | 13 ---
.../hibernate/criteria/model/Item.hbm.xml | 22 -----
.../src/test/resources/import.sql | 21 -----
.../.gitignore | 0
.../README.md | 4 +-
.../pom.xml | 66 ++-------------
.../manytomany}/PersistenceConfig.java | 8 +-
.../baeldung/manytomany/dao/IEmployeeDao.java | 8 ++
.../baeldung/manytomany/dao/IProjectDao.java | 8 ++
.../manytomany}/dao/common/AbstractDao.java | 2 +-
.../dao/common/AbstractHibernateDao.java | 2 +-
.../manytomany}/dao/common/IOperations.java | 2 +-
.../manytomany/dao/impl/EmployeeDao.java | 9 ++-
.../manytomany/dao/impl/ProjectDao.java | 9 ++-
.../baeldung}/manytomany/model/Employee.java | 2 +-
.../baeldung}/manytomany/model/Project.java | 3 +-
.../manytomany/util/HibernateUtil.java | 7 +-
.../src/main/resources/logback.xml | 0
.../main/resources/persistence-h2.properties | 11 +++
.../java/com/baeldung/SpringContextTest.java | 3 +-
...notationJavaConfigMainIntegrationTest.java | 7 +-
...nyToManyAnnotationMainIntegrationTest.java | 10 ++-
.../src/test/resources/manytomany.cfg.xml | 2 +-
46 files changed, 74 insertions(+), 303 deletions(-)
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvd
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvx
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.doc
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.pos
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tim
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5
delete mode 100644 persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
delete mode 100644 persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
delete mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
delete mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
delete mode 100644 persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/.gitignore (100%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/README.md (57%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/pom.xml (54%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring => hibernate-mapping-2/src/main/java/com/baeldung/manytomany}/PersistenceConfig.java (95%)
create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java
create mode 100644 persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/persistence => hibernate-mapping-2/src/main/java/com/baeldung/manytomany}/dao/common/AbstractDao.java (87%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/persistence => hibernate-mapping-2/src/main/java/com/baeldung/manytomany}/dao/common/AbstractHibernateDao.java (97%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/persistence => hibernate-mapping-2/src/main/java/com/baeldung/manytomany}/dao/common/IOperations.java (87%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/persistence => hibernate-mapping-2/src/main/java/com/baeldung}/manytomany/dao/impl/EmployeeDao.java (50%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/persistence => hibernate-mapping-2/src/main/java/com/baeldung}/manytomany/dao/impl/ProjectDao.java (50%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/hibernate => hibernate-mapping-2/src/main/java/com/baeldung}/manytomany/model/Employee.java (97%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/hibernate => hibernate-mapping-2/src/main/java/com/baeldung}/manytomany/model/Project.java (96%)
rename persistence-modules/{hibernate-many-to-many/src/main/java/com/baeldung/hibernate => hibernate-mapping-2/src/main/java/com/baeldung}/manytomany/util/HibernateUtil.java (90%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/src/main/resources/logback.xml (100%)
create mode 100644 persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/src/test/java/com/baeldung/SpringContextTest.java (91%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java (89%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java (92%)
rename persistence-modules/{hibernate-many-to-many => hibernate-mapping-2}/src/test/resources/manytomany.cfg.xml (97%)
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdt
deleted file mode 100644
index d71a08150212e0d18327d1491c3687976b1c0d38..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 160
zcmcD&o+B>fQ<|KbmuhMdT#{dun&Ot3nv+uOmRMZkl30?+z`($mbzSAP`{iOo;d#DB
z{fW~w7#bQFnHYE&m>Bf`D==s!=jZArB?2{-=B4XpWG1B+d6=BK3Q
y=miwzr<5j_a4;I`Gf2xDfe2#|VFDsd^%=wiK$2#Rj0ZF(zW`bZ2Af23UjYC|kS^)~
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fdx
deleted file mode 100644
index 72359255c620cb440b643215ce0e4a85f205da77..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 84
zcmcD&o+B>nQ<|KbmuhMdT#{dun&Ot3nv+uOmRMZknU|7U!N9=4m~~y{wfp5_L*aS8
hM*WG?G#Ho|fuamnK+Mp`ctB(F3!o}62&>U62LPU67+U}U
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.fnm
deleted file mode 100644
index b0143e1ac5e967810feee7771557bca5f71a4922..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 532
zcmcD&o+B>gQ<|KbmuhO@mYJH9;+dD0U(CS3z?gMi<+c0eVngA1zDE6t(=-@Z1>!R@
zlTwTF5=&C!lXDV_iy4@h8U8~7lWah05!i%){Nj?#y!2wX{G!~%61_Aq#R0Pfm$Ks0
zw6x3$MgykI6h;~t%Uw{EpHiA!;+L44%EU;0XLF~d7AF^F7L;V>=P}d3e74-w-29?S
W7A8ijhxh@F$uEEr4hGV{B@6-GbkQ<|KbmuhP4mtT}y?2=fL$N&Uc*HvD-UoJKjp66@SpEyl}p`^5=qP+Zo
P#^e_uX%J`#I_?Dk?LHOl
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.nvm
deleted file mode 100644
index 19f60a39bcf9a121ca3bc1590ba6df45481bf44a..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 88
zcmcD&o+B>mQ<|KbmuhP4mtT}y?3-GWn37nM$N&Uc*HvD-UoJKjp66@SpEyl}fe9oE
b0_Dt%5C((xe<0vLpfULcRDfZE({vpGz#bVo
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.si
deleted file mode 100644
index 3d537083b422c76bfcef3c42fb25ad1eeb45bf4f..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 514
zcmZWm-AcnS7+u9~xJ_kF@X}p)F_49(cGKM`sGA6z3LSV^LX*u()08Bwdy8ENUivJ)
zgBN=R!3XeC(?5_cA^AAx`_AEzTrB;A<|uMWK)QxaW|Rc-Hkh(fsiZwGkG^j{1#G^L
z%>{aEE3TyfJLTW{1{2jsFTm_Yw4hOYMlk|0QJC-DbL9G@b;WqdIFcR<>Uoeh~}|{1}jVe#N8(yQQWik
zQ)?at(xar1ultt;i?~bl)UlS{L*z=vHCR=Cd9F=p0Ank05)#pH8}_U&JhRM`Qv+J{
zvSWfE#=0uPOMr}VQl?mDXx?y4r+8<_03j2ZhNfddR`BW=X6}kmC0JuZ?Xa-6Rc?ZZ
k9`UglGER{Mlwnf69M}`bei#g{KiaQf$xkNh=X|#K1BMr#*8l(j
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2.tvd
deleted file mode 100644
index b46c8d109cc2a907cd84fbbf6e87ad51cff7929d..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 392
zcmW-dze`(D6vxlgC=Ftbkz&VE+Y%kb7xR(~f;J6xskBJ7;&$@h$$eMukH@|D5#1c@
zY@rZ05n3p562ZMwXQ6|CK$p@kP90qA)dSxH-w)?}hwt*0n4W%<$D}A)cuz)dQtY&`
zZFC3#!OqpQzpFoOICZ>MJ;Z(mhW4MpC=5S6J3Rp?TztHUHa12|C4al(ec7uGFuV`N
zwtdxl{be0L)M|6li$@3D#^4}aXWR8M+x#~3{HS=hKLx>c1%=gFCMeF0A>~LVU5v?S
znR1r$L}+IvNp1G5MB}nlE2>6yT!fHycnKzVAHu{-D2z5B46Dsq7;C_JiiUB;x<2JC
z{0js+vW_b<#BzbA1vkY!%e3)~^|&EH*1D7{AFu^KP$fq5gc(A&1lJEdWhiiWuVWi1
zZLV0H5@vs(@86~Fa6$8MJKp0e(LK9Ztw#&2BXY@6^4MsryRHdSk84eMcW;8=d*$dQ<|KbmuhMdl3J7-mYQ6WUsUXwmy%k+z`($mbzSAP`{iOo;d#DB{fW~w
c7?>D=q6{WL%lQ<|KbmuhMdkY8MqnU`K1UX)pqTI7lQ<|KbmuhMdkY8MqnU`K1UX)pqS_I@V072GumDlcM>D0O1m)+6Xon>a0yL6Ju
zPB5UIt(}E`f&YVGdMiQjZ}81-E~Sw9*!Mke-tWy$&h(9yN7^KB4lKX{*up(gi6?}x
z*JpSCJpJLeS3f@=zLy_2d(Y|wN*E1Z4#)(+SyRNB1?i()WjRx+P*rY95IW@bkya%{+IS}l
zD2zQ8g_$Z19Sd2lrR}*wTHi$UTwPVhhN?R=Ri|!pY
zU}+~qDjJ_4PtwPPQ1s#)4eVlYj=Dxd(kyhtg(^aYXnj$PsFP(_UTSb9ySE;6O@d^d4#s+OQVVr!snE98D%uaoJ%K^ar7cF
zA>#Ha<=ewOJ{*nN&XA9H2Yfsl(7m=nB9mIqk6AW7hdb7Fq2!f9CDu4|ud%Q3
z)|O}=w*Qa=sf%)2=veIo2S29o{)`q
GU*tdZxy^3?
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_2_Lucene50_0.tip
deleted file mode 100644
index 9803f1b398829ace933101fbc393ea47807267f3..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 195
zcmcD&o+B>ol#`#F9a5B<8j@O+TkM&al3KyQz`&GsUFEg=&diPJQ=d`gp3
z^HNO>;tlM9+L+yfLx9Ry85o(FA2Bg7FfyQtvaZ7>%C`xdDE~WbqC%6vqUOHImHmuB
VyFg&+0gcHoAWQ~^%eLE20RSolE8PG9
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfe
deleted file mode 100644
index 8fb074f30e754beeb8a030f31d07de2babe63b62..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 341
zcmcD&o+B>qQ<|KbmuhO@oS$2eUz(TVnpaYknOe*M1X
zMK3L-0we_ldJu{sm_;wIECtGGgwodh@i2qq4fG1~!R7(w_CVz$QRGwdlOf`aqEPuf
z6#0_OT&R3Agl1A?(JO&j%De=sX$r_CP?aneP{9bGoAY3T6QJ5fKprW9aM)nl8$o75
heaEf})$WhxkOGJ}J5)2n;R70zUqIC|B=Stl1OR>yJ!${|
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.cfs
deleted file mode 100644
index e26078b9e7cfbaca6e06ec3cf3156f48d0b92d08..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 2119
zcmcIl%TE(Q7@wKl?Nj9~Z^TD}V5}4bjIXK?ltcL?Vgcc6Uk_yF1P9Ho&d%ZHikvL|pRoxVQ^K
z83{+s+sl-S$2ZRGxRR1B3lRZvSZ<_#keUvHD~?{6F0vg-IFEoEWVdZrCXvvlaVybO
zd<3xJbWT_UvQ7y;{ItU=wG>lJ+Zr>3Bf$6RRA=Ul2s+O7`|vvMJrf^(q(=FfsB`Js
zdh6tGi|wZ)o5chXa%rs*9YE3nP;9|rzY@LhlP6H+Cg2g^emCA_KJlIwzKdsR=fI@nK?+`vA14I
OvhREg-uJeq`PhGT-i
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/_3.si
deleted file mode 100644
index f2d6b6a030c291e9fdddf28b924e5caad9a02f57..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 371
zcmcD&o+B>oQ<|KbmuhMdoSL4SnpfhPmzK}Kz`&SwUFEg=&diPN-zVhpTE
zn30i-DZiL2JTosPzr0w%(11HDu`E%qEEUKv67nxfOwLJFaLz9($S+DP$;{8=fl3z@
z13B!5hI$5ihKBqQ!Cas=u(%*pT-#FDCnQ+c(9(o22kbnU0#;K!AY{)k)=Ml(&R|W<
zO))bO0UJ_OnpcvUn+j8iX%bs;erZv1Dr;I!X>kS@&;+QREQSVp2Am+h#U+Wk1-yo4
zCZ>iKCPv2Q#-`@XtntQr#hGkCGC8dnLZvdw!^5m3zbG}uEi*MIrPwXMC^xZ0FE>9W
cmCMOBI3zwez}3~|fX3t(pr8YRcS#F10cJaIr~m)}
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5 b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/segments_5
deleted file mode 100644
index 66a4c385a5adac5ff16e505da6de875fcd295c3d..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 198
zcmcD&o+HjtoSL4SnpaZHz`($kbzSAP`{iOo;d#DB{fX1G8BJMPS%DHDAOOTHK+FUb
zVv09nL{qE5;ZvHNnwM&7@*fI7nqX`g4H9EuiZ@2rtwp?Uh65UtUx3X45?V&3b^sz|
BR7L;*
diff --git a/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock b/persistence-modules/hibernate-many-to-many/com.baeldung.hibernatesearch.model.Product/write.lock
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
deleted file mode 100644
index 5ba018dc52..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.persistence.manytomany.dao;
-
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.persistence.dao.common.IOperations;
-
-public interface IEmployeeDao extends IOperations{
-
-}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
deleted file mode 100644
index 48fbb8bf6b..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.persistence.manytomany.dao;
-
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.persistence.dao.common.IOperations;
-
-public interface IProjectDao extends IOperations{
-
-}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
deleted file mode 100644
index e1ea3e2024..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/spring/PersistenceConfig.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.baeldung.spring;
-
-import com.google.common.base.Preconditions;
-import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.core.env.Environment;
-import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.orm.hibernate5.HibernateTransactionManager;
-import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-import javax.sql.DataSource;
-import java.util.Properties;
-
-@Configuration
-@EnableTransactionManagement
-@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.persistence" })
-public class PersistenceConfig {
-
- @Autowired
- private Environment env;
-
- @Bean
- public LocalSessionFactoryBean sessionFactory() {
- final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
- sessionFactory.setDataSource(dataSource());
- sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
- sessionFactory.setHibernateProperties(hibernateProperties());
-
- return sessionFactory;
- }
-
- @Bean
- public DataSource dataSource() {
- final BasicDataSource dataSource = new BasicDataSource();
- dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
- dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
- dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
- dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
-
- return dataSource;
- }
-
- @Bean
- public PlatformTransactionManager hibernateTransactionManager() {
- final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
- transactionManager.setSessionFactory(sessionFactory().getObject());
- return transactionManager;
- }
-
- @Bean
- public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
- return new PersistenceExceptionTranslationPostProcessor();
- }
-
- private final Properties hibernateProperties() {
- final Properties hibernateProperties = new Properties();
- hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
- hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
-
- hibernateProperties.setProperty("hibernate.show_sql", "false");
-
- // Envers properties
- hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
-
- return hibernateProperties;
- }
-
-}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql b/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
deleted file mode 100644
index ae008f29bc..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/resources/import.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-insert into item (item_id, item_name, item_desc, item_price)
-values(1,'item One', 'test 1', 35.12);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(2,'Pogo stick', 'Pogo stick', 466.12);
-insert into item (item_id, item_name, item_desc, item_price)
-values(3,'Raft', 'Raft', 345.12);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(4,'Skate Board', 'Skating', 135.71);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(5,'Umbrella', 'Umbrella for Rain', 619.25);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(6,'Glue', 'Glue for home', 432.73);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(7,'Paint', 'Paint for Room', 1311.40);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(8,'Red paint', 'Red paint for room', 1135.71);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(9,'Household Chairs', 'Chairs for house', 25.71);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(10,'Office Chairs', 'Chairs for office', 395.98);
-
-insert into item (item_id, item_name, item_desc, item_price)
-values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml b/persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
deleted file mode 100644
index d7c8f24fb0..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/resources/manytomany.cfg.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
- com.mysql.jdbc.Driver
- tutorialmy5ql
- jdbc:mysql://localhost:3306/spring_hibernate_many_to_many
- tutorialuser
- org.hibernate.dialect.MySQLDialect
- thread
- false
-
-
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties b/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
deleted file mode 100644
index e3544d354a..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/main/resources/persistence-h2.properties
+++ /dev/null
@@ -1,21 +0,0 @@
-# jdbc.X
-jdbc.driverClassName=org.h2.Driver
-jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
-jdbc.eventGeneratedId=sa
-jdbc.user=sa
-jdbc.pass=
-
-# hibernate.X
-hibernate.dialect=org.hibernate.dialect.H2Dialect
-hibernate.show_sql=false
-hibernate.hbm2ddl.auto=create-drop
-hibernate.cache.use_second_level_cache=true
-hibernate.cache.use_query_cache=true
-hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
-
-# hibernate.search.X
-hibernate.search.default.directory_provider = filesystem
-hibernate.search.default.indexBase = /data/index/default
-
-# envers.X
-envers.audit_table_suffix=_audit_log
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore b/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/test/resources/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
deleted file mode 100644
index 9e0109aae2..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql b/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
deleted file mode 100644
index 087d62d331..0000000000
--- a/persistence-modules/hibernate-many-to-many/src/test/resources/import.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12);
-
-insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);
-
-insert into item (item_id, item_name, item_desc, item_price) values(3,'Raft', 'Raft', 345.12);
-
-insert into item (item_id, item_name, item_desc, item_price) values(4,'Skate Board', 'Skating', 135.71);
-
-insert into item (item_id, item_name, item_desc, item_price) values(5,'Umbrella', 'Umbrella for Rain', 619.25);
-
-insert into item (item_id, item_name, item_desc, item_price) values(6,'Glue', 'Glue for home', 432.73);
-
-insert into item (item_id, item_name, item_desc, item_price) values(7,'Paint', 'Paint for Room', 1311.40);
-
-insert into item (item_id, item_name, item_desc, item_price) values(8,'Red paint', 'Red paint for room', 1135.71);
-
-insert into item (item_id, item_name, item_desc, item_price) values(9,'Household Chairs', 'Chairs for house', 25.71);
-
-insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98);
-
-insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36);
diff --git a/persistence-modules/hibernate-many-to-many/.gitignore b/persistence-modules/hibernate-mapping-2/.gitignore
similarity index 100%
rename from persistence-modules/hibernate-many-to-many/.gitignore
rename to persistence-modules/hibernate-mapping-2/.gitignore
diff --git a/persistence-modules/hibernate-many-to-many/README.md b/persistence-modules/hibernate-mapping-2/README.md
similarity index 57%
rename from persistence-modules/hibernate-many-to-many/README.md
rename to persistence-modules/hibernate-mapping-2/README.md
index 19b865d4e1..7a811e17cf 100644
--- a/persistence-modules/hibernate-many-to-many/README.md
+++ b/persistence-modules/hibernate-mapping-2/README.md
@@ -1,6 +1,6 @@
-## Hibernate 5 with Spring
+## Hibernate Mapping
-This module contains articles about Hibernate 5 with Spring.
+This module contains articles about Hibernate Mappings.
### Relevant articles
diff --git a/persistence-modules/hibernate-many-to-many/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml
similarity index 54%
rename from persistence-modules/hibernate-many-to-many/pom.xml
rename to persistence-modules/hibernate-mapping-2/pom.xml
index 6f1abb6a7a..10c07c95eb 100644
--- a/persistence-modules/hibernate-many-to-many/pom.xml
+++ b/persistence-modules/hibernate-mapping-2/pom.xml
@@ -3,9 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- hibernate-many-to-many
+ hibernate-mapping-2y
0.1-SNAPSHOT
- hibernate-many-to-many
+ hibernate-mapping-2
com.baeldung
@@ -19,24 +19,8 @@
org.springframework
spring-context
${org.springframework.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.springframework
- spring-aspects
- ${org.springframework.version}
-
- org.springframework
- spring-orm
- ${org.springframework.version}
-
org.springframework.data
spring-data-jpa
@@ -47,16 +31,6 @@
hibernate-core
${hibernate.version}
-
- javax.transaction
- jta
- ${jta.version}
-
-
- org.hibernate
- hibernate-search-orm
- ${hibernatesearch.version}
-
org.apache.tomcat
tomcat-dbcp
@@ -70,53 +44,31 @@
${guava.version}
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
- test
-
org.springframework
spring-test
${org.springframework.version}
test
-
- org.springframework.security
- spring-security-test
- ${org.springframework.security.version}
- test
-
-
- org.hsqldb
- hsqldb
- ${hsqldb.version}
-
com.h2database
h2
${h2.version}
-
-
- jakarta.xml.bind
- jakarta.xml.bind-api
- 2.3.2
-
+
com.sun.xml.bind
jaxb-core
- 2.3.0.1
+ ${com.sun.xml.version}
javax.xml.bind
jaxb-api
- 2.3.1
+ ${javax.xml.bind.version}
com.sun.xml.bind
jaxb-impl
- 2.3.1
+ ${com.sun.xml.version}
@@ -124,13 +76,11 @@
5.0.2.RELEASE
1.10.6.RELEASE
- 4.2.1.RELEASE
5.2.10.Final
- 5.8.2.Final
9.0.0.M26
- 1.1
- 2.3.4
+ 2.3.0.1
+ 2.3.1
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java
similarity index 95%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java
index f7179b07e5..0d7b8bdbcf 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java
@@ -1,7 +1,9 @@
-package com.baeldung.manytomany.spring;
+package com.baeldung.manytomany;
import java.util.Properties;
+
import javax.sql.DataSource;
+
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@@ -20,7 +22,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.hibernate.manytomany" })
+@ComponentScan({ "com.baeldung.manytomany" })
public class PersistenceConfig {
@Autowired
@@ -30,7 +32,7 @@ public class PersistenceConfig {
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
- sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java
new file mode 100644
index 0000000000..68bf5d5bad
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java
@@ -0,0 +1,8 @@
+package com.baeldung.manytomany.dao;
+
+import com.baeldung.manytomany.dao.common.IOperations;
+import com.baeldung.manytomany.model.Employee;
+
+public interface IEmployeeDao extends IOperations{
+
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java
new file mode 100644
index 0000000000..d2645db44a
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java
@@ -0,0 +1,8 @@
+package com.baeldung.manytomany.dao;
+
+import com.baeldung.manytomany.dao.common.IOperations;
+import com.baeldung.manytomany.model.Project;
+
+public interface IProjectDao extends IOperations{
+
+}
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java
similarity index 87%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java
index 5a6c76a93a..b37b48e645 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java
@@ -1,4 +1,4 @@
-package com.baeldung.persistence.dao.common;
+package com.baeldung.manytomany.dao.common;
import java.io.Serializable;
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java
similarity index 97%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java
index f34866d883..9c8a8faa2e 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java
@@ -1,4 +1,4 @@
-package com.baeldung.persistence.dao.common;
+package com.baeldung.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java
similarity index 87%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java
index 4ef99221ab..8a85b52fc9 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java
@@ -1,4 +1,4 @@
-package com.baeldung.persistence.dao.common;
+package com.baeldung.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java
similarity index 50%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java
index 25fee8c379..b24013c567 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java
@@ -1,9 +1,10 @@
-package com.baeldung.persistence.manytomany.dao.impl;
+package com.baeldung.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.persistence.dao.common.AbstractHibernateDao;
-import com.baeldung.persistence.manytomany.dao.IEmployeeDao;
+
+import com.baeldung.manytomany.dao.IEmployeeDao;
+import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
+import com.baeldung.manytomany.model.Employee;
@Repository
public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao {
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java
similarity index 50%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java
index 8fc29a5de3..a70212f519 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java
@@ -1,9 +1,10 @@
-package com.baeldung.persistence.manytomany.dao.impl;
+package com.baeldung.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.persistence.dao.common.AbstractHibernateDao;
-import com.baeldung.persistence.manytomany.dao.IProjectDao;
+
+import com.baeldung.manytomany.dao.IProjectDao;
+import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
+import com.baeldung.manytomany.model.Project;
@Repository
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java
similarity index 97%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java
index bfe1b5ad29..39671c21bc 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java
@@ -1,4 +1,4 @@
-package com.baeldung.hibernate.manytomany.model;
+package com.baeldung.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java
similarity index 96%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java
index c291d7d7af..b5dc3cb856 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java
@@ -1,8 +1,9 @@
-package com.baeldung.hibernate.manytomany.model;
+package com.baeldung.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
diff --git a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java
similarity index 90%
rename from persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java
index ff035c0c37..d429564564 100644
--- a/persistence-modules/hibernate-many-to-many/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java
@@ -1,14 +1,15 @@
-package com.baeldung.hibernate.manytomany.util;
+package com.baeldung.manytomany.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.baeldung.manytomany.model.Employee;
+import com.baeldung.manytomany.model.Project;
+
public class HibernateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
diff --git a/persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml b/persistence-modules/hibernate-mapping-2/src/main/resources/logback.xml
similarity index 100%
rename from persistence-modules/hibernate-many-to-many/src/main/resources/logback.xml
rename to persistence-modules/hibernate-mapping-2/src/main/resources/logback.xml
diff --git a/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties b/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties
new file mode 100644
index 0000000000..9c8cf6e02b
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties
@@ -0,0 +1,11 @@
+# jdbc.X
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+jdbc.eventGeneratedId=sa
+jdbc.user=sa
+jdbc.pass=
+
+# hibernate.X
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=false
+hibernate.hbm2ddl.auto=create-drop
\ No newline at end of file
diff --git a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
similarity index 91%
rename from persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java
rename to persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
index 24c038aeb6..f1a6f675ce 100644
--- a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/SpringContextTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
@@ -6,8 +6,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-import com.baeldung.spring.PersistenceConfig;
+import com.baeldung.manytomany.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
diff --git a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
similarity index 89%
rename from persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
rename to persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
index 797d3384a0..19d1a5ff50 100644
--- a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
@@ -2,6 +2,7 @@ package com.baeldung.hibernate.manytomany;
import java.util.HashSet;
import java.util.Set;
+
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
@@ -12,9 +13,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
-import com.baeldung.manytomany.spring.PersistenceConfig;
+import com.baeldung.manytomany.PersistenceConfig;
+import com.baeldung.manytomany.model.Employee;
+import com.baeldung.manytomany.model.Project;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
diff --git a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
similarity index 92%
rename from persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
rename to persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
index d09b2888df..bfa158d43f 100644
--- a/persistence-modules/hibernate-many-to-many/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
@@ -1,10 +1,12 @@
package com.baeldung.hibernate.manytomany;
-import static org.junit.Assert.assertNotNull;
import static junit.framework.TestCase.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
@@ -13,9 +15,9 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import com.baeldung.hibernate.manytomany.util.HibernateUtil;
-import com.baeldung.hibernate.manytomany.model.Employee;
-import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.manytomany.model.Employee;
+import com.baeldung.manytomany.model.Project;
+import com.baeldung.manytomany.util.HibernateUtil;
/**
* Configured in: manytomany.cfg.xml
diff --git a/persistence-modules/hibernate-many-to-many/src/test/resources/manytomany.cfg.xml b/persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml
similarity index 97%
rename from persistence-modules/hibernate-many-to-many/src/test/resources/manytomany.cfg.xml
rename to persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml
index 2ca23d57d3..3ddff9a993 100644
--- a/persistence-modules/hibernate-many-to-many/src/test/resources/manytomany.cfg.xml
+++ b/persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml
@@ -13,4 +13,4 @@
false
create-drop
-
+
\ No newline at end of file
From 91bd7fa37fcab4b499fa38fe527deae21791a4b7 Mon Sep 17 00:00:00 2001
From: Loredana Crusoveanu
Date: Wed, 23 Feb 2022 17:43:45 +0200
Subject: [PATCH 163/235] remove duplicate code from old module BAEL-5336
---
spring-5-autowiring-beans/README.md | 3 --
spring-5-autowiring-beans/pom.xml | 24 ----------------
.../java/com/baeldung/autowiring/App.java | 14 ----------
.../controller/CorrectController.java | 18 ------------
.../controller/FlawedController.java | 15 ----------
.../autowiring/service/MyComponent.java | 10 -------
.../autowiring/service/MyService.java | 19 -------------
.../service/MyServiceConfiguration.java | 14 ----------
.../CorrectControllerIntegrationTest.java | 23 ---------------
.../FlawedControllerIntegrationTest.java | 28 -------------------
10 files changed, 168 deletions(-)
delete mode 100644 spring-5-autowiring-beans/README.md
delete mode 100644 spring-5-autowiring-beans/pom.xml
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
delete mode 100644 spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
delete mode 100644 spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
delete mode 100644 spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
diff --git a/spring-5-autowiring-beans/README.md b/spring-5-autowiring-beans/README.md
deleted file mode 100644
index dc8751325e..0000000000
--- a/spring-5-autowiring-beans/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant Articles:
-
-- [Spring @Autowired Field Null – Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null)
diff --git a/spring-5-autowiring-beans/pom.xml b/spring-5-autowiring-beans/pom.xml
deleted file mode 100644
index 32b56cc9ad..0000000000
--- a/spring-5-autowiring-beans/pom.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
- 4.0.0
- spring-5-autowiring-beans
- 0.0.1-SNAPSHOT
- spring-5-autowiring-beans
-
-
- com.baeldung
- parent-boot-2
- 0.0.1-SNAPSHOT
- ../parent-boot-2
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
-
-
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
deleted file mode 100644
index d2d0db7a60..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/App.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.baeldung.autowiring;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.annotation.ComponentScan;
-
-@SpringBootApplication
-public class App {
-
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
deleted file mode 100644
index e0c0d7eeac..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.baeldung.autowiring.controller;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-
-import com.baeldung.autowiring.service.MyService;
-
-@Controller
-public class CorrectController {
-
- @Autowired
- MyService myService;
-
- public String control() {
- return myService.serve();
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
deleted file mode 100644
index 673e686f79..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.baeldung.autowiring.controller;
-
-import org.springframework.stereotype.Controller;
-
-import com.baeldung.autowiring.service.MyService;
-
-@Controller
-public class FlawedController {
-
- public String control() {
- MyService userService = new MyService();
- return userService.serve();
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
deleted file mode 100644
index c04ca3f4ba..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyComponent.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.baeldung.autowiring.service;
-
-import org.springframework.stereotype.Component;
-
-@Component
-public class MyComponent {
-
- public void doWork() {}
-
-}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
deleted file mode 100644
index 3443dc05de..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyService.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.autowiring.service;
-
-import org.springframework.beans.factory.annotation.Autowired;
-
-/**
- * The bean corresponding to this class is defined in MyServiceConfiguration
- * Alternatively, you could choose to decorate this class with @Component or @Service
- */
-public class MyService {
-
- @Autowired
- MyComponent myComponent;
-
- public String serve() {
- myComponent.doWork();
- return "success";
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java b/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
deleted file mode 100644
index e30e4f770e..0000000000
--- a/spring-5-autowiring-beans/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.baeldung.autowiring.service;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-public class MyServiceConfiguration {
-
- @Bean
- MyService myService() {
- return new MyService();
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
deleted file mode 100644
index 3807641edd..0000000000
--- a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.baeldung.autowiring.controller;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-
-@ExtendWith(SpringExtension.class)
-@SpringBootTest
-public class CorrectControllerIntegrationTest {
-
- @Autowired
- CorrectController controller;
-
- @Test
- void whenControl_ThenRunSuccessfully() {
- assertDoesNotThrow(() -> controller.control());
- }
-
-}
diff --git a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java b/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
deleted file mode 100644
index 79d446604f..0000000000
--- a/spring-5-autowiring-beans/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.baeldung.autowiring.controller;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-@ExtendWith(SpringExtension.class)
-@SpringBootTest
-public class FlawedControllerIntegrationTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(FlawedControllerIntegrationTest.class);
-
- @Autowired
- FlawedController myController;
-
- @Test
- void whenControl_ThenThrowNullPointerException() {
- NullPointerException npe = assertThrows(NullPointerException.class, () -> myController.control());
- LOGGER.error("Got a NullPointerException", npe);
- }
-
-}
From 87c9fde8d71247c349dc0345947f2c5d857af3ed Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Wed, 23 Feb 2022 17:04:52 +0000
Subject: [PATCH 164/235] [JAVA-9909] Fix code for DFS article
---
.../baeldung/algorithms/dfs/BinaryTree.java | 78 ++++++-------------
.../algorithms/dfs/BinaryTreeUnitTest.java | 14 +---
2 files changed, 28 insertions(+), 64 deletions(-)
diff --git a/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java b/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java
index a6019ea9f9..a3cb2b396e 100644
--- a/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java
+++ b/algorithms-searching/src/main/java/com/baeldung/algorithms/dfs/BinaryTree.java
@@ -1,7 +1,5 @@
package com.baeldung.algorithms.dfs;
-import java.util.LinkedList;
-import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
@@ -124,69 +122,43 @@ public class BinaryTree {
}
}
- public void traverseLevelOrder() {
- if (root == null) {
- return;
- }
- Queue nodes = new LinkedList<>();
- nodes.add(root);
-
- while (!nodes.isEmpty()) {
-
- Node node = nodes.remove();
-
- System.out.print(" " + node.value);
-
- if (node.left != null) {
- nodes.add(node.left);
- }
-
- if (node.left != null) {
- nodes.add(node.right);
- }
- }
- }
-
-
public void traverseInOrderWithoutRecursion() {
- Stack stack = new Stack();
+ Stack stack = new Stack<>();
Node current = root;
- stack.push(root);
- while(! stack.isEmpty()) {
- while(current.left != null) {
- current = current.left;
- stack.push(current);
- }
- current = stack.pop();
- visit(current.value);
- if(current.right != null) {
- current = current.right;
+
+ while (current != null || !stack.isEmpty()) {
+ while (current != null) {
stack.push(current);
+ current = current.left;
}
+
+ Node top = stack.pop();
+ visit(top.value);
+ current = top.right;
}
}
-
+
public void traversePreOrderWithoutRecursion() {
- Stack stack = new Stack();
- Node current = root;
+ Stack stack = new Stack<>();
+ Node current;
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
visit(current.value);
-
+
if(current.right != null)
stack.push(current.right);
-
+
if(current.left != null)
stack.push(current.left);
- }
+ }
}
-
+
public void traversePostOrderWithoutRecursion() {
- Stack stack = new Stack();
+ Stack stack = new Stack<>();
Node prev = root;
- Node current = root;
+ Node current;
stack.push(root);
while (!stack.isEmpty()) {
@@ -206,14 +178,14 @@ public class BinaryTree {
stack.push(current.left);
}
}
- }
- }
-
- private void visit(int value) {
- System.out.print(" " + value);
+ }
}
-
- class Node {
+
+ private void visit(int value) {
+ System.out.print(" " + value);
+ }
+
+ static class Node {
int value;
Node left;
Node right;
diff --git a/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java b/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java
index 076da14f81..f98b4377ed 100644
--- a/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java
+++ b/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java
@@ -1,11 +1,11 @@
package com.baeldung.algorithms.dfs;
+import org.junit.Test;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
public class BinaryTreeUnitTest {
@Test
@@ -13,7 +13,7 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
- assertTrue(!bt.isEmpty());
+ assertFalse(bt.isEmpty());
}
@Test
@@ -111,14 +111,6 @@ public class BinaryTreeUnitTest {
bt.traversePostOrderWithoutRecursion();
}
- @Test
- public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
-
- BinaryTree bt = createBinaryTree();
-
- bt.traverseLevelOrder();
- }
-
private BinaryTree createBinaryTree() {
BinaryTree bt = new BinaryTree();
From 6ca42b7a4ecbbffc2b8a890f70995cbbe8dc4a6f Mon Sep 17 00:00:00 2001
From: lsieun <331505785@qq.com>
Date: Fri, 25 Feb 2022 05:13:13 +0800
Subject: [PATCH 165/235] BAEL-4151: Guide to ByteBuffer (#11859)
* Convert Byte Array to its Numeric Representation
* Remove Redundant Getter Method
* BAEL-4286 How to get the value of a bit at a certain position from a byte
* BAEL-4286(update): remove redundant test methods
* BAEL-4151: Guide to ByteBuffer
---
.../bytebuffer/ByteBufferUnitTest.java | 339 ++++++++++++++++++
1 file changed, 339 insertions(+)
create mode 100644 core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java
diff --git a/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java
new file mode 100644
index 0000000000..5d108ba14a
--- /dev/null
+++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/bytebuffer/ByteBufferUnitTest.java
@@ -0,0 +1,339 @@
+package com.baeldung.bytebuffer;
+
+import org.junit.Test;
+
+import java.lang.reflect.Field;
+import java.nio.*;
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.Assert.*;
+
+public class ByteBufferUnitTest {
+ @Test
+ public void givenBufferCreation_whenUsingAllocate_thenSuccess() {
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertNotNull(buffer);
+ }
+
+ @Test
+ public void givenBufferCreation_whenUsingAllocateDirect_thenSuccess() {
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ assertNotNull(buffer);
+ }
+
+ @Test
+ public void givenBufferCreation_whenUsingWrap_thenSuccess() {
+ byte[] bytes = new byte[10];
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ assertNotNull(buffer);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingAllocate_thenInitialIndices() {
+ // create instance using allocate
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+
+ // get index
+ int position = buffer.position();
+ int limit = buffer.limit();
+ int capacity = buffer.capacity();
+
+ // assert
+ assertEquals(0, position);
+ assertEquals(10, limit);
+ assertEquals(10, capacity);
+ }
+
+ @Test
+ public void givenBufferIndex_whenChangingPositionAndLimit_thenSuccess() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+
+ // change index
+ buffer.position(2);
+ buffer.limit(5);
+
+ // assert
+ assertIndex(buffer, -1, 2, 5, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingWrap_thenInitialIndices() {
+ // create instance
+ byte[] bytes = new byte[10];
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+
+ // assert
+ assertIndex(buffer, -1, 0, 10, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingWrapWithOffsetAndLength_thenInitialIndices() {
+ // create instance
+ byte[] bytes = new byte[10];
+ ByteBuffer buffer = ByteBuffer.wrap(bytes, 2, 6);
+
+ // assert
+ assertIndex(buffer, -1, 2, 8, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingMarkAndReset_thenOK() {
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ buffer.position(2);
+ assertIndex(buffer, -1, 2, 10, 10);
+
+ buffer.mark();
+ assertIndex(buffer, 2, 2, 10, 10);
+
+ buffer.position(5);
+ assertIndex(buffer, 2, 5, 10, 10);
+
+ buffer.reset();
+ assertIndex(buffer, 2, 2, 10, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingClear_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // clear
+ buffer.clear();
+ assertIndex(buffer, -1, 0, 10, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingFlip_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // flip
+ buffer.flip();
+ assertIndex(buffer, -1, 0, 5, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingRewind_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // rewind
+ buffer.rewind();
+ assertIndex(buffer, -1, 0, 8, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingCompact_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // compact
+ buffer.compact();
+ assertIndex(buffer, -1, 3, 10, 10);
+ }
+
+ @Test
+ public void givenBufferIndex_whenUsingRemain_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+
+ // change index
+ buffer.position(2);
+ buffer.limit(8);
+
+ // remain
+ boolean flag = buffer.hasRemaining();
+ int remaining = buffer.remaining();
+
+ // assert
+ assertTrue(flag);
+ assertEquals(6, remaining);
+ }
+
+ @Test(expected = BufferUnderflowException.class)
+ public void givenNotEnoughRemaining_WhenCallingGetInt_thenBufferUnderflowException() {
+ ByteBuffer buffer = ByteBuffer.allocate(2);
+ buffer.getInt();
+ }
+
+ @Test(expected = BufferOverflowException.class)
+ public void givenNotEnoughRemaining_WhenCallingPutInt_thenBufferOverflowException() {
+ ByteBuffer buffer = ByteBuffer.allocate(2);
+ buffer.putInt(10);
+ }
+
+ @Test
+ public void givenBufferView_whenUsingDuplicate_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // view
+ ByteBuffer view = buffer.duplicate();
+ assertIndex(view, 2, 5, 8, 10);
+ }
+
+ @Test
+ public void givenBufferView_whenUsingSlice_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // view
+ ByteBuffer view = buffer.slice();
+ assertIndex(view, -1, 0, 3, 3);
+ }
+
+ @Test
+ public void givenBufferView_whenUsingAsReaOnlyBuffer_thenOK() {
+ // create instance
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ assertIndex(buffer, -1, 0, 10, 10);
+
+ // change index
+ buffer.position(2);
+ buffer.mark();
+ buffer.position(5);
+ buffer.limit(8);
+ assertIndex(buffer, 2, 5, 8, 10);
+
+ // view
+ ByteBuffer view = buffer.asReadOnlyBuffer();
+ assertIndex(view, 2, 5, 8, 10);
+ }
+
+ @Test
+ public void givenBufferView_whenUsingAsIntBuffer_thenOK() {
+ // create instance
+ byte[] bytes = new byte[]{
+ (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, // CAFEBABE ---> cafebabe
+ (byte) 0xF0, (byte) 0x07, (byte) 0xBA, (byte) 0x11, // F007BA11 ---> football
+ (byte) 0x0F, (byte) 0xF1, (byte) 0xCE // 0FF1CE ---> office
+ };
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ assertIndex(buffer, -1, 0, 11, 11);
+
+ // view
+ IntBuffer intBuffer = buffer.asIntBuffer();
+ int capacity = intBuffer.capacity();
+ assertEquals(2, capacity);
+ assertIndex(intBuffer, -1, 0, 2, 2);
+ }
+
+ @Test
+ public void givenByteOrder_whenUsingBigEndian_thenOK() {
+ // create instance
+ byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+
+ // change byte order
+ buffer.order(ByteOrder.BIG_ENDIAN);
+ int val = buffer.getInt();
+
+ // assert
+ assertEquals(0xCAFEBABE, val);
+ }
+
+ @Test
+ public void givenByteOrder_whenUsingLittleEndian_thenOK() {
+ // create instance
+ byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+
+ // change byte order
+ buffer.order(ByteOrder.LITTLE_ENDIAN);
+ int val = buffer.getInt();
+
+ // assert
+ assertEquals(0xBEBAFECA, val);
+ }
+
+ @Test
+ public void givenComparing_whenUsingEqualsAndCompareTo_thenOK() {
+ // create instance
+ byte[] bytes1 = "World".getBytes(StandardCharsets.UTF_8);
+ byte[] bytes2 = "HelloWorld".getBytes(StandardCharsets.UTF_8);
+ ByteBuffer buffer1 = ByteBuffer.wrap(bytes1);
+ ByteBuffer buffer2 = ByteBuffer.wrap(bytes2);
+
+ // change index
+ buffer2.position(5);
+
+ // equals and compareTo
+ boolean equal = buffer1.equals(buffer2);
+ int result = buffer1.compareTo(buffer2);
+
+ // assert
+ assertTrue(equal);
+ assertEquals(0, result);
+ }
+
+ private void assertIndex(Buffer buffer, int mark, int position, int limit, int capacity) {
+ assertEquals(mark, getMark(buffer));
+ assertEquals(position, buffer.position());
+ assertEquals(limit, buffer.limit());
+ assertEquals(capacity, buffer.capacity());
+ }
+
+ private int getMark(Buffer buffer) {
+ try {
+ Class> clazz = Buffer.class;
+ Field f = clazz.getDeclaredField("mark");
+ f.setAccessible(true);
+ Object result = f.get(buffer);
+ return (int) result;
+ } catch (NoSuchFieldException | IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ return -1;
+ }
+}
From 1d80576a7c6d795e552af488b42e31662ce7c79c Mon Sep 17 00:00:00 2001
From: vunamtien
Date: Fri, 25 Feb 2022 04:15:22 +0700
Subject: [PATCH 166/235] BAEL-5379-create-simple-rock-paper-scissors-game
(#11855)
* BAEL-5379-create-simple-rock-paper-scissors-game
* BAEL-5379-create-simple-rock-paper-scissors-game
* BAEL-5379-create-simple-rock-paper-scissors-game
Co-authored-by: tienvn4
---
.../baeldung/game/RockPaperScissorsGame.java | 35 +++++++++++--------
1 file changed, 21 insertions(+), 14 deletions(-)
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
index fc9299f12d..17f0f02698 100644
--- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java
@@ -1,17 +1,24 @@
package com.baeldung.game;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Random;
-import java.util.Scanner;
+import java.util.*;
class RockPaperScissorsGame {
- private static Map movesMap = new HashMap() {{
- put(0, "rock");
- put(1, "paper");
- put(2, "scissors");
- }};
+ enum Move {
+ ROCK("rock"),
+ PAPER("paper"),
+ SCISSORS("scissors");
+
+ private String value;
+
+ Move(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+ }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
@@ -31,7 +38,7 @@ class RockPaperScissorsGame {
break;
}
- if (!movesMap.containsValue(playerMove)) {
+ if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) {
System.out.println("Your move isn't valid!");
continue;
}
@@ -51,15 +58,15 @@ class RockPaperScissorsGame {
}
private static boolean isPlayerWin(String playerMove, String computerMove) {
- return playerMove.equals("rock") && computerMove.equals("scissors")
- || (playerMove.equals("scissors") && computerMove.equals("paper"))
- || (playerMove.equals("paper") && computerMove.equals("rock"));
+ return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value)
+ || (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value))
+ || (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value));
}
private static String getComputerMove() {
Random random = new Random();
int randomNumber = random.nextInt(3);
- String computerMove = movesMap.get(randomNumber);
+ String computerMove = Move.values()[randomNumber].getValue();
System.out.println("Computer move: " + computerMove);
return computerMove;
}
From cb65018f66cd2a7405f89797d139b9ce63381963 Mon Sep 17 00:00:00 2001
From: lucaCambi77
Date: Fri, 25 Feb 2022 02:17:58 +0100
Subject: [PATCH 167/235] [ BAEL-5337 ] - Enable Logging for Spring Security
(#11803)
* feat: logging application
* fix: apply formatter
---
.../baeldung/logging/LoggingController.java | 16 ++++++++++++
.../com/baeldung/logging/SecurityConfig.java | 26 +++++++++++++++++++
.../logging/SecurityLoggingApplication.java | 14 ++++++++++
.../resources/application-logging.properties | 4 +++
4 files changed, 60 insertions(+)
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/LoggingController.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityConfig.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityLoggingApplication.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/resources/application-logging.properties
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/LoggingController.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/LoggingController.java
new file mode 100644
index 0000000000..c2d47fe6d6
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/LoggingController.java
@@ -0,0 +1,16 @@
+package com.baeldung.logging;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+
+@Controller
+public class LoggingController {
+
+ @GetMapping("/logging")
+ public ResponseEntity logging() {
+ return new ResponseEntity<>("logging/baeldung", HttpStatus.OK);
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityConfig.java
new file mode 100644
index 0000000000..f48f817dd2
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityConfig.java
@@ -0,0 +1,26 @@
+package com.baeldung.logging;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@EnableWebSecurity
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ @Value("${spring.websecurity.debug:false}")
+ boolean webSecurityDebug;
+
+ @Override
+ public void configure(WebSecurity web) {
+ web.debug(webSecurityDebug);
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests()
+ .antMatchers("/**")
+ .permitAll();
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityLoggingApplication.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityLoggingApplication.java
new file mode 100644
index 0000000000..2fadf1cc26
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/logging/SecurityLoggingApplication.java
@@ -0,0 +1,14 @@
+package com.baeldung.logging;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SecurityLoggingApplication {
+
+ public static void main(String... args) {
+ SpringApplication application = new SpringApplication(SecurityLoggingApplication.class);
+ application.setAdditionalProfiles("logging");
+ application.run(args);
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-logging.properties b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-logging.properties
new file mode 100644
index 0000000000..4f0c3450a3
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-logging.properties
@@ -0,0 +1,4 @@
+
+logging.level.org.springframework.security=DEBUG
+
+spring.websecurity.debug=true
\ No newline at end of file
From f74400ee6ec1449ebabe16794338927410e2d768 Mon Sep 17 00:00:00 2001
From: Ulisses Lima
Date: Fri, 25 Feb 2022 03:36:17 -0300
Subject: [PATCH 168/235] BAEL-2080 - Check if a user is logged-in with
Servlets and JSP (#11821)
* BAEL-2080 - Check if a user is logged-in with Servlets and JSP
* new module: javax-servlets-2
* adding javax-servlets-2 to the parent pom.
* adding module javax-servlets-2 to all profiles
---
javax-servlets-2/README.md | 5 +
javax-servlets-2/pom.xml | 60 ++++++++++++
.../java/com/baeldung/user/check/User.java | 80 +++++++++++++++
.../baeldung/user/check/UserCheckFilter.java | 46 +++++++++
.../user/check/UserCheckLoginServlet.java | 56 +++++++++++
.../user/check/UserCheckLogoutServlet.java | 26 +++++
.../baeldung/user/check/UserCheckServlet.java | 28 ++++++
.../src/main/resources/logback.xml | 13 +++
.../main/webapp/WEB-INF/user.check/home.jsp | 31 ++++++
.../main/webapp/WEB-INF/user.check/login.jsp | 33 +++++++
.../user/check/UserCheckServletLiveTest.java | 98 +++++++++++++++++++
pom.xml | 2 +
12 files changed, 478 insertions(+)
create mode 100644 javax-servlets-2/README.md
create mode 100644 javax-servlets-2/pom.xml
create mode 100644 javax-servlets-2/src/main/java/com/baeldung/user/check/User.java
create mode 100644 javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java
create mode 100644 javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java
create mode 100644 javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java
create mode 100644 javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java
create mode 100644 javax-servlets-2/src/main/resources/logback.xml
create mode 100644 javax-servlets-2/src/main/webapp/WEB-INF/user.check/home.jsp
create mode 100644 javax-servlets-2/src/main/webapp/WEB-INF/user.check/login.jsp
create mode 100644 javax-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java
diff --git a/javax-servlets-2/README.md b/javax-servlets-2/README.md
new file mode 100644
index 0000000000..f126f17297
--- /dev/null
+++ b/javax-servlets-2/README.md
@@ -0,0 +1,5 @@
+## Servlets
+
+This module contains articles about Servlets.
+
+### Relevant Articles:
diff --git a/javax-servlets-2/pom.xml b/javax-servlets-2/pom.xml
new file mode 100644
index 0000000000..34c00c3d05
--- /dev/null
+++ b/javax-servlets-2/pom.xml
@@ -0,0 +1,60 @@
+
+
+ 4.0.0
+ com.baeldung.javax-servlets
+ javax-servlets-2
+ 1.0-SNAPSHOT
+ javax-servlets-2
+ war
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+ commons-fileupload
+ commons-fileupload
+ ${commons-fileupload.version}
+
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-api.version}
+
+
+ javax.servlet.jsp
+ javax.servlet.jsp-api
+ ${javax.servlet.jsp-api.version}
+ provided
+
+
+ javax.servlet
+ jstl
+ ${jstl.version}
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${org.apache.httpcomponents.version}
+ test
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+
+
+ 4.5.13
+ 4.0.1
+
+
diff --git a/javax-servlets-2/src/main/java/com/baeldung/user/check/User.java b/javax-servlets-2/src/main/java/com/baeldung/user/check/User.java
new file mode 100644
index 0000000000..f61c0490bc
--- /dev/null
+++ b/javax-servlets-2/src/main/java/com/baeldung/user/check/User.java
@@ -0,0 +1,80 @@
+package com.baeldung.user.check;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * @since 6 de fev de 2022
+ * @author ulisses
+ */
+public class User implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ protected static final HashMap DB = new HashMap<>();
+ static {
+ DB.put("admin", new User("admin", "password"));
+ DB.put("user", new User("user", "pass"));
+ }
+
+ private String name;
+ private String password;
+
+ private List logins = new ArrayList();
+
+ public User(String name, String password) {
+ this.name = name;
+ this.password = password;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getLogins() {
+ return logins;
+ }
+
+ public void setLogins(List logins) {
+ this.logins = logins;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ User other = (User) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+}
diff --git a/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java
new file mode 100644
index 0000000000..2a370afe85
--- /dev/null
+++ b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckFilter.java
@@ -0,0 +1,46 @@
+package com.baeldung.user.check;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.annotation.WebFilter;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebFilter("/user-check/*")
+public class UserCheckFilter implements Filter {
+ public static void forward(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
+ request.getRequestDispatcher("/WEB-INF/user.check" + page)
+ .forward(request, response);
+ }
+
+ @Override
+ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
+ if (!(req instanceof HttpServletRequest)) {
+ throw new ServletException("Can only process HttpServletRequest");
+ }
+
+ if (!(res instanceof HttpServletResponse)) {
+ throw new ServletException("Can only process HttpServletResponse");
+ }
+
+ HttpServletRequest request = (HttpServletRequest) req;
+ HttpServletResponse response = (HttpServletResponse) res;
+
+ request.setAttribute("origin", request.getRequestURI());
+
+ if (!request.getRequestURI()
+ .contains("login") && request.getSession(false) == null) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ forward(request, response, "/login.jsp");
+ // we return here so the original servlet is not processed
+ return;
+ }
+
+ chain.doFilter(request, response);
+ }
+}
diff --git a/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java
new file mode 100644
index 0000000000..e1a38fc7b8
--- /dev/null
+++ b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLoginServlet.java
@@ -0,0 +1,56 @@
+package com.baeldung.user.check;
+
+import java.io.IOException;
+import java.util.Date;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+@WebServlet("/user-check/login")
+public class UserCheckLoginServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ if (request.getSession(false) != null) {
+ response.sendRedirect(request.getContextPath() + "/user-check/home");
+ return;
+ }
+
+ String referer = (String) request.getAttribute("origin");
+ request.setAttribute("origin", referer);
+ UserCheckFilter.forward(request, response, "/login.jsp");
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ String key = request.getParameter("name");
+ String pass = request.getParameter("password");
+
+ User user = User.DB.get(key);
+ if (user == null || !user.getPassword()
+ .equals(pass)) {
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ request.setAttribute("origin", request.getParameter("origin"));
+ request.setAttribute("error", "invalid login");
+ UserCheckFilter.forward(request, response, "/login.jsp");
+ return;
+ }
+
+ user.getLogins()
+ .add(new Date());
+
+ HttpSession session = request.getSession();
+ session.setAttribute("user", user);
+
+ String origin = request.getParameter("origin");
+ if (origin == null || origin.contains("login"))
+ origin = "./";
+
+ response.sendRedirect(origin);
+ }
+}
diff --git a/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java
new file mode 100644
index 0000000000..42c0bb87ab
--- /dev/null
+++ b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckLogoutServlet.java
@@ -0,0 +1,26 @@
+package com.baeldung.user.check;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+@WebServlet("/user-check/logout")
+public class UserCheckLogoutServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ HttpSession session = request.getSession(false);
+ if (session != null) {
+ session.invalidate();
+ }
+
+ request.setAttribute("loggedOut", true);
+ response.sendRedirect("./");
+ }
+}
diff --git a/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java
new file mode 100644
index 0000000000..d7d5d1e762
--- /dev/null
+++ b/javax-servlets-2/src/main/java/com/baeldung/user/check/UserCheckServlet.java
@@ -0,0 +1,28 @@
+package com.baeldung.user.check;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+@WebServlet(name = "home", urlPatterns = { "/user-check/", "/user-check", "/user-check/home" })
+public class UserCheckServlet extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ HttpSession session = request.getSession(false);
+ if (session == null || session.getAttribute("user") == null) {
+ throw new IllegalStateException("user not logged in");
+ }
+
+ User user = (User) session.getAttribute("user");
+ request.setAttribute("user", user);
+
+ UserCheckFilter.forward(request, response, "/home.jsp");
+ }
+}
diff --git a/javax-servlets-2/src/main/resources/logback.xml b/javax-servlets-2/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/javax-servlets-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/javax-servlets-2/src/main/webapp/WEB-INF/user.check/home.jsp b/javax-servlets-2/src/main/webapp/WEB-INF/user.check/home.jsp
new file mode 100644
index 0000000000..4e17763552
--- /dev/null
+++ b/javax-servlets-2/src/main/webapp/WEB-INF/user.check/home.jsp
@@ -0,0 +1,31 @@
+<%@ page contentType="text/html;charset=UTF-8" session="false"%>
+<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
+
+
+
+ login success - current session info
+
+
+
+ user info
+
+ name: ${user.name}
+
+
+
+
+
+
+
+
diff --git a/javax-servlets-2/src/main/webapp/WEB-INF/user.check/login.jsp b/javax-servlets-2/src/main/webapp/WEB-INF/user.check/login.jsp
new file mode 100644
index 0000000000..19a857585d
--- /dev/null
+++ b/javax-servlets-2/src/main/webapp/WEB-INF/user.check/login.jsp
@@ -0,0 +1,33 @@
+<%@ page contentType="text/html;charset=UTF-8" session="false"%>
+<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
+
+
+
+ login
+
+
+
+
+
diff --git a/javax-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java b/javax-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java
new file mode 100644
index 0000000000..42858d61e7
--- /dev/null
+++ b/javax-servlets-2/src/test/java/com/baeldung/user/check/UserCheckServletLiveTest.java
@@ -0,0 +1,98 @@
+package com.baeldung.user.check;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.LaxRedirectStrategy;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class UserCheckServletLiveTest {
+ private static final String BASE_URL = "http://localhost:8080/javax-servlets-2/user-check";
+
+ @Mock
+ HttpServletRequest request;
+
+ @Mock
+ HttpServletResponse response;
+
+ private CloseableHttpClient buildClient() {
+ return HttpClientBuilder.create()
+ .setRedirectStrategy(new LaxRedirectStrategy())
+ .build();
+ }
+
+ @Test
+ public void whenCorrectCredentials_thenLoginSucceeds() throws Exception {
+ try (CloseableHttpClient client = buildClient()) {
+ HttpPost post = new HttpPost(BASE_URL + "/login");
+
+ List form = new ArrayList<>();
+ form.add(new BasicNameValuePair("name", "admin"));
+ form.add(new BasicNameValuePair("password", "password"));
+
+ post.setEntity(new UrlEncodedFormEntity(form));
+ try (CloseableHttpResponse response = client.execute(post)) {
+ String body = EntityUtils.toString(response.getEntity());
+
+ assertTrue(response.getStatusLine()
+ .getStatusCode() == 200);
+
+ assertTrue(body.contains("login success"));
+ }
+ }
+ }
+
+ @Test
+ public void whenIncorrectCredentials_thenLoginFails() throws Exception {
+ try (CloseableHttpClient client = buildClient()) {
+ HttpPost post = new HttpPost(BASE_URL + "/login");
+
+ List form = new ArrayList<>();
+ form.add(new BasicNameValuePair("name", "admin"));
+ form.add(new BasicNameValuePair("password", "invalid"));
+
+ post.setEntity(new UrlEncodedFormEntity(form));
+ try (CloseableHttpResponse response = client.execute(post)) {
+ String body = EntityUtils.toString(response.getEntity());
+
+ assertTrue(response.getStatusLine()
+ .getStatusCode() == 401);
+
+ assertTrue(body.contains("invalid login"));
+ }
+ }
+ }
+
+ @Test
+ public void whenNotLoggedIn_thenRedirectedToLoginPage() throws Exception {
+ try (CloseableHttpClient client = buildClient()) {
+ HttpGet get = new HttpGet(BASE_URL + "/home");
+
+ try (CloseableHttpResponse response = client.execute(get)) {
+ String body = EntityUtils.toString(response.getEntity());
+
+ assertTrue(response.getStatusLine()
+ .getStatusCode() == 401);
+
+ assertTrue(body.contains("redirected to login"));
+ }
+ }
+ }
+}
diff --git a/pom.xml b/pom.xml
index 99217774e9..cab9a34f02 100644
--- a/pom.xml
+++ b/pom.xml
@@ -459,6 +459,7 @@
java-vavr-stream
java-websocket
javax-servlets
+ javax-servlets-2
javaxval
jaxb
jee-7
@@ -943,6 +944,7 @@
java-vavr-stream
java-websocket
javax-servlets
+ javax-servlets-2
javaxval
jaxb
jee-7
From f4d7c9a0ea1272f7998130628b08d00a3ef745cf Mon Sep 17 00:00:00 2001
From: mladensavic94
Date: Fri, 25 Feb 2022 09:54:42 +0100
Subject: [PATCH 169/235] Caching Maven Dependencies with Docker - fix
---
.../src/main/java/com/baeldung/maven_caching/CoreClass.java | 4 ++--
docker/docker-caching/multi-module-caching/pom.xml | 3 +--
.../java/com/baeldung/maven_caching/MavenCachingMain.java | 2 +-
3 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java b/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
index 7d57110d72..d8c73a331a 100644
--- a/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
+++ b/docker/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
@@ -4,11 +4,11 @@ import com.google.common.io.Files;
public class CoreClass {
- public String method(){
+ public String method() {
return "Hello from core module!!";
}
- public String dependencyMethod(){
+ public String dependencyMethod() {
return Files.simplifyPath("/home/app/test");
}
}
diff --git a/docker/docker-caching/multi-module-caching/pom.xml b/docker/docker-caching/multi-module-caching/pom.xml
index c5a7d9ec6f..7968114385 100644
--- a/docker/docker-caching/multi-module-caching/pom.xml
+++ b/docker/docker-caching/multi-module-caching/pom.xml
@@ -5,8 +5,7 @@
com.baeldung
multi-module-caching
0.0.1-SNAPSHOT
- maven-caching
- maven-caching
+ Multi-module Maven caching example
pom
diff --git a/docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java b/docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
index 81673fd9ac..4fbd8e5311 100644
--- a/docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
+++ b/docker/docker-caching/single-module-caching/src/main/java/com/baeldung/maven_caching/MavenCachingMain.java
@@ -5,7 +5,7 @@ import com.google.common.io.Files;
public class MavenCachingMain {
public static void main(String[] args) {
- System.out.println("Hello from maven_caching app!!!");
+ System.out.println("Hello from maven_caching app!!!");
System.out.println(Files.simplifyPath("/home/app/test"));
}
}
From 12c25ba2e3a2903fe779001bdf7ef51b2709acf4 Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Fri, 25 Feb 2022 15:47:15 +0530
Subject: [PATCH 170/235] JAVA-10307:Fix Table ITEM not found issue
---
.../src/main/resources/{import.sql => import-db.sql} | 0
.../spring-hibernate-5/src/test/resources/criteria.cfg.xml | 1 +
.../src/test/resources/{import.sql => import-db.sql} | 0
3 files changed, 1 insertion(+)
rename persistence-modules/spring-hibernate-5/src/main/resources/{import.sql => import-db.sql} (100%)
rename persistence-modules/spring-hibernate-5/src/test/resources/{import.sql => import-db.sql} (100%)
diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/import.sql b/persistence-modules/spring-hibernate-5/src/main/resources/import-db.sql
similarity index 100%
rename from persistence-modules/spring-hibernate-5/src/main/resources/import.sql
rename to persistence-modules/spring-hibernate-5/src/main/resources/import-db.sql
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
index bc4fed9680..9ca9836a70 100644
--- a/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
+++ b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml
@@ -11,6 +11,7 @@
org.hibernate.dialect.H2Dialect
create-drop
+ import-db.sql
false
diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import-db.sql
similarity index 100%
rename from persistence-modules/spring-hibernate-5/src/test/resources/import.sql
rename to persistence-modules/spring-hibernate-5/src/test/resources/import-db.sql
From de6d367e413f3ec302ac19030030e20c11fabe06 Mon Sep 17 00:00:00 2001
From: sanitaso
Date: Fri, 25 Feb 2022 12:54:20 +0100
Subject: [PATCH 171/235] add files to springdoc
---
.../swaggerResponseAPI/.gitignore | 33 ++++++++
.../swaggerResponseAPI/pom.xml | 69 +++++++++++++++++
.../SwaggerResponseApiApplication.java | 13 ++++
.../controller/ProductController.java | 39 ++++++++++
.../swaggerresponseapi/model/Product.java | 15 ++++
.../service/ProductService.java | 21 +++++
.../src/main/resources/application.properties | 1 +
.../ProductIntegrationTest.java | 76 +++++++++++++++++++
.../SwaggerResponseApiApplicationTests.java | 13 ++++
9 files changed, 280 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
new file mode 100644
index 0000000000..f60f3beecd
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
@@ -0,0 +1,33 @@
+HELP.md
+target/
+.mvn/wrapper/
+!**/src/main/**/target/
+!**/src/test/**/target/
+mvnv*
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
new file mode 100644
index 0000000000..17544290e4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
@@ -0,0 +1,69 @@
+
+
+ 4.0.0
+
+ com.baeldung.spring-boot-modules
+ spring-boot-disable-logging
+ 1.0.0-SNAPSHOT
+
+ com.baeldung
+ swaggerResponseAPI
+ 0.0.1-SNAPSHOT
+ swaggerResponseAPI
+ swaggerResponseAPI
+
+ 11
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springdoc
+ springdoc-openapi-ui
+ 1.6.6
+
+
+ junit
+ junit
+ 4.13.2
+ test
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ 2.13.0
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.projectlombok
+ lombok
+
+
+
+
+
+
+
+
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
new file mode 100644
index 0000000000..913544b459
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerresponseapi;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SwaggerResponseApiApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SwaggerResponseApiApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
new file mode 100644
index 0000000000..3e9a3291d9
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
@@ -0,0 +1,39 @@
+package com.baeldung.swaggerresponseapi.controller;
+
+import com.baeldung.swaggerresponseapi.model.Product;
+import com.baeldung.swaggerresponseapi.service.ProductService;
+
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.responses.ApiResponses;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+
+@RestController
+public class ProductController {
+ private final ProductService productService;
+
+ public ProductController(ProductService productService) {
+ this.productService = productService;
+ }
+
+ @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Product successfully added!") })
+ @PostMapping("/create")
+ public Product addProduct(@RequestBody Product product) {
+ return productService.addProducts(product);
+ }
+
+ @ApiResponses(value = { @ApiResponse(content = { @Content(mediaType = "application/json",
+ array = @ArraySchema(schema = @Schema(implementation = Product.class))) }) })
+ @GetMapping("/products")
+ public List getProductsList() {
+ return productService.getProductsList();
+ }
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
new file mode 100644
index 0000000000..0a100582fc
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
@@ -0,0 +1,15 @@
+package com.baeldung.swaggerresponseapi.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@Getter
+@Setter
+@AllArgsConstructor
+@NoArgsConstructor
+public class Product {
+ String code;
+ String name;
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
new file mode 100644
index 0000000000..5e7533d6f4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
@@ -0,0 +1,21 @@
+package com.baeldung.swaggerresponseapi.service;
+
+import com.baeldung.swaggerresponseapi.model.Product;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+public class ProductService {
+ List productsList = new ArrayList<>();
+
+ public Product addProducts(Product product) {
+ productsList.add(product);
+ return product;
+ }
+
+ public List getProductsList() {
+ return productsList;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
new file mode 100644
index 0000000000..ef6a8953e2
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
@@ -0,0 +1,76 @@
+package com.baeldung.swaggerresponseapi;
+
+import com.baeldung.swaggerresponseapi.controller.ProductController;
+import com.baeldung.swaggerresponseapi.model.Product;
+import com.baeldung.swaggerresponseapi.service.ProductService;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+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.result.MockMvcResultMatchers;
+
+import java.util.Arrays;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.reset;
+import static org.hamcrest.CoreMatchers.is;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(ProductController.class)
+public class ProductIntegrationTest {
+
+ @Autowired
+ MockMvc mock;
+
+ @MockBean
+ private ProductService productService;
+
+ @Test
+ public void givenProduct_whenAddNewProduct_thenReturnValidStatusCode() throws Exception {
+ Product product = new Product("1001", "Milk");
+ given(productService.addProducts(any(Product.class))).willReturn(product);
+
+ mock.perform(post("/create").contentType(MediaType.APPLICATION_JSON)
+ .content(toJsonString(product)))
+ .andDo(print())
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.code").value("1001"));
+
+ reset(productService);
+ }
+
+ @Test
+ public void givenProductsList_whenGetAllProducts_thenReturnValidProducts() throws Exception {
+ Product product1 = new Product("1001", "Milk");
+ Product product2 = new Product("2002", "Butter");
+
+ given(productService.getProductsList()).willReturn(Arrays.asList(product1, product2));
+
+ mock.perform(get("/products").contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andDo(print())
+ .andExpect(jsonPath("$[0].code", is(product1.getCode())))
+ .andExpect(jsonPath("$[1].name", is(product2.getName())));
+
+ reset(productService);
+ }
+
+ public String toJsonString(Product product) throws JsonProcessingException {
+ ObjectMapper om = new ObjectMapper();
+ String json = om.writeValueAsString(product);
+ return json;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
new file mode 100644
index 0000000000..9e8c6ee0fa
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerresponseapi;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class SwaggerResponseApiApplicationTests {
+
+ @Test
+ void contextLoads() {
+ }
+
+}
From f62de535543e8f04bfaa073ae2eaf185492fd0cd Mon Sep 17 00:00:00 2001
From: sanitaso
Date: Fri, 25 Feb 2022 15:25:38 +0100
Subject: [PATCH 172/235] modify pom
---
.../spring-boot-springdoc/swaggerResponseAPI/pom.xml | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
index 17544290e4..c168248df2 100644
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
+++ b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
@@ -3,9 +3,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung.spring-boot-modules
- spring-boot-disable-logging
- 1.0.0-SNAPSHOT
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.6.3
+
com.baeldung
swaggerResponseAPI
From 6aa40fd5fbc9f713e763dea82f9832203dc71e49 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 25 Feb 2022 20:43:35 +0000
Subject: [PATCH 173/235] [JAVA-10127] Update commented out modules in pom
---
pom.xml | 32 ++++++++++++++++----------------
1 file changed, 16 insertions(+), 16 deletions(-)
diff --git a/pom.xml b/pom.xml
index 99217774e9..e55743990a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -400,7 +400,6 @@
dagger
data-structures
ddd
-
deeplearning4j
discord4j
disruptor
@@ -432,7 +431,6 @@
hazelcast
helidon
httpclient
-
httpclient-simple
hystrix
@@ -482,8 +480,8 @@
kubernetes
ksqldb
- language-interop
- libraries-2
+ language-interop
+ libraries-2
libraries-3
libraries-apache-commons
libraries-apache-commons-collections
@@ -519,12 +517,12 @@
micronaut
microprofile
msf4j
-
+
mustache
mybatis
netflix-modules
-
+ netty
ninja
open-liberty
@@ -885,7 +883,6 @@
dagger
data-structures
ddd
-
deeplearning4j
discord4j
disruptor
@@ -916,7 +913,6 @@
hazelcast
helidon
httpclient
-
httpclient-simple
hystrix
@@ -1003,12 +999,12 @@
micronaut
microprofile
msf4j
-
+
mustache
mybatis
netflix-modules
-
+ netty
ninja
open-liberty
@@ -1198,7 +1194,6 @@
wildfly
xml
xstream
-
@@ -1339,12 +1334,15 @@
core-java-modules/core-java-time-measurements
core-java-modules/core-java-networking-3
core-java-modules/multimodulemavenproject
+ ddd-modules
+ httpclient-2
+ libraries-concurrency
persistence-modules/sirix
persistence-modules/spring-data-cassandra-2
quarkus-vs-springboot
quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-camel
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
testing-modules/testing-assertions
@@ -1397,12 +1395,15 @@
core-java-modules/core-java-networking-3
core-java-modules/multimodulemavenproject
core-java-modules/core-java-strings
+ ddd-modules
+ httpclient-2
+ libraries-concurrency
persistence-modules/sirix
persistence-modules/spring-data-cassandra-2
quarkus-vs-springboot
quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-camel
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
testing-modules/testing-assertions
@@ -1470,7 +1471,6 @@
0.0.1
3.12.2
3.0.0
-
3.13.0
1.18.20
1.4.200
From e65fe9db25acc832bc07af7057aeb9034b7be7b2 Mon Sep 17 00:00:00 2001
From: Elmar Mammadov
Date: Sat, 26 Feb 2022 05:24:07 +0100
Subject: [PATCH 174/235] BAEL-5350: Java - How to create new Entry (key,
value) (#11817)
* BAEL-5350:
1. Added example usage of creating entries with Java itself
2. Added example usage of creating entries with Apache commons collecttions & Guava
3. Custom entry class and its usages
* BAEL-5350:
1. Created unit tests
* BAEL-5350:
1. simplifed assertion for java 9 entry creation
* BAEL-5350:
1. moved into core-java-collections-maps-4 module
2. updated custom entry class and its unit test
---
.../core-java-collections-maps-4/pom.xml | 25 +++-
.../entries/SimpleCustomKeyValue.java | 53 ++++++++
.../entries/EntriesExampleUnitTest.java | 113 ++++++++++++++++++
.../entries/SimpleCustomKeyValueUnitTest.java | 31 +++++
core-java-modules/pom.xml | 1 -
pom.xml | 2 +
6 files changed, 222 insertions(+), 3 deletions(-)
create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/entries/SimpleCustomKeyValue.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/EntriesExampleUnitTest.java
create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/SimpleCustomKeyValueUnitTest.java
diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml
index be467dd57b..e5afd87bbe 100644
--- a/core-java-modules/core-java-collections-maps-4/pom.xml
+++ b/core-java-modules/core-java-collections-maps-4/pom.xml
@@ -15,6 +15,16 @@
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
junit
junit
@@ -37,12 +47,23 @@
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
UTF-8
- 1.8
- 1.8
+ 1.9
+ 1.9
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/entries/SimpleCustomKeyValue.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/entries/SimpleCustomKeyValue.java
new file mode 100644
index 0000000000..b2925cd508
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/entries/SimpleCustomKeyValue.java
@@ -0,0 +1,53 @@
+package com.baeldung.entries;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.StringJoiner;
+
+public class SimpleCustomKeyValue implements Map.Entry {
+
+ private final K key;
+ private V value;
+
+ public SimpleCustomKeyValue(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ @Override
+ public K getKey() {
+ return key;
+ }
+
+ @Override
+ public V getValue() {
+ return value;
+ }
+
+ @Override
+ public V setValue(V value) {
+ return this.value = value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ SimpleCustomKeyValue, ?> that = (SimpleCustomKeyValue, ?>) o;
+ return Objects.equals(key, that.key) && Objects.equals(value, that.value);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(key, value);
+ }
+
+ @Override
+ public String toString() {
+ return new StringJoiner(", ", SimpleCustomKeyValue.class.getSimpleName() + "[", "]").add("key=" + key).add("value=" + value).toString();
+ }
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/EntriesExampleUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/EntriesExampleUnitTest.java
new file mode 100644
index 0000000000..954a4a4f22
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/EntriesExampleUnitTest.java
@@ -0,0 +1,113 @@
+package com.baeldung.entries;
+
+import com.google.common.collect.Maps;
+import org.apache.commons.collections4.KeyValue;
+import org.apache.commons.collections4.keyvalue.DefaultMapEntry;
+import org.apache.commons.collections4.keyvalue.UnmodifiableMapEntry;
+import org.junit.jupiter.api.Test;
+
+import java.util.AbstractMap;
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
+
+public class EntriesExampleUnitTest {
+
+ @Test
+ public void givenEntries_whenVerifying_thenShouldContainKeyValues() {
+ AbstractMap.SimpleEntry firstEntry = new AbstractMap.SimpleEntry<>("key1", "value1");
+ AbstractMap.SimpleEntry secondEntry = new AbstractMap.SimpleEntry<>("key2", "value2");
+ AbstractMap.SimpleEntry thirdEntry = new AbstractMap.SimpleEntry<>(firstEntry);
+ thirdEntry.setValue("a different value");
+
+ assertThat(Stream.of(firstEntry, secondEntry, thirdEntry))
+ .extracting("key", "value")
+ .containsExactly(
+ tuple("key1", "value1"),
+ tuple("key2", "value2"),
+ tuple("key1", "a different value"));
+ }
+
+ @Test
+ public void givenImmutableEntries_whenVerifying_thenShouldContainKeyValues() {
+ AbstractMap.SimpleImmutableEntry firstEntry = new AbstractMap.SimpleImmutableEntry<>("key1", "value1");
+ AbstractMap.SimpleImmutableEntry secondEntry = new AbstractMap.SimpleImmutableEntry<>("key2", "value2");
+ AbstractMap.SimpleImmutableEntry thirdEntry = new AbstractMap.SimpleImmutableEntry<>(firstEntry);
+
+ assertThat(Stream.of(firstEntry, secondEntry, thirdEntry))
+ .extracting("key", "value")
+ .containsExactly(
+ tuple("key1", "value1"),
+ tuple("key2", "value2"),
+ tuple("key1", "value1"));
+ }
+
+ @Test
+ public void givenImmutableEntryUsingJava9_whenVerifying_thenShouldContainKeyValues() {
+ Map.Entry entry = Map.entry("key", "value");
+
+ assertThat(entry.getKey())
+ .isEqualTo("key");
+ assertThat(entry.getValue())
+ .isEqualTo("value");
+ }
+
+
+ @Test
+ public void givenEntriesWithApacheCommons_whenVerifying_thenShouldContainKeyValues() {
+ Map.Entry firstEntry = new DefaultMapEntry<>("key1", "value1");
+ KeyValue secondEntry = new DefaultMapEntry<>("key2", "value2");
+
+ KeyValue thirdEntry = new DefaultMapEntry<>(firstEntry);
+ KeyValue fourthEntry = new DefaultMapEntry<>(secondEntry);
+
+ firstEntry.setValue("a different value");
+
+ assertThat(firstEntry)
+ .extracting("key", "value")
+ .containsExactly("key1", "a different value");
+
+ assertThat(Stream.of(secondEntry, thirdEntry, fourthEntry))
+ .extracting("key", "value")
+ .containsExactly(
+ tuple("key2", "value2"),
+ tuple("key1", "value1"),
+ tuple("key2", "value2"));
+ }
+
+ @Test
+ public void givenImmutableEntriesWithApacheCommons_whenVerifying_thenShouldContainKeyValues() {
+ Map.Entry firstEntry = new UnmodifiableMapEntry<>("key1", "value1");
+ KeyValue secondEntry = new UnmodifiableMapEntry<>("key2", "value2");
+
+ KeyValue thirdEntry = new UnmodifiableMapEntry<>(firstEntry);
+ KeyValue fourthEntry = new UnmodifiableMapEntry<>(secondEntry);
+
+ assertThat(firstEntry)
+ .extracting("key", "value")
+ .containsExactly("key1", "value1");
+
+ assertThat(Stream.of(secondEntry, thirdEntry, fourthEntry))
+ .extracting("key", "value")
+ .containsExactly(
+ tuple("key2", "value2"),
+ tuple("key1", "value1"),
+ tuple("key2", "value2"));
+ }
+
+
+ @Test
+ public void givenImmutableEntriesWithGuava_whenVerifying_thenShouldContainKeyValues() {
+ Map.Entry firstEntry = Maps.immutableEntry("key1", "value1");
+ Map.Entry secondEntry = Maps.immutableEntry("key2", "value2");
+
+ assertThat(Stream.of(firstEntry, secondEntry))
+ .extracting("key", "value")
+ .containsExactly(
+ tuple("key1", "value1"),
+ tuple("key2", "value2"));
+ }
+
+}
diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/SimpleCustomKeyValueUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/SimpleCustomKeyValueUnitTest.java
new file mode 100644
index 0000000000..d055bb1653
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/entries/SimpleCustomKeyValueUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.entries;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
+
+class SimpleCustomKeyValueUnitTest {
+
+
+ @Test
+ public void givenModifiableEntries_whenVerifying_thenShouldContainKeyValues() {
+ Map.Entry firstEntry = new SimpleCustomKeyValue<>("key1", "value1");
+
+ Map.Entry secondEntry = new SimpleCustomKeyValue<>("key2", "value2");
+ secondEntry.setValue("different value");
+
+ Map map = Map.ofEntries(firstEntry, secondEntry);
+
+ assertThat(map)
+ .isEqualTo(ImmutableMap.builder()
+ .put("key1", "value1")
+ .put("key2", "different value")
+ .build());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index a25cf11454..60319b4de4 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -38,7 +38,6 @@
core-java-collections-maps
core-java-collections-maps-2
core-java-collections-maps-3
- core-java-collections-maps-4
core-java-concurrency-2
core-java-concurrency-advanced
core-java-concurrency-advanced-2
diff --git a/pom.xml b/pom.xml
index cab9a34f02..3138b5c610 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1329,6 +1329,7 @@
core-java-modules/core-java-collections-set
+ core-java-modules/core-java-collections-maps-4
core-java-modules/core-java-date-operations-1
core-java-modules/core-java-datetime-conversion
core-java-modules/core-java-datetime-string
@@ -1387,6 +1388,7 @@
core-java-modules/core-java-collections-set
+ core-java-modules/core-java-collections-maps-4
core-java-modules/core-java-date-operations-1
core-java-modules/core-java-datetime-conversion
core-java-modules/core-java-datetime-string
From 768e9ae3877175cee1d12f3eb1de71fe81eddf41 Mon Sep 17 00:00:00 2001
From: Sameer
Date: Sat, 26 Feb 2022 17:25:31 +0530
Subject: [PATCH 175/235] Maven Classifier (#11833)
* maven classifier
* static imports
* bumped up plugin versions
Co-authored-by: s9m33r
---
.../maven-classifier-example-consumer/pom.xml | 53 ++++++++
.../classifier/consumer/FuelStation.java | 17 +++
.../consumer/FuelStationUnitTest.java | 21 +++
.../maven-classifier-example-provider/pom.xml | 122 ++++++++++++++++++
.../provider/factory/CarFactory.java | 14 ++
.../classifier/provider/model/Car.java | 26 ++++
.../provider/model/PowerSource.java | 5 +
.../provider/factory/CarFactoryUnitTest.java | 32 +++++
.../classifier/provider/stub/CarStub.java | 17 +++
maven-modules/maven-classifier/pom.xml | 27 ++++
maven-modules/pom.xml | 1 +
11 files changed, 335 insertions(+)
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-consumer/src/main/java/com/baeldung/maven/classifier/consumer/FuelStation.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-consumer/src/test/java/com/baeldung/maven/classifier/consumer/FuelStationUnitTest.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactory.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/Car.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/PowerSource.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactoryUnitTest.java
create mode 100644 maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/stub/CarStub.java
create mode 100644 maven-modules/maven-classifier/pom.xml
diff --git a/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
new file mode 100644
index 0000000000..cbf046ed5a
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
@@ -0,0 +1,53 @@
+
+
+
+ maven-classifier
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+
+ 4.0.0
+
+ maven-classifier-example-consumer
+
+
+ 8
+ 8
+
+
+
+
+ com.baeldung
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
+
+
+ com.baeldung
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
+ arbitrary
+
+
+
+
+
+
+
+
+
+ com.baeldung
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
+ sources
+
+
+ com.baeldung
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
+ tests
+
+
+
+
diff --git a/maven-modules/maven-classifier/maven-classifier-example-consumer/src/main/java/com/baeldung/maven/classifier/consumer/FuelStation.java b/maven-modules/maven-classifier/maven-classifier-example-consumer/src/main/java/com/baeldung/maven/classifier/consumer/FuelStation.java
new file mode 100644
index 0000000000..cf5dc03457
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-consumer/src/main/java/com/baeldung/maven/classifier/consumer/FuelStation.java
@@ -0,0 +1,17 @@
+
+package com.baeldung.maven.classifier.consumer;
+
+import com.baeldung.maven.dependency.classifier.provider.model.Car;
+import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
+
+public class FuelStation {
+
+ public FuelStation.Zone refill(Car car) {
+ return PowerSource.BATTERY.equals(car.getPowerSource()) ? FuelStation.Zone.BATTERY : FuelStation.Zone.UNKNOWN;
+ }
+
+ public enum Zone {
+ BATTERY,
+ UNKNOWN
+ }
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-consumer/src/test/java/com/baeldung/maven/classifier/consumer/FuelStationUnitTest.java b/maven-modules/maven-classifier/maven-classifier-example-consumer/src/test/java/com/baeldung/maven/classifier/consumer/FuelStationUnitTest.java
new file mode 100644
index 0000000000..e04afb8276
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-consumer/src/test/java/com/baeldung/maven/classifier/consumer/FuelStationUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.maven.classifier.consumer;
+
+import com.baeldung.maven.classifier.consumer.FuelStation.Zone;
+import com.baeldung.maven.dependency.classifier.provider.model.Car;
+import com.baeldung.maven.dependency.classifier.provider.stub.CarStub;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class FuelStationUnitTest {
+
+ @Test
+ @DisplayName("Given fuel type battery When request for refill Then Return Battery Zone")
+ public void givenFuelTypeBattery_whenRequestToRefill_thenReturnBatteryZone() {
+ FuelStation fuelStation = new FuelStation();
+ Car electricCar = CarStub.ELECTRIC_CAR;
+
+ assertEquals(Zone.BATTERY, fuelStation.refill(electricCar));
+ }
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml b/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
new file mode 100644
index 0000000000..12cb4fa1a2
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
@@ -0,0 +1,122 @@
+
+
+
+ 4.0.0
+
+
+ maven-classifier
+ com.baeldung
+ 0.0.1-SNAPSHOT
+
+
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
+
+
+ 8
+ 8
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.10.0
+
+
+ JDK 8
+ compile
+
+ compile
+
+
+ 8
+ 8
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 3.2.2
+
+
+ Arbitrary
+
+ jar
+
+
+ arbitrary
+
+
+
+ Test Jar
+
+ test-jar
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 3.2.1
+
+
+ attach-sources
+ verify
+
+ jar-no-fork
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 3.3.2
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+
+
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactory.java b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactory.java
new file mode 100644
index 0000000000..285fec9ddc
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactory.java
@@ -0,0 +1,14 @@
+package com.baeldung.maven.dependency.classifier.provider.factory;
+
+import com.baeldung.maven.dependency.classifier.provider.model.Car;
+import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
+
+public class CarFactory {
+
+ public static Car manufacture(Type carType) {
+ Car car = new Car();
+ car.setType(carType);
+
+ return car;
+ }
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/Car.java b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/Car.java
new file mode 100644
index 0000000000..93d5091f55
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/Car.java
@@ -0,0 +1,26 @@
+package com.baeldung.maven.dependency.classifier.provider.model;
+
+public class Car {
+ private Type type;
+ private PowerSource fuelType;
+
+ public Type getType() {
+ return this.type;
+ }
+
+ public void setType(Type carType) {
+ this.type = carType;
+ }
+
+ public PowerSource getPowerSource() {
+ return this.fuelType;
+ }
+
+ public void setFuelType(PowerSource fuelType) {
+ this.fuelType = fuelType;
+ }
+
+ public enum Type {
+ ELECTRIC
+ }
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/PowerSource.java b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/PowerSource.java
new file mode 100644
index 0000000000..3ac5d98efe
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/src/main/java/com/baeldung/maven/dependency/classifier/provider/model/PowerSource.java
@@ -0,0 +1,5 @@
+package com.baeldung.maven.dependency.classifier.provider.model;
+
+public enum PowerSource {
+ BATTERY
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactoryUnitTest.java b/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactoryUnitTest.java
new file mode 100644
index 0000000000..36f0b36f1c
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/factory/CarFactoryUnitTest.java
@@ -0,0 +1,32 @@
+
+package com.baeldung.maven.dependency.classifier.provider.factory;
+
+import com.baeldung.maven.dependency.classifier.provider.model.Car;
+import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
+import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
+import com.baeldung.maven.dependency.classifier.provider.stub.CarStub;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+class CarFactoryUnitTest {
+
+ @Test
+ @DisplayName("Given Car type When CarFactory manufacture is called Then create a Car of the given type")
+ public void givenCarType_whenCarFactoryManufactureCalled_thenCreateCarOfGivenType() {
+ Car car = CarFactory.manufacture(Type.ELECTRIC);
+
+ assertNotNull(car, "CarFactory didn't manufacture a car. Car is null");
+ assertEquals(Type.ELECTRIC, car.getType());
+ }
+
+ @Test
+ @DisplayName("Given an electric car When asked for fuel type Then return Battery")
+ public void givenElectricCar_whenAskedForFuelType_thenReturnBattery() {
+ Car car = CarStub.ELECTRIC_CAR;
+
+ assertEquals(PowerSource.BATTERY, car.getPowerSource());
+ }
+}
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/stub/CarStub.java b/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/stub/CarStub.java
new file mode 100644
index 0000000000..54dbd1166f
--- /dev/null
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/src/test/java/com/baeldung/maven/dependency/classifier/provider/stub/CarStub.java
@@ -0,0 +1,17 @@
+package com.baeldung.maven.dependency.classifier.provider.stub;
+
+import com.baeldung.maven.dependency.classifier.provider.model.Car;
+import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
+import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
+import org.mockito.Mockito;
+
+import static org.mockito.Mockito.when;
+
+public class CarStub {
+ public static Car ELECTRIC_CAR = Mockito.mock(Car.class);
+
+ static {
+ when(ELECTRIC_CAR.getType()).thenReturn(Type.ELECTRIC);
+ when(ELECTRIC_CAR.getPowerSource()).thenReturn(PowerSource.BATTERY);
+ }
+}
diff --git a/maven-modules/maven-classifier/pom.xml b/maven-modules/maven-classifier/pom.xml
new file mode 100644
index 0000000000..6b75f60893
--- /dev/null
+++ b/maven-modules/maven-classifier/pom.xml
@@ -0,0 +1,27 @@
+
+
+ 4.0.0
+
+ maven-classifier
+ pom
+ 0.0.1-SNAPSHOT
+
+
+ maven-classifier-example-consumer
+ maven-classifier-example-provider
+
+
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ 8
+ 8
+
+
+
diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml
index 21bc0e72e1..37be581804 100644
--- a/maven-modules/pom.xml
+++ b/maven-modules/pom.xml
@@ -36,6 +36,7 @@
maven-surefire-plugin
maven-parent-pom-resolution
maven-simple
+ maven-classifier
From eae57f5496a6e56d73393f295fcc6955d0a65273 Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Mon, 28 Feb 2022 01:51:17 +0530
Subject: [PATCH 176/235] BAEL-5359: Updating Multiple Fields in a MongoDB
Document (#11861)
* BAEL-5359: Updating Multiple Fields in a MongoDB Document
* BAEL-5359: Add test class file
* BAEL-5359: Rename UpdateMultipleFieldsUnitTest.java to UpdateMultipleFieldsLiveTest.java
---
.../mongo/update/MultipleFieldsExample.java | 44 ++++++++++
.../mongo/update/UpdateMultipleFields.java | 36 +++++++++
.../update/UpdateMultipleFieldsLiveTest.java | 80 +++++++++++++++++++
3 files changed, 160 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
new file mode 100644
index 0000000000..b2fcddeafb
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
@@ -0,0 +1,44 @@
+package com.baeldung.mongo.update;
+
+import org.bson.Document;
+
+import com.mongodb.BasicDBObject;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.result.UpdateResult;
+
+public class MultipleFieldsExample {
+
+ public static void main(String[] args) {
+
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
+
+ MongoClient mongoClient = new MongoClient("localhost", 27017);
+ MongoDatabase database = mongoClient.getDatabase("baeldung");
+ MongoCollection collection = database.getCollection("employee");
+
+ //
+ // Filter on the basis of employee_id
+ //
+
+ BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
+
+ //
+ // Update the fields in Document
+ //
+
+ BasicDBObject updateFields = new BasicDBObject();
+ updateFields.append("department_id", 3);
+ updateFields.append("job", "Sales Manager");
+ BasicDBObject setQuery = new BasicDBObject();
+ setQuery.append("$set", updateFields);
+ UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
+
+ System.out.println("updateResult:- " + updateResult);
+ System.out.println("updateResult:- " + updateResult.getModifiedCount());
+
+ }
+}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
new file mode 100644
index 0000000000..20af6d99cb
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
@@ -0,0 +1,36 @@
+package com.baeldung.mongo.update;
+
+import org.bson.Document;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class UpdateMultipleFields {
+
+ public static void main(String[] args) {
+
+ //
+ // Connect to cluster
+ //
+
+ MongoClient mongoClient = new MongoClient("localhost", 27007);
+ MongoDatabase database = mongoClient.getDatabase("baeldung");
+ MongoCollection collection = database.getCollection("employee");
+
+ //
+ // Update query
+ //
+
+ UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875),
+ Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
+
+ System.out.println("updateResult:- " + updateResult);
+ System.out.println("updateResult:- " + updateResult.getModifiedCount());
+
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
new file mode 100644
index 0000000000..d1538d5312
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.update;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+
+import org.bson.Document;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.mongodb.BasicDBObject;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class UpdateMultipleFieldsLiveTest {
+
+ private MongoClient mongoClient;
+ private MongoDatabase db;
+ private MongoCollection collection;
+
+ @Before
+ public void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ db = mongoClient.getDatabase("baeldung");
+ collection = db.getCollection("employee");
+
+ collection.insertOne(Document.parse(
+ "{'employee_id':794875,'employee_name': 'David smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
+ }
+ }
+
+ @Test
+ public void updateMultipleFieldsUsingDBObject() {
+
+ BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
+ BasicDBObject updateFields = new BasicDBObject();
+ updateFields.append("department_id", 4);
+ updateFields.append("job", "Sales Manager");
+ BasicDBObject setQuery = new BasicDBObject();
+ setQuery.append("$set", updateFields);
+
+ collection.updateMany(searchQuery, setQuery);
+
+ Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
+ assertNotNull(nameDoc);
+ assertFalse(nameDoc.isEmpty());
+
+ String job = nameDoc.get("job", String.class);
+ assertNotNull(job);
+
+ Integer department_id = nameDoc.get("department_id", Integer.class);
+ assertNotNull(department_id);
+
+ }
+
+ @Test
+ public void updateMultipleFieldsUsingDocument() {
+
+ collection.updateMany(Filters.eq("employee_id", 794875),
+ Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
+
+ Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
+ assertNotNull(nameDoc);
+ assertFalse(nameDoc.isEmpty());
+
+ String job = nameDoc.get("job", String.class);
+ assertNotNull(job);
+
+ Integer department_id = nameDoc.get("department_id", Integer.class);
+ assertNotNull(department_id);
+
+ }
+
+}
From e10e20a24be601c031dc677001043f01b075f93a Mon Sep 17 00:00:00 2001
From: Chukwuka Onyekachukwu Victor
Date: Sun, 27 Feb 2022 21:33:39 +0100
Subject: [PATCH 177/235] Added a new Class and few test cases to the
core-java-modules (#11867)
* added a new project: hexagonal architecture
* Added some test cases for the project
* Added a new project to demo the error: variable might not have been initialized
* Added a new Class to the core-java-modules
* Added a New Class to the core-java-module
---
.../VariableMightNotHaveBeenInitialized.java | 45 +++++++++++++++++++
...leMightNotHaveBeenInitializedUnitTest.java | 24 ++++++++++
2 files changed, 69 insertions(+)
create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
create mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
new file mode 100644
index 0000000000..64118e6307
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
@@ -0,0 +1,45 @@
+package com.baeldung.exception.variablemightnothavebeeninitialized;
+
+public class VariableMightNotHaveBeenInitialized {
+
+ private static int instanceVariableCount;
+
+ /**
+ * Method would not compile if lines 14 and 18 are uncommented.
+ */
+ public static void countEven() {
+ //uninstantiated
+ int count;
+ int[] arr = new int[]{23, 56, 89, 12, 23};
+ for (int i = 0; i < arr.length; i++) {
+ if ((arr[i] % 2) == 0) {
+ // count++;
+ }
+
+ }
+ // System.out.println("Total Even Numbers : " + count);
+ }
+
+ public static int countEvenUsingInstanceVariable(int[] arr) {
+
+ for (int i = 0; i < arr.length; i++) {
+ if ((arr[i] % 2) == 0) {
+ instanceVariableCount++;
+ }
+
+ }
+ return instanceVariableCount;
+ }
+
+ public static int countEvenUsingIfElse(int[] arr, int args) {
+ int count;
+ count = args > 0 ? args : 0;
+ for (int i = 0; i < arr.length; i++) {
+ if ((arr[i] % 2) == 0) {
+ count++;
+ }
+
+ }
+ return count;
+ }
+}
diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
new file mode 100644
index 0000000000..c4773d6442
--- /dev/null
+++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.exception.variablemightnothavebeeninitialized;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class VariableMightNotHaveBeenInitializedUnitTest {
+
+ @Test
+ public void usingInstanceVariable_returnCount() {
+ int[] arr = new int[]{1, 2, 3, 4, 5, 6};
+ int value = VariableMightNotHaveBeenInitialized.countEvenUsingInstanceVariable(arr);
+
+ assertEquals(3, value);
+ }
+
+ @Test
+ public void usingArgumentsAndIfElse_returnCount() {
+ int[] arr = new int[]{1, 2, 3, 4, 5, 6};
+ int value = VariableMightNotHaveBeenInitialized.countEvenUsingIfElse(arr, 2);
+
+ assertEquals(5, value);
+ }
+}
From 3c8bf25c07cde5169c57525e775a8ee201dbd0fc Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Mon, 28 Feb 2022 10:15:29 +0530
Subject: [PATCH 178/235] Using property for dependencies versions
---
.../spring-hibernate-5/pom.xml | 37 +++++++++----------
1 file changed, 17 insertions(+), 20 deletions(-)
diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml
index bb8c4e8228..ba18c5a221 100644
--- a/persistence-modules/spring-hibernate-5/pom.xml
+++ b/persistence-modules/spring-hibernate-5/pom.xml
@@ -107,27 +107,22 @@
com.h2database
h2
${h2.version}
-
+
- jakarta.xml.bind
- jakarta.xml.bind-api
- 2.3.2
-
-
- com.sun.xml.bind
- jaxb-core
- 2.3.0.1
-
-
- javax.xml.bind
- jaxb-api
- 2.3.1
-
-
- com.sun.xml.bind
- jaxb-impl
- 2.3.1
-
+ com.sun.xml.bind
+ jaxb-core
+ ${com.sun.xml.version}
+
+
+ javax.xml.bind
+ jaxb-api
+ ${javax.xml.bind.version}
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ ${com.sun.xml.version}
+
@@ -142,6 +137,8 @@
9.0.0.M26
1.1
2.3.4
+ 2.3.0.1
+ 2.3.1
\ No newline at end of file
From 55826111075ef9ba56c43e3cd2fb69537b98d661 Mon Sep 17 00:00:00 2001
From: Kai Yuan
Date: Tue, 1 Mar 2022 02:44:16 +0100
Subject: [PATCH 179/235] file to map article (#11838)
* file to map article
* add aggregateByKeys method
---
.../com/baeldung/filetomap/FileToHashMap.java | 83 +++++++++++++++++++
.../filetomap/FileToHashMapUnitTest.java | 66 +++++++++++++++
.../resources/filetomap/theLordOfRings.txt | 6 ++
3 files changed, 155 insertions(+)
create mode 100644 core-java-modules/core-java-io-4/src/main/java/com/baeldung/filetomap/FileToHashMap.java
create mode 100644 core-java-modules/core-java-io-4/src/test/java/com/baeldung/filetomap/FileToHashMapUnitTest.java
create mode 100644 core-java-modules/core-java-io-4/src/test/resources/filetomap/theLordOfRings.txt
diff --git a/core-java-modules/core-java-io-4/src/main/java/com/baeldung/filetomap/FileToHashMap.java b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/filetomap/FileToHashMap.java
new file mode 100644
index 0000000000..f88404a1a4
--- /dev/null
+++ b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/filetomap/FileToHashMap.java
@@ -0,0 +1,83 @@
+package com.baeldung.filetomap;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class FileToHashMap {
+
+ enum DupKeyOption {
+ OVERWRITE, DISCARD
+ }
+
+ public static Map byBufferedReader(String filePath, DupKeyOption dupKeyOption) {
+ HashMap map = new HashMap<>();
+ String line;
+ try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
+ while ((line = reader.readLine()) != null) {
+ String[] keyValuePair = line.split(":", 2);
+ if (keyValuePair.length > 1) {
+ String key = keyValuePair[0];
+ String value = keyValuePair[1];
+ if (DupKeyOption.OVERWRITE == dupKeyOption) {
+ map.put(key, value);
+ } else if (DupKeyOption.DISCARD == dupKeyOption) {
+ map.putIfAbsent(key, value);
+ }
+ } else {
+ System.out.println("No Key:Value found in line, ignoring: " + line);
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return map;
+ }
+
+ public static Map byStream(String filePath, DupKeyOption dupKeyOption) {
+ Map map = new HashMap<>();
+ try (Stream lines = Files.lines(Paths.get(filePath))) {
+ lines.filter(line -> line.contains(":"))
+ .forEach(line -> {
+ String[] keyValuePair = line.split(":", 2);
+ String key = keyValuePair[0];
+ String value = keyValuePair[1];
+ if (DupKeyOption.OVERWRITE == dupKeyOption) {
+ map.put(key, value);
+ } else if (DupKeyOption.DISCARD == dupKeyOption) {
+ map.putIfAbsent(key, value);
+ }
+ });
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return map;
+ }
+
+ public static Map> aggregateByKeys(String filePath) {
+ Map> map = new HashMap<>();
+ try (Stream lines = Files.lines(Paths.get(filePath))) {
+ lines.filter(line -> line.contains(":"))
+ .forEach(line -> {
+ String[] keyValuePair = line.split(":", 2);
+ String key = keyValuePair[0];
+ String value = keyValuePair[1];
+ if (map.containsKey(key)) {
+ map.get(key).add(value);
+ } else {
+ map.put(key, Stream.of(value).collect(Collectors.toList()));
+ }
+ });
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return map;
+ }
+}
diff --git a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/filetomap/FileToHashMapUnitTest.java b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/filetomap/FileToHashMapUnitTest.java
new file mode 100644
index 0000000000..c89f26de69
--- /dev/null
+++ b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/filetomap/FileToHashMapUnitTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.filetomap;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.net.URISyntaxException;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class FileToHashMapUnitTest {
+
+ private String filePath;
+
+ private static final Map EXPECTED_MAP_DISCARD = Stream.of(new String[][]{
+ {"title", "The Lord of the Rings: The Return of the King"},
+ {"director", "Peter Jackson"},
+ {"actor", "Sean Astin"}
+ }).collect(Collectors.toMap(data -> data[0], data -> data[1]));
+
+ private static final Map EXPECTED_MAP_OVERWRITE = Stream.of(new String[][]{
+ {"title", "The Lord of the Rings: The Return of the King"},
+ {"director", "Peter Jackson"},
+ {"actor", "Ian McKellen"}
+ }).collect(Collectors.toMap(data -> data[0], data -> data[1]));
+
+ private static final Map> EXPECTED_MAP_AGGREGATE = Stream.of(new String[][]{
+ {"title", "The Lord of the Rings: The Return of the King"},
+ {"director", "Peter Jackson"},
+ {"actor", "Sean Astin", "Ian McKellen"}
+ }).collect(Collectors.toMap(arr -> arr[0], arr -> Arrays.asList(Arrays.copyOfRange(arr, 1, arr.length))));
+
+ @Before
+ public void setPath() throws URISyntaxException {
+ if (filePath == null) {
+ filePath = Paths.get(ClassLoader.getSystemResource("filetomap/theLordOfRings.txt").toURI()).toString();
+ }
+ }
+
+ @Test
+ public void givenInputFile_whenInvokeByBufferedReaderPriorToJava8_shouldGetExpectedMap() {
+ Map mapOverwrite = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
+ Map mapDiscard = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.DISCARD);
+ assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
+ assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
+ }
+
+ @Test
+ public void givenInputFile_whenInvokeByStream_shouldGetExpectedMap() {
+ Map mapOverwrite = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
+ Map mapDiscard = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.DISCARD);
+ assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
+ assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
+ }
+
+ @Test
+ public void givenInputFile_whenInvokeAggregateByKeys_shouldGetExpectedMap() {
+ Map> mapAgg = FileToHashMap.aggregateByKeys(filePath);
+ assertThat(mapAgg).isEqualTo(EXPECTED_MAP_AGGREGATE);
+ }
+}
diff --git a/core-java-modules/core-java-io-4/src/test/resources/filetomap/theLordOfRings.txt b/core-java-modules/core-java-io-4/src/test/resources/filetomap/theLordOfRings.txt
new file mode 100644
index 0000000000..1ab069e533
--- /dev/null
+++ b/core-java-modules/core-java-io-4/src/test/resources/filetomap/theLordOfRings.txt
@@ -0,0 +1,6 @@
+title:The Lord of the Rings: The Return of the King
+director:Peter Jackson
+actor:Sean Astin
+actor:Ian McKellen
+Gandalf and Aragorn lead the World of Men against Sauron's
+army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.
\ No newline at end of file
From ca1feef04f8c1bf099a465d33958f77474ce51e1 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:13:20 +0500
Subject: [PATCH 180/235] Updated README.md
Added link back to the article: https://www.baeldung.com/java-producer-consumer-problem
---
core-java-modules/core-java-concurrency-advanced-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-concurrency-advanced-4/README.md b/core-java-modules/core-java-concurrency-advanced-4/README.md
index 446a553b88..ba838dbc72 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/README.md
+++ b/core-java-modules/core-java-concurrency-advanced-4/README.md
@@ -4,3 +4,4 @@
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
- [Start Two Threads at the Exact Same Time in Java](https://www.baeldung.com/java-start-two-threads-at-same-time)
- [Volatile Variables and Thread Safety](https://www.baeldung.com/java-volatile-variables-thread-safety)
+- [Producer-Consumer Problem With Example in Java](https://www.baeldung.com/java-producer-consumer-problem)
From a48620e5eb1228f789f300b3eba212c1dc622a0d Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:16:24 +0500
Subject: [PATCH 181/235] Updated README.md
added link back to the article: https://www.baeldung.com/spring-cloud-gateway-url-rewriting
---
spring-cloud/spring-cloud-gateway/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-cloud/spring-cloud-gateway/README.md b/spring-cloud/spring-cloud-gateway/README.md
index 6b199977e3..808536ce80 100644
--- a/spring-cloud/spring-cloud-gateway/README.md
+++ b/spring-cloud/spring-cloud-gateway/README.md
@@ -9,3 +9,4 @@ This module contains articles about Spring Cloud Gateway
- [Spring Cloud Gateway Routing Predicate Factories](https://www.baeldung.com/spring-cloud-gateway-routing-predicate-factories)
- [Spring Cloud Gateway WebFilter Factories](https://www.baeldung.com/spring-cloud-gateway-webfilter-factories)
- [Using Spring Cloud Gateway with OAuth 2.0 Patterns](https://www.baeldung.com/spring-cloud-gateway-oauth2)
+- [URL Rewriting With Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-url-rewriting)
From bd175a879c5aab6245feeba0f1098c31c91eb147 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:21:53 +0500
Subject: [PATCH 182/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-map-vs-hashmap
---
core-java-modules/core-java-collections-maps-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-collections-maps-4/README.md b/core-java-modules/core-java-collections-maps-4/README.md
index 795f0df702..a3f40d5ab7 100644
--- a/core-java-modules/core-java-collections-maps-4/README.md
+++ b/core-java-modules/core-java-collections-maps-4/README.md
@@ -6,3 +6,4 @@ This module contains articles about Map data structures in Java.
- [Using a Custom Class as a Key in a Java HashMap](https://www.baeldung.com/java-custom-class-map-key)
- [Nested HashMaps Examples in Java](https://www.baeldung.com/java-nested-hashmaps)
- [Java HashMap With Different Value Types](https://www.baeldung.com/java-hashmap-different-value-types)
+- [Difference Between Map and HashMap in Java](https://www.baeldung.com/java-map-vs-hashmap)
From b3a6dd04b37dea4de24723ad82a835063e149dcb Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:27:58 +0500
Subject: [PATCH 183/235] Updated README.md
added link back to the article: https://www.baeldung.com/spring-security-enable-logging
---
spring-security-modules/spring-security-web-boot-3/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-security-modules/spring-security-web-boot-3/README.md b/spring-security-modules/spring-security-web-boot-3/README.md
index 45fede7a4c..2f98e0f4a0 100644
--- a/spring-security-modules/spring-security-web-boot-3/README.md
+++ b/spring-security-modules/spring-security-web-boot-3/README.md
@@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com
- [Spring Security – Cache Control Headers](https://www.baeldung.com/spring-security-cache-control-headers)
- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight)
- [Content Security Policy with Spring Security](https://www.baeldung.com/spring-security-csp)
+- [Enable Logging for Spring Security](https://www.baeldung.com/spring-security-enable-logging)
- More articles: [[<-- prev]](/spring-security-modules/spring-security-web-boot-2)
From 085d41f3e51fe04c8623a8638113a1dacf41169a Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:30:07 +0500
Subject: [PATCH 184/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-missing-return-statement
---
core-java-modules/core-java-exceptions-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-exceptions-4/README.md b/core-java-modules/core-java-exceptions-4/README.md
index 259feb685c..e77787a8a3 100644
--- a/core-java-modules/core-java-exceptions-4/README.md
+++ b/core-java-modules/core-java-exceptions-4/README.md
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Java ArrayIndexOutOfBoundsException](https://www.baeldung.com/java-arrayindexoutofboundsexception)
+- [Java Missing Return Statement](https://www.baeldung.com/java-missing-return-statement)
From bc49cacab39d2a8fe6f960d1f0dfe7062d718ec6 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:32:54 +0500
Subject: [PATCH 185/235] Updated README.md
added link back to the article: https://www.baeldung.com/servlets-jsp-check-user-login
---
javax-servlets-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/javax-servlets-2/README.md b/javax-servlets-2/README.md
index f126f17297..9a7ad02d39 100644
--- a/javax-servlets-2/README.md
+++ b/javax-servlets-2/README.md
@@ -3,3 +3,4 @@
This module contains articles about Servlets.
### Relevant Articles:
+- [Check if a User Is Logged-in With Servlets and JSP](https://www.baeldung.com/servlets-jsp-check-user-login)
From 839711825b249addd1bf48aa06b331e7070cd094 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:50:13 +0500
Subject: [PATCH 186/235] Created/Updated README.md
added link back to the article: https://www.baeldung.com/maven-artifact-classifiers
---
maven-modules/maven-classifier/README.md | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 maven-modules/maven-classifier/README.md
diff --git a/maven-modules/maven-classifier/README.md b/maven-modules/maven-classifier/README.md
new file mode 100644
index 0000000000..ab8a7f914f
--- /dev/null
+++ b/maven-modules/maven-classifier/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [A Guide to Maven Artifact Classifiers](https://www.baeldung.com/maven-artifact-classifiers)
From 188d5daaf6a66959c4d109b91ccb8701ac5a2760 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 09:53:30 +0500
Subject: [PATCH 187/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-map-new-entry
---
core-java-modules/core-java-collections-maps-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-collections-maps-4/README.md b/core-java-modules/core-java-collections-maps-4/README.md
index a3f40d5ab7..92da12fbf9 100644
--- a/core-java-modules/core-java-collections-maps-4/README.md
+++ b/core-java-modules/core-java-collections-maps-4/README.md
@@ -7,3 +7,4 @@ This module contains articles about Map data structures in Java.
- [Nested HashMaps Examples in Java](https://www.baeldung.com/java-nested-hashmaps)
- [Java HashMap With Different Value Types](https://www.baeldung.com/java-hashmap-different-value-types)
- [Difference Between Map and HashMap in Java](https://www.baeldung.com/java-map-vs-hashmap)
+- [How to Create a New Entry in a Map](https://www.baeldung.com/java-map-new-entry)
From db7b5b1fd57f2c379e849414703b60fb4acadc59 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Tue, 1 Mar 2022 10:04:30 +0500
Subject: [PATCH 188/235] Updated README.md
added link back to the article: https://www.baeldung.com/ops/docker-cache-maven-dependencies
---
docker/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/docker/README.md b/docker/README.md
index 0adf1c9b51..b2ae5d56c9 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -7,3 +7,4 @@
- [Dockerfile Strategies for Git](https://www.baeldung.com/ops/dockerfile-git-strategies)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
- [How to Include Files Outside of Docker’s Build Context](https://www.baeldung.com/ops/docker-include-files-outside-build-context)
+- [Caching Maven Dependencies with Docker](https://www.baeldung.com/ops/docker-cache-maven-dependencies)
From 786138fd9bc341fd69e69902a64dcdd434acfe11 Mon Sep 17 00:00:00 2001
From: maibin
Date: Mon, 28 Feb 2022 21:22:53 -0800
Subject: [PATCH 189/235] Revert "Added a new Class and few test cases to the
core-java-modules (#11867)" (#11874)
This reverts commit e10e20a24be601c031dc677001043f01b075f93a.
---
.../VariableMightNotHaveBeenInitialized.java | 45 -------------------
...leMightNotHaveBeenInitializedUnitTest.java | 24 ----------
2 files changed, 69 deletions(-)
delete mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
delete mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
deleted file mode 100644
index 64118e6307..0000000000
--- a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.baeldung.exception.variablemightnothavebeeninitialized;
-
-public class VariableMightNotHaveBeenInitialized {
-
- private static int instanceVariableCount;
-
- /**
- * Method would not compile if lines 14 and 18 are uncommented.
- */
- public static void countEven() {
- //uninstantiated
- int count;
- int[] arr = new int[]{23, 56, 89, 12, 23};
- for (int i = 0; i < arr.length; i++) {
- if ((arr[i] % 2) == 0) {
- // count++;
- }
-
- }
- // System.out.println("Total Even Numbers : " + count);
- }
-
- public static int countEvenUsingInstanceVariable(int[] arr) {
-
- for (int i = 0; i < arr.length; i++) {
- if ((arr[i] % 2) == 0) {
- instanceVariableCount++;
- }
-
- }
- return instanceVariableCount;
- }
-
- public static int countEvenUsingIfElse(int[] arr, int args) {
- int count;
- count = args > 0 ? args : 0;
- for (int i = 0; i < arr.length; i++) {
- if ((arr[i] % 2) == 0) {
- count++;
- }
-
- }
- return count;
- }
-}
diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
deleted file mode 100644
index c4773d6442..0000000000
--- a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.baeldung.exception.variablemightnothavebeeninitialized;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class VariableMightNotHaveBeenInitializedUnitTest {
-
- @Test
- public void usingInstanceVariable_returnCount() {
- int[] arr = new int[]{1, 2, 3, 4, 5, 6};
- int value = VariableMightNotHaveBeenInitialized.countEvenUsingInstanceVariable(arr);
-
- assertEquals(3, value);
- }
-
- @Test
- public void usingArgumentsAndIfElse_returnCount() {
- int[] arr = new int[]{1, 2, 3, 4, 5, 6};
- int value = VariableMightNotHaveBeenInitialized.countEvenUsingIfElse(arr, 2);
-
- assertEquals(5, value);
- }
-}
From c87c79e035b37e92f334f11741ddfb5f08ea342a Mon Sep 17 00:00:00 2001
From: Daniel Strmecki
Date: Tue, 1 Mar 2022 10:07:50 +0100
Subject: [PATCH 190/235] BAEL-5307: Move code from new module to existing
(#11868)
---
graphql/graphql-java/pom.xml | 119 ++++++++++++++++++
.../graphql/clients/AmericanExpressNodes.java | 24 ++++
.../graphql/clients/ApacheHttpClient.java | 25 ++++
.../com/baeldung/graphql/data/Author.java | 31 +++++
.../java/com/baeldung/graphql/data/Book.java | 25 ++++
.../baeldung/graphql/data/BookRepository.java | 19 +++
.../java/com/baeldung/graphql/data/Data.java | 22 ++++
.../com/baeldung/graphql/data/Response.java | 19 +++
.../graphql/server/GraphQLEndpoint.java | 36 ++++++
.../baeldung/graphql/server/GraphQLQuery.java | 21 ++++
.../src/main/resources/schema.graphqls | 17 +++
.../baeldung/graphql/GraphQLMockServer.java | 85 +++++++++++++
.../clients/AmericanExpressNodesUnitTest.java | 39 ++++++
.../clients/ApacheHttpClientUnitTest.java | 49 ++++++++
14 files changed, 531 insertions(+)
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/AmericanExpressNodes.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/ApacheHttpClient.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Author.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Book.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/data/BookRepository.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Data.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Response.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLEndpoint.java
create mode 100644 graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLQuery.java
create mode 100644 graphql/graphql-java/src/main/resources/schema.graphqls
create mode 100644 graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java
create mode 100644 graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/AmericanExpressNodesUnitTest.java
create mode 100644 graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/ApacheHttpClientUnitTest.java
diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml
index 4e2444c1fb..f2733bf671 100644
--- a/graphql/graphql-java/pom.xml
+++ b/graphql/graphql-java/pom.xml
@@ -12,8 +12,24 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
+ ../../
+
+
+ jitpack.io
+ https://jitpack.io
+
+
+
+ false
+
+ central
+ Central Repository
+ https://repo.maven.apache.org/maven2
+
+
+
com.graphql-java
@@ -25,11 +41,114 @@
ratpack-core
${ratpack-core.version}
+
+ com.github.americanexpress.nodes
+ nodes
+ 0.5.0
+
+
+ com.graphql-java
+ graphql-java
+ 9.2
+
+
+ com.graphql-java
+ graphql-java-tools
+ 5.2.4
+
+
+ com.graphql-java
+ graphql-java-servlet
+ 6.1.3
+
+
+ javax.servlet
+ javax.servlet-api
+ 3.0.1
+ provided
+
+
+ org.apache.commons
+ commons-lang3
+ 3.12.0
+
+
+ org.mock-server
+ mockserver-netty
+ 5.11.2
+
+
+ org.mock-server
+ mockserver-client-java
+ 5.11.2
+
+
+ com.graphql-java-generator
+ graphql-java-runtime
+ ${graphql.java.generator.version}
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.8.2
+ test
+
+
+ org.assertj
+ assertj-core
+ 3.22.0
+ test
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+ org.eclipse.jetty
+ jetty-maven-plugin
+ 10.0.7
+
+
+ maven-war-plugin
+ 3.1.0
+
+
+ com.graphql-java-generator
+ graphql-maven-plugin
+ ${graphql.java.generator.version}
+
+
+
+ generateClientCode
+
+
+
+
+ com.baeldung.graphql.generated
+ false
+ false
+ true
+
+
+
+
+
3.0.3
1.4.6
+ 3.1
+ 1.8
+ 1.8
+ 1.18
\ No newline at end of file
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/AmericanExpressNodes.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/AmericanExpressNodes.java
new file mode 100644
index 0000000000..446dbd416e
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/AmericanExpressNodes.java
@@ -0,0 +1,24 @@
+package com.baeldung.graphql.clients;
+
+import com.baeldung.graphql.data.Data;
+import io.aexp.nodes.graphql.GraphQLRequestEntity;
+import io.aexp.nodes.graphql.GraphQLResponseEntity;
+import io.aexp.nodes.graphql.GraphQLTemplate;
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.IOException;
+
+public class AmericanExpressNodes {
+
+ public static GraphQLResponseEntity callGraphQLService(String url, String query) throws IOException {
+ GraphQLTemplate graphQLTemplate = new GraphQLTemplate();
+
+ GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder()
+ .url(StringUtils.join(url, "?query=", query))
+ .request(Data.class)
+ .build();
+
+ return graphQLTemplate.query(requestEntity, Data.class);
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/ApacheHttpClient.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/ApacheHttpClient.java
new file mode 100644
index 0000000000..d4f88e62f5
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/clients/ApacheHttpClient.java
@@ -0,0 +1,25 @@
+package com.baeldung.graphql.clients;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.impl.client.HttpClientBuilder;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+public class ApacheHttpClient {
+
+ public static HttpResponse callGraphQLService(String url, String query) throws URISyntaxException, IOException {
+ HttpClient client = HttpClientBuilder.create().build();
+ HttpGet request = new HttpGet(url);
+ URI uri = new URIBuilder(request.getURI())
+ .addParameter("query", query)
+ .build();
+ request.setURI(uri);
+ return client.execute(request);
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Author.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Author.java
new file mode 100644
index 0000000000..876df27769
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Author.java
@@ -0,0 +1,31 @@
+package com.baeldung.graphql.data;
+
+import org.apache.commons.lang3.StringUtils;
+
+public class Author {
+
+ private String name;
+ private String surname;
+
+ public Author() {
+
+ }
+
+ public Author(String name, String surname) {
+ this.name = name;
+ this.surname = surname;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getSurname() {
+ return surname;
+ }
+
+ public String getFullName() {
+ return StringUtils.join(getName(), " ", getSurname());
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Book.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Book.java
new file mode 100644
index 0000000000..6e6188368b
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Book.java
@@ -0,0 +1,25 @@
+package com.baeldung.graphql.data;
+
+public class Book {
+
+ private String title;
+ private Author author;
+
+ public Book() {
+
+ }
+
+ public Book(String title, Author author) {
+ this.title = title;
+ this.author = author;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public Author getAuthor() {
+ return author;
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/BookRepository.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/BookRepository.java
new file mode 100644
index 0000000000..f812ed088d
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/BookRepository.java
@@ -0,0 +1,19 @@
+package com.baeldung.graphql.data;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class BookRepository {
+
+ private static final List books = Stream.of(
+ new Book("Title 1", new Author("Pero", "Peric")),
+ new Book("Title 2", new Author("Marko", "Maric"))
+ ).collect(Collectors.toList());
+
+ public List getAllBooks() {
+ return Collections.unmodifiableList(books);
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Data.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Data.java
new file mode 100644
index 0000000000..63263a496b
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Data.java
@@ -0,0 +1,22 @@
+package com.baeldung.graphql.data;
+
+import java.util.Collections;
+import java.util.List;
+
+public class Data {
+
+ private List allBooks;
+
+ public Data() {
+
+ }
+
+ public Data(List allBooks) {
+ this.allBooks = allBooks;
+ }
+
+ public List getAllBooks() {
+ return Collections.unmodifiableList(allBooks);
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Response.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Response.java
new file mode 100644
index 0000000000..eedd13e04e
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/data/Response.java
@@ -0,0 +1,19 @@
+package com.baeldung.graphql.data;
+
+public class Response {
+
+ private Data data;
+
+ public Response() {
+
+ }
+
+ public Response(Data data) {
+ this.data = data;
+ }
+
+ public Data getData() {
+ return data;
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLEndpoint.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLEndpoint.java
new file mode 100644
index 0000000000..c69144c9f5
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLEndpoint.java
@@ -0,0 +1,36 @@
+package com.baeldung.graphql.server;
+
+import com.baeldung.graphql.data.BookRepository;
+import com.coxautodev.graphql.tools.SchemaParser;
+import graphql.schema.GraphQLSchema;
+import graphql.servlet.SimpleGraphQLHttpServlet;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet(urlPatterns = "/graphql")
+public class GraphQLEndpoint extends HttpServlet {
+
+ private SimpleGraphQLHttpServlet graphQLServlet;
+
+ @Override
+ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ graphQLServlet.service(req, resp);
+ }
+
+ @Override
+ public void init() {
+ GraphQLSchema schema = SchemaParser.newParser()
+ .resolvers(new GraphQLQuery(new BookRepository()))
+ .file("schema.graphqls")
+ .build()
+ .makeExecutableSchema();
+ graphQLServlet = SimpleGraphQLHttpServlet
+ .newBuilder(schema)
+ .build();
+ }
+}
diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLQuery.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLQuery.java
new file mode 100644
index 0000000000..8ba9fa25c5
--- /dev/null
+++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/server/GraphQLQuery.java
@@ -0,0 +1,21 @@
+package com.baeldung.graphql.server;
+
+import com.baeldung.graphql.data.Book;
+import com.baeldung.graphql.data.BookRepository;
+import com.coxautodev.graphql.tools.GraphQLQueryResolver;
+
+import java.util.List;
+
+public class GraphQLQuery implements GraphQLQueryResolver {
+
+ private final BookRepository repository;
+
+ public GraphQLQuery(BookRepository repository) {
+ this.repository = repository;
+ }
+
+ public List allBooks() {
+ return repository.getAllBooks();
+ }
+
+}
diff --git a/graphql/graphql-java/src/main/resources/schema.graphqls b/graphql/graphql-java/src/main/resources/schema.graphqls
new file mode 100644
index 0000000000..b0834e04b7
--- /dev/null
+++ b/graphql/graphql-java/src/main/resources/schema.graphqls
@@ -0,0 +1,17 @@
+type Book {
+ title: String!
+ author: Author
+}
+
+type Author {
+ name: String!
+ surname: String!
+}
+
+type Query {
+ allBooks: [Book]
+}
+
+schema {
+ query: Query
+}
\ No newline at end of file
diff --git a/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java b/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java
new file mode 100644
index 0000000000..fb5a789428
--- /dev/null
+++ b/graphql/graphql-java/src/test/java/com/baeldung/graphql/GraphQLMockServer.java
@@ -0,0 +1,85 @@
+package com.baeldung.graphql;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.mockserver.client.MockServerClient;
+import org.mockserver.integration.ClientAndServer;
+import org.mockserver.model.HttpStatusCode;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URISyntaxException;
+
+import static org.mockserver.integration.ClientAndServer.startClientAndServer;
+import static org.mockserver.matchers.Times.exactly;
+import static org.mockserver.model.HttpRequest.request;
+import static org.mockserver.model.HttpResponse.response;
+
+public class GraphQLMockServer {
+
+ public static ClientAndServer mockServer;
+ public static String serviceUrl;
+
+ private static int serverPort;
+
+ public static final String SERVER_ADDRESS = "127.0.0.1";
+ public static final String HTTP_GET_POST = "GET";
+ public static final String PATH = "/graphql";
+
+ @BeforeAll
+ static void startServer() throws IOException, URISyntaxException {
+ serverPort = getFreePort();
+ serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
+ mockServer = startClientAndServer(serverPort);
+ mockAllBooksTitleRequest();
+ mockAllBooksTitleAuthorRequest();
+ }
+
+ @AfterAll
+ static void stopServer() {
+ mockServer.stop();
+ }
+
+ private static void mockAllBooksTitleAuthorRequest() {
+ String requestQuery = "{allBooks{title,author{name,surname}}}";
+ String responseJson = "{\"data\":{\"allBooks\":[{\"title\":\"Title 1\",\"author\":{\"name\":\"Pero\",\"surname\":\"Peric\"}},{\"title\":\"Title 2\",\"author\":{\"name\":\"Marko\",\"surname\":\"Maric\"}}]}}";
+
+ new MockServerClient(SERVER_ADDRESS, serverPort)
+ .when(
+ request()
+ .withPath(PATH)
+ .withQueryStringParameter("query", requestQuery),
+ exactly(1)
+ )
+ .respond(
+ response()
+ .withStatusCode(HttpStatusCode.OK_200.code())
+ .withBody(responseJson)
+ );
+ }
+
+ private static void mockAllBooksTitleRequest() {
+ String requestQuery = "{allBooks{title}}";
+ String responseJson = "{\"data\":{\"allBooks\":[{\"title\":\"Title 1\"},{\"title\":\"Title 2\"}]}}";
+
+ new MockServerClient(SERVER_ADDRESS, serverPort)
+ .when(
+ request()
+ .withPath(PATH)
+ .withQueryStringParameter("query", requestQuery),
+ exactly(1)
+ )
+ .respond(
+ response()
+ .withStatusCode(HttpStatusCode.OK_200.code())
+ .withBody(responseJson)
+ );
+ }
+
+ private static int getFreePort () throws IOException {
+ try (ServerSocket serverSocket = new ServerSocket(0)) {
+ return serverSocket.getLocalPort();
+ }
+ }
+
+}
diff --git a/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/AmericanExpressNodesUnitTest.java b/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/AmericanExpressNodesUnitTest.java
new file mode 100644
index 0000000000..8466cdee76
--- /dev/null
+++ b/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/AmericanExpressNodesUnitTest.java
@@ -0,0 +1,39 @@
+package com.baeldung.graphql.clients;
+
+import com.baeldung.graphql.GraphQLMockServer;
+import com.baeldung.graphql.data.Data;
+import io.aexp.nodes.graphql.GraphQLResponseEntity;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertAll;
+
+class AmericanExpressNodesUnitTest extends GraphQLMockServer {
+
+ @Test
+ void givenGraphQLEndpoint_whenRequestingAllBooksWithTitle_thenExpectedJsonIsReturned() throws IOException {
+ GraphQLResponseEntity responseEntity = AmericanExpressNodes.callGraphQLService(serviceUrl, "{allBooks{title}}");
+
+ assertAll(
+ () -> assertThat(responseEntity.getResponse().getAllBooks()).hasSize(2),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(0).getTitle()).isEqualTo("Title 1"),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(1).getTitle()).isEqualTo("Title 2")
+ );
+ }
+
+ @Test
+ void givenGraphQLEndpoint_whenRequestingAllBooksWithTitleAndAuthor_thenExpectedJsonIsReturned() throws IOException {
+ GraphQLResponseEntity responseEntity = AmericanExpressNodes.callGraphQLService(serviceUrl, "{allBooks{title,author{name,surname}}}");
+
+ assertAll(
+ () -> assertThat(responseEntity.getResponse().getAllBooks()).hasSize(2),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(0).getTitle()).isEqualTo("Title 1"),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(0).getAuthor().getFullName()).isEqualTo("Pero Peric"),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(1).getTitle()).isEqualTo("Title 2"),
+ () -> assertThat(responseEntity.getResponse().getAllBooks().get(1).getAuthor().getFullName()).isEqualTo("Marko Maric")
+ );
+ }
+
+}
diff --git a/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/ApacheHttpClientUnitTest.java b/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/ApacheHttpClientUnitTest.java
new file mode 100644
index 0000000000..17d97e0d14
--- /dev/null
+++ b/graphql/graphql-java/src/test/java/com/baeldung/graphql/clients/ApacheHttpClientUnitTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.graphql.clients;
+
+import com.baeldung.graphql.GraphQLMockServer;
+import com.baeldung.graphql.data.Response;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpResponse;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertAll;
+
+class ApacheHttpClientUnitTest extends GraphQLMockServer {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ @Test
+ void givenGraphQLEndpoint_whenRequestingAllBooksWithTitle_thenExpectedJsonIsReturned() throws IOException, URISyntaxException {
+ HttpResponse httpResponse = ApacheHttpClient.callGraphQLService(serviceUrl, "{allBooks{title}}");
+ String actualResponse = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8.name());
+ Response parsedResponse = objectMapper.readValue(actualResponse, Response.class);
+
+ assertAll(
+ () -> assertThat(parsedResponse.getData().getAllBooks()).hasSize(2),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(0).getTitle()).isEqualTo("Title 1"),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(1).getTitle()).isEqualTo("Title 2")
+ );
+ }
+
+ @Test
+ void givenGraphQLEndpoint_whenRequestingAllBooksWithTitleAndAuthor_thenExpectedJsonIsReturned() throws IOException, URISyntaxException {
+ HttpResponse httpResponse = ApacheHttpClient.callGraphQLService(serviceUrl, "{allBooks{title,author{name,surname}}}");
+ String actualResponse = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8.name());
+ Response parsedResponse = objectMapper.readValue(actualResponse, Response.class);
+
+ assertAll(
+ () -> assertThat(parsedResponse.getData().getAllBooks()).hasSize(2),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(0).getTitle()).isEqualTo("Title 1"),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(0).getAuthor().getFullName()).isEqualTo("Pero Peric"),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(1).getTitle()).isEqualTo("Title 2"),
+ () -> assertThat(parsedResponse.getData().getAllBooks().get(1).getAuthor().getFullName()).isEqualTo("Marko Maric")
+ );
+ }
+
+}
From 36899fd0e354792587282f6fc8741d4e59c1f595 Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Tue, 1 Mar 2022 18:13:26 +0530
Subject: [PATCH 191/235] JAVA-10379 Fix tests in hibernate-mapping-2 module
---
.../hibernate-mapping-2/pom.xml | 2 +-
...notationJavaConfigMainIntegrationTest.java | 7 ++
...nyToManyAnnotationMainIntegrationTest.java | 92 ++++++++++---------
3 files changed, 57 insertions(+), 44 deletions(-)
diff --git a/persistence-modules/hibernate-mapping-2/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml
index 10c07c95eb..06a1535442 100644
--- a/persistence-modules/hibernate-mapping-2/pom.xml
+++ b/persistence-modules/hibernate-mapping-2/pom.xml
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- hibernate-mapping-2y
+ hibernate-mapping-2
0.1-SNAPSHOT
hibernate-mapping-2
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
index 19d1a5ff50..69b791b4d4 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
@@ -45,6 +45,13 @@ public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest {
projects.add(new Project("Networking Project"));
session.persist(new Employee("Peter", "Oven", projects));
session.persist(new Employee("Allan", "Norman", projects));
+
+ Set employees = new HashSet();
+ employees.add(new Employee("Sam", "Curran"));
+ employees.add(new Employee("Tom", "Curran"));
+ Project project = new Project("Database Project");
+ project.setEmployees(employees);
+ session.persist(project);
}
}
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
index bfa158d43f..71051c821c 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.manytomany;
-import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashSet;
import java.util.List;
@@ -23,60 +23,66 @@ import com.baeldung.manytomany.util.HibernateUtil;
* Configured in: manytomany.cfg.xml
*/
public class HibernateManyToManyAnnotationMainIntegrationTest {
- private static SessionFactory sessionFactory;
+ private static SessionFactory sessionFactory;
- private Session session;
+ private Session session;
- @BeforeClass
- public static void beforeTests() {
- sessionFactory = HibernateUtil.getSessionFactory();
- }
+ @BeforeClass
+ public static void beforeTests() {
+ sessionFactory = HibernateUtil.getSessionFactory();
+ }
- @Before
- public void setUp() {
- session = sessionFactory.openSession();
- session.beginTransaction();
- }
+ @Before
+ public void setUp() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ }
- @Test
- public void givenData_whenInsert_thenCreatesMtoMrelationship() {
- String[] employeeData = { "Peter Oven", "Allan Norman" };
- String[] projectData = { "IT Project", "Networking Project" };
- Set projects = new HashSet();
-
- for (String proj : projectData) {
- projects.add(new Project(proj));
- }
-
- for (String emp : employeeData) {
- Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
- assertEquals(0, employee.getProjects().size());
- employee.setProjects(projects);
- session.persist(employee);
- assertNotNull(employee);
- }
- }
-
- @Test
+ @Test
public void givenSession_whenRead_thenReturnsMtoMdata() {
+ prepareData();
+ @SuppressWarnings("unchecked")
+ List employeeList = session.createQuery("FROM Employee").list();
@SuppressWarnings("unchecked")
- List employeeList = session.createQuery("FROM Employee").list();
+ List projectList = session.createQuery("FROM Project").list();
assertNotNull(employeeList);
+ assertNotNull(projectList);
+ assertEquals(2, employeeList.size());
+ assertEquals(2, projectList.size());
+
for(Employee employee : employeeList) {
assertNotNull(employee.getProjects());
}
+ for(Project project : projectList) {
+ assertNotNull(project.getEmployees());
+ }
}
- @After
- public void tearDown() {
- session.getTransaction()
- .commit();
- session.close();
- }
+ private void prepareData() {
+ String[] employeeData = { "Peter Oven", "Allan Norman" };
+ String[] projectData = { "IT Project", "Networking Project" };
+ Set projects = new HashSet();
- @AfterClass
- public static void afterTests() {
- sessionFactory.close();
- }
+ for (String proj : projectData) {
+ projects.add(new Project(proj));
+ }
+
+ for (String emp : employeeData) {
+ Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
+ employee.setProjects(projects);
+ session.persist(employee);
+ }
+ }
+
+ @After
+ public void tearDown() {
+ session.getTransaction().commit();
+ session.close();
+ }
+
+ @AfterClass
+ public static void afterTests() {
+ sessionFactory.close();
+ }
}
From 5aa5da657bd8a9b26b0c9db7e7cc43cfa4f24259 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Wed, 2 Mar 2022 12:26:29 +0000
Subject: [PATCH 192/235] [JAVA-10320] Run Cassandra test with a single fork
---
persistence-modules/java-cassandra/pom.xml | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml
index 6df75edc56..b0b98b040a 100644
--- a/persistence-modules/java-cassandra/pom.xml
+++ b/persistence-modules/java-cassandra/pom.xml
@@ -50,6 +50,25 @@
+
+
+ integration-lite-first
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+ 1
+ true
+
+
+
+
+
+
+
3.1.2
From 304f5fa74d1f24ab798bd0d96451be0351127e69 Mon Sep 17 00:00:00 2001
From: Mateusz Szablak
Date: Thu, 3 Mar 2022 04:52:25 +0100
Subject: [PATCH 193/235] BAEL-5201 Finding the Last Row in an Excel
Spreadsheet From Java (#11873)
---
.../poi/excel/lastrow/LastRowUnitTest.java | 67 ++++++++++++++++++
.../src/test/resources/lastRowTest.xlsx | Bin 0 -> 8949 bytes
2 files changed, 67 insertions(+)
create mode 100644 apache-poi-2/src/test/java/com/baeldung/poi/excel/lastrow/LastRowUnitTest.java
create mode 100644 apache-poi-2/src/test/resources/lastRowTest.xlsx
diff --git a/apache-poi-2/src/test/java/com/baeldung/poi/excel/lastrow/LastRowUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/lastrow/LastRowUnitTest.java
new file mode 100644
index 0000000000..ea838be4ce
--- /dev/null
+++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/lastrow/LastRowUnitTest.java
@@ -0,0 +1,67 @@
+package com.baeldung.poi.excel.lastrow;
+
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Paths;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class LastRowUnitTest {
+ private static final String FILE_NAME = "lastRowTest.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void setup() throws URISyntaxException {
+ fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
+ }
+
+ @Test
+ public void givenExampleGrid_whenGetRow_thenReturnRowObjectIfModified() throws IOException {
+ Workbook workbook = new XSSFWorkbook(fileLocation);
+ Sheet sheet = workbook.getSheetAt(0);
+
+ assertEquals(7, sheet.getLastRowNum());
+ assertEquals(6, sheet.getPhysicalNumberOfRows());
+
+ assertNotNull(sheet.getRow(0));
+ assertNotNull(sheet.getRow(1));
+ assertNotNull(sheet.getRow(2));
+ assertNotNull(sheet.getRow(3));
+ assertNull(sheet.getRow(4));
+ assertNull(sheet.getRow(5));
+ assertNotNull(sheet.getRow(6));
+ assertNotNull(sheet.getRow(7));
+ assertNull(sheet.getRow(8));
+
+ assertSame(sheet.getRow(7), getLastRowFromSheet(sheet));
+ }
+
+ @Test
+ public void givenEmptySheet_whenGetRow_thenReturnNull() throws IOException {
+ Workbook workbook = new XSSFWorkbook(fileLocation);
+ Sheet sheet = workbook.getSheetAt(1);
+
+ assertEquals(-1, sheet.getLastRowNum());
+ assertEquals(0, sheet.getPhysicalNumberOfRows());
+
+ assertNull(sheet.getRow(0));
+
+ assertSame(sheet.getRow(0), getLastRowFromSheet(sheet));
+ }
+
+ public static Row getLastRowFromSheet(Sheet sheet) {
+ Row lastRow = null;
+ int lastRowNum = sheet.getLastRowNum();
+ if (lastRowNum >= 0) {
+ lastRow = sheet.getRow(lastRowNum);
+ }
+ return lastRow;
+ }
+}
diff --git a/apache-poi-2/src/test/resources/lastRowTest.xlsx b/apache-poi-2/src/test/resources/lastRowTest.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..3980ceb1f2f6a7bbb2f2e2a184b453234f717d71
GIT binary patch
literal 8949
zcmeHMg`$apu+2l
z+S|F9+PUbfc{rFlzhr%7YeSiX2+x=efQMcG-|auR2cU_=b{*`%?!$x&4D~Wq(l6}t
zxIqZ>(WGND2qt0gu`O}B{M+Y;ANqpi$x)RpQzUFx53gsVz-0DT38hroZnY-2IX#@^
zV@$S$bk}cN)-j)SGJe46)@Ga~h>eo0`OZ%dpEY_Fz+V4*$s(@Li<6=$giJ7gUxhQt--FLOvG=;O4;8XqZ=#T}3zoi(@O
zNpHxl64fD>?=EMF4fAPI`+3Ir^H)3jWzCuM=CM1ejH>U~qe?ES-c1OOe-Rj?ec-_N
z$xsb6+Q2}Cs@&iC08mpSiKKMG64?_<;aW`Ug^L)Y)myVBseR
z10p&MsrpW)HqLCUKac-K=zlOQ|Mu!1;^h@P*@3}_Qa2&Jmy?UJSR%6S!ct9CYCe9_
z3z#)gxwNEuh8`Tjt$sLv{X*L|xT_&$8So
z(}|zjL*K;a)2Uc`8}6+)i^98J6>1R973Z*I4_)@TuTC}SxIe=K%JZNT(tFew5J6G2
z1S?wq2Fab}jwTxH%m4xaKmtI8du7A+Cr;e$ove-Q?X7I-j9>@DD~^5=awmNST@G3)S=)pWE$x+qh6noKn=HyPnMTjOGpA^
zmYQ9+uH@dV_XdqBg^*~s^ZG<+;|L39n)gndTpg`Q5yY8COH=dNozT7A%Q7TLpZ)N_
z*v0zM2fKxZ0a_MrrzUztZSr#O6)ZMCvshe@2ODPUM33fPIgE$oJKlw*Fz{%3|2C37
zHyeyzz|KHnk%S2g5m+SsJ%&Cc$j8jFV+9{3eW!S`ENX;X>4yqYDGFCpha?|lMy+9?
z`-;_ehLqeMX3&044)1^DSqbLySxP;Ab^K}+E#uAUSQ=S^azGsW0>K!W(~b2dU7FE4
z0vD3%R4AE#P)|&M33Xt(#SxJ4GZv<%q|Gs!6js7TA{o{
zQv|WpD2-P8Ln^4AVPMgVsP+jRp>;ngi`*8K0wV$CYyG}COwizR;P?P}I{&K1wBL*@
zU1v?8QQkLiFZQX5mVin&6V6yeuaK$uXS=q<5`N*=w1+!%(sEMzCr-*TbeY$+G#b;(
zsdnmk65-#j2-bu%q0#&EPlOm-m3Pblcun}JWfxidFN9h%Y|+2w6E!rviJB)MUtvvK5(`|_
z1?`_9V-Mkl3{}fU&=F_EIg(PbuB2lwhLbQj-=ydD6^583OZ1rugpF-SN{qY6JQ=hk+X9vEfDEDPQJNO>YD+@m_K0YDjZ$~tO
zF#|E`k5+mKl-_>#@cL4@GNInOu4XZTPKIA#oof56d2PUpQbv`D6E7pEmnJ6>A74JW
zbpij5%wx_#*^nNoZzR*gC9};p#j47D-Ay+17$C9*w2iV%5zg*sS<%YsOGf1_&R?DR
zq`~cPhu@x58^epf%Ki?COx54>4IP_4d`Cs&a*Yp@N5sQLC5gc$L#mjR{#^;FARb_m
z+bCX&9^s&x_t6(Q#di)m%*Cd*LjX{$tGw(<;x4roV!Z$r+}?a_4lU~1^CN-MeD=A=
zUlra0wKJ2?PV{>1bIK*NAMDtFExtPd8z3j6B6;Y@&?lKw&SF8TPzR)a*KoKRl_&Hd
z9ECQ^>BiO$-+`CBK{ndP1|H2z!$CQ3!MphjM)~iblC8Yrq~LRG1@Y!al8a`|Ft*1Q
zW|vUO;FTW-pD(rs5h39jV6Gk9uDRtNJr7Sv5gdsh{ak6m`qE6js!vJz%?h)e2znJU
zMp2QJWC?Jv0OPgT4E0V%BB?45;$Ryse#9%
zVqjLo*GxnJ(8cMtvqkVJr7(1_VQ_2yvO%&X{8(2VQ}zq@6R&0;_#QS=!?W+VJVB?Hy*OcHqygN
zJrU$hB3ttobH!VGrqI`1xX~L0B{+MPTzb@8pW5!a`=S2V+amt-mzc9{63W7*?$JvQ
zKY+ECVN~vW`E?)$&1ADigV<4cE98V|l4_+sJw@Ha1cn!eAG$6n4y8fi*6}>EY+>
zm15Lqg(Y8Y5$w5#?edDSx7E(9e%uYO68>&<7SYUn@{s|6Vv?T%z#nza#lqCqlfKi^;jf$OecM?r=Xh7TFVU7c6oNTG=8|fc9P`9;TrAm
z`GM@5-MLDas{^MQZv4R9LFr2NgbO*V5~pw?UHv{QhxYC38%W0ZB=)}T2%
zTBtYV#fGtk#0^gR8e*%wHVF;f$L$XS(xV((QI-uF#fV>t;-IcLc!6_Z`sAJ=GIE?J
z1Vd5ViIEjeEjxLN?+e8oX4wn2{rBKEHi9!(3!Twl@T?S;hA}elu_e@lx>7NZGRT%
zQ$AG)un-7_Gq2s^zqNzRpE`d){``og(JM-?#p(<9?fJv>XRSBHuaG{Ud68bVQzEjF
zz`h@~b}>ZhZ2kQEs2#ag8CD8{{WY^gxnfD^{pwb1v8&)V43&rl|%go_ecMD}C&WFy@RiU2PN8@zAZ%}~%nO(2g
zd^0^&qJ?#dEXT$K*hB3>(p6;775ZLOFDeQ{Ai|k~UT!Bx+kKt-ijTnj9#_swbtR=Rhx*U&_;Dc
z0%P*&O?YZ>XCmM2gN+4xXPTg6E8#X|pfTq4qnF+EocQY_1VnT>xZh=s5!(}vzuO0iTlho|yUq_~8a
z8xb?YA?Nqd@}(>*ay0!IW^c;KW%C=~4_^)%e8yBURGgto=0k8G*t-C(mb&1OOCJ1u
z?q4s6Rd?OSa8R{z(lzedJ|eW#75|du%i8JGp{mHXzm`gK|0GVPs7D$wTiKRl!p*s*
zG+pxOtvv~F;fc6Rw{+@NWat*9h_lwF=Hzp?Zs$p^g8|}@uWeQuO{U&5b#r1*R>4pE
z+&)g0EEJoOb;L2wJ-%xsuO*`vMTs(!tkw8_LzOY}ZJ-SSOxFm~D(foJE&i4l>m5Y%GBOqVXJ
zr+8+dv_qPycv%HU1bLT&>@epAx4=eB6mw&ceUs|UU8k`?$ij-#V#F3uVXB*Ykp5<#
zy;mzkWGicG=3B$bB&QGsV#
zOk;hyxFd1A%%{1?iP2ip<*l~m0lPYn%L2t}G{T%q4y^GI2di_qIzg7l
z^bci+hIHk}SsjG4J*as*?RQBG&!O`gKC#a-YAS_3B&RSRPnL%I7`98e`wMtF5H)89
zK$JSbV&Mj(DH+V>)o`lonZ47YN9#{i#@r4yZ=wmOZpzgxzu(4dUNYwwEElKnx9Weq
zxV6fkE(QB_Q0LU|nDcNV@W$ly-{?uy*e?u1AvATe#sn#;jkZjWJ0}#>*tMwDvyDU`FdDSJp=W&cyt3%%AE5)=@mZm6mHW-
zD>2kM2?z(Z%`$U0>y)l>^AEO8d&IIC8>|z*UT+0lGB?%!fYq*lQ*#J25#$EOIf4=Y
zU(WGIX-iDhjY((63R-@AE~w?B51f4luVI;^eyUVlGS~Xd4Dh&BXwiE6vfV}?1O)N=BM$(owblv
zi^U;#fInsXRlFP38K1G9OLl{z4JL9HXv*@D!>-PT7fSOZy|HkXv9oAP)`#Q|8k*i1
zrc0n{=~he|bf7wBzY@A_O=!uo(0LIszOa9Bn^fK?3DsaGRzOI^VL6ev{;;MS)T&=e
z%1VDx?h!Pt!n3e&9kpJe8WX4#7qe%$XW4ehG%a#TZhUi%c;vhRVeUvHg%EGEna
z1fV&ry~&ftGrr~}xa4KgB^|k{-aTqXc=}A9y{&tW-F8*_lrZl*Y_9h2h_U6voX>&r
zpFY@*_a_f>wlH)uHBohOva~b*V@@X)EsWOjlc5HPmEXRTM{nPLI1B|$Fbx9>riPi=8!I{4J2xeGaU0JRT~oT>LS%ueqb64Elx_huQ6D&+(B)ZG{eV+j9qy
zvI>lHlY;Px`($9L|^5-7Yliu7+j0aR;nFI($O2XNEvx;_khS~I11ltky-KztxBoy-pq3W%MpeO
zkUxD(w5Q$AhcgdfiV2`>6=*t=<>Uhv+nrCsKfygAN$=g8NfW`?c?Q3STQ)1^6!2d&4A@e`B&JM64_2hWvwy;o9;i!PQ
zqP+c94Fp5U^U{G=d1|m6%iuV$$S}uhH){qQbj84lx)6
zm0^=#?7u_M*xt$XzZirK>i=%u@yfED?07-TNIyjTywa;(or7x;lE8dedrIEueTy14
zW3ggQw_f9J5ON^JA(&wqd>L=!5$k${(5(^mS(ywQ&u=xVXo6KT-3gyn$$(rnU@|Iz
zjJ!R^)X^)!QQpJ&%Or>-67mT-Gw;b)eo3!QP}j@}Sjvp%P)Tp$sRZYyY*lC4FWV4@wNYdRp!2*`zrh|Ps9)YrODqnzOT>zG8TXd
zRj`NnrPkgzy{}pQGBw8dzx)16!Mg9|zP9qq3mhz+!5-kg(sJLyeH#1A!8E~dAL9>F
zd*91_YV*s>1L8mX;Xcv1@8O?B;+H)Dun6;TpH|$rzMsZ_*=LabasPiL_50TU%%Hz)
g0RRK?zuo(
literal 0
HcmV?d00001
From 240ba4e0dbec2216715d58f958328a909f3afd2e Mon Sep 17 00:00:00 2001
From: Dhawal Kapil
Date: Thu, 3 Mar 2022 13:35:05 +0530
Subject: [PATCH 194/235] JAVA-10352 Updated versions of various libraries and
standardised pom version to 1.0.0-SNAPSHOT
---
maven-modules/maven-simple/maven-profiles/pom.xml | 2 +-
maven-modules/maven-simple/parent-project/core/pom.xml | 2 +-
maven-modules/maven-simple/parent-project/pom.xml | 3 +--
maven-modules/maven-simple/parent-project/service/pom.xml | 2 +-
maven-modules/maven-simple/parent-project/webapp/pom.xml | 2 +-
maven-modules/maven-simple/plugin-management/pom.xml | 6 +++---
.../maven-simple/plugin-management/submodule-1/pom.xml | 2 +-
.../maven-simple/plugin-management/submodule-2/pom.xml | 2 +-
maven-modules/maven-simple/pom.xml | 1 +
9 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/maven-modules/maven-simple/maven-profiles/pom.xml b/maven-modules/maven-simple/maven-profiles/pom.xml
index 322dada104..ba915038ad 100644
--- a/maven-modules/maven-simple/maven-profiles/pom.xml
+++ b/maven-modules/maven-simple/maven-profiles/pom.xml
@@ -5,7 +5,7 @@
4.0.0
com.baeldung
maven-profiles
- 0.0.1-SNAPSHOT
+ 1.0.0-SNAPSHOT
maven-profiles
diff --git a/maven-modules/maven-simple/parent-project/core/pom.xml b/maven-modules/maven-simple/parent-project/core/pom.xml
index ec25c9ace5..8f7371639f 100644
--- a/maven-modules/maven-simple/parent-project/core/pom.xml
+++ b/maven-modules/maven-simple/parent-project/core/pom.xml
@@ -10,7 +10,7 @@
parent-project
com.baeldung
- 1.0-SNAPSHOT
+ 1.0.0-SNAPSHOT
diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml
index a68f8e63bc..fce9aa3f72 100644
--- a/maven-modules/maven-simple/parent-project/pom.xml
+++ b/maven-modules/maven-simple/parent-project/pom.xml
@@ -4,14 +4,13 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
parent-project
- 1.0-SNAPSHOT
parent-project
pom
com.baeldung
maven-simple
- 0.0.1-SNAPSHOT
+ 1.0.0-SNAPSHOT
diff --git a/maven-modules/maven-simple/parent-project/service/pom.xml b/maven-modules/maven-simple/parent-project/service/pom.xml
index 1953ec8638..39945af248 100644
--- a/maven-modules/maven-simple/parent-project/service/pom.xml
+++ b/maven-modules/maven-simple/parent-project/service/pom.xml
@@ -10,7 +10,7 @@
parent-project
com.baeldung
- 1.0-SNAPSHOT
+ 1.0.0-SNAPSHOT
diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml
index bd13c5aeb8..1ab1321b20 100644
--- a/maven-modules/maven-simple/parent-project/webapp/pom.xml
+++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml
@@ -10,7 +10,7 @@
parent-project
com.baeldung
- 1.0-SNAPSHOT
+ 1.0.0-SNAPSHOT
diff --git a/maven-modules/maven-simple/plugin-management/pom.xml b/maven-modules/maven-simple/plugin-management/pom.xml
index 2fb2d5ed41..3c4bd886ac 100644
--- a/maven-modules/maven-simple/plugin-management/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/pom.xml
@@ -9,7 +9,7 @@
maven-simple
com.baeldung
- 0.0.1-SNAPSHOT
+ 1.0.0-SNAPSHOT
@@ -56,8 +56,8 @@
- 3.8.1
- 3.2.0
+ 3.10.0
+ 3.3.0
\ No newline at end of file
diff --git a/maven-modules/maven-simple/plugin-management/submodule-1/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-1/pom.xml
index c36e092254..ff08dec9a6 100644
--- a/maven-modules/maven-simple/plugin-management/submodule-1/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/submodule-1/pom.xml
@@ -8,7 +8,7 @@
plugin-management
com.baeldung
- 0.0.1-SNAPSHOT
+ 1.0.0-SNAPSHOT
diff --git a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
index e50d3cc26d..5db76cebdb 100644
--- a/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
+++ b/maven-modules/maven-simple/plugin-management/submodule-2/pom.xml
@@ -8,7 +8,7 @@
plugin-management
com.baeldung
- 0.0.1-SNAPSHOT
+ 1.0.0-SNAPSHOT
\ No newline at end of file
diff --git a/maven-modules/maven-simple/pom.xml b/maven-modules/maven-simple/pom.xml
index 938e2240f8..fe59259758 100644
--- a/maven-modules/maven-simple/pom.xml
+++ b/maven-modules/maven-simple/pom.xml
@@ -5,6 +5,7 @@
4.0.0
maven-simple
maven-simple
+ 1.0.0-SNAPSHOT
pom
From 2eb49b96cbe156482effd6ecc16238ab0aadbf21 Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Thu, 3 Mar 2022 23:06:08 +0530
Subject: [PATCH 195/235] BAEL 5359: Update formatting (#11880)
* BAEL-5359: Updating Multiple Fields in a MongoDB Document
* BAEL-5359: Add test class file
* BAEL-5359: Rename UpdateMultipleFieldsUnitTest.java to UpdateMultipleFieldsLiveTest.java
* BAEL-5359: Update formatting
---
.../mongo/update/MultipleFieldsExample.java | 46 +++++++++----------
.../mongo/update/UpdateMultipleFields.java | 31 ++++++-------
.../update/UpdateMultipleFieldsLiveTest.java | 16 +++----
3 files changed, 45 insertions(+), 48 deletions(-)
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
index b2fcddeafb..ebc56cbfd0 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
@@ -10,35 +10,35 @@ import com.mongodb.client.result.UpdateResult;
public class MultipleFieldsExample {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- //
- // Connect to cluster (default is localhost:27017)
- //
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
- MongoClient mongoClient = new MongoClient("localhost", 27017);
- MongoDatabase database = mongoClient.getDatabase("baeldung");
- MongoCollection collection = database.getCollection("employee");
+ MongoClient mongoClient = new MongoClient("localhost", 27017);
+ MongoDatabase database = mongoClient.getDatabase("baeldung");
+ MongoCollection collection = database.getCollection("employee");
- //
- // Filter on the basis of employee_id
- //
+ //
+ // Filter on the basis of employee_id
+ //
- BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
+ BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
- //
- // Update the fields in Document
- //
+ //
+ // Update the fields in Document
+ //
- BasicDBObject updateFields = new BasicDBObject();
- updateFields.append("department_id", 3);
- updateFields.append("job", "Sales Manager");
- BasicDBObject setQuery = new BasicDBObject();
- setQuery.append("$set", updateFields);
- UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
+ BasicDBObject updateFields = new BasicDBObject();
+ updateFields.append("department_id", 3);
+ updateFields.append("job", "Sales Manager");
+ BasicDBObject setQuery = new BasicDBObject();
+ setQuery.append("$set", updateFields);
+ UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
- System.out.println("updateResult:- " + updateResult);
- System.out.println("updateResult:- " + updateResult.getModifiedCount());
+ System.out.println("updateResult:- " + updateResult);
+ System.out.println("updateResult:- " + updateResult.getModifiedCount());
- }
+ }
}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
index 20af6d99cb..96dd086ed7 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
@@ -11,26 +11,25 @@ import com.mongodb.client.result.UpdateResult;
public class UpdateMultipleFields {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- //
- // Connect to cluster
- //
+ //
+ // Connect to cluster
+ //
- MongoClient mongoClient = new MongoClient("localhost", 27007);
- MongoDatabase database = mongoClient.getDatabase("baeldung");
- MongoCollection collection = database.getCollection("employee");
+ MongoClient mongoClient = new MongoClient("localhost", 27007);
+ MongoDatabase database = mongoClient.getDatabase("baeldung");
+ MongoCollection collection = database.getCollection("employee");
- //
- // Update query
- //
+ //
+ // Update query
+ //
- UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875),
- Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
+ UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
- System.out.println("updateResult:- " + updateResult);
- System.out.println("updateResult:- " + updateResult.getModifiedCount());
+ System.out.println("updateResult:- " + updateResult);
+ System.out.println("updateResult:- " + updateResult.getModifiedCount());
- }
+ }
-}
\ No newline at end of file
+}
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
index d1538d5312..d06de23423 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
@@ -2,8 +2,6 @@ package com.baeldung.update;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import org.bson.Document;
import org.junit.Before;
@@ -15,7 +13,6 @@ import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
-import com.mongodb.client.result.UpdateResult;
public class UpdateMultipleFieldsLiveTest {
@@ -30,8 +27,7 @@ public class UpdateMultipleFieldsLiveTest {
db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("employee");
- collection.insertOne(Document.parse(
- "{'employee_id':794875,'employee_name': 'David smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
+ collection.insertOne(Document.parse("{'employee_id':794875,'employee_name': 'David Smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
}
}
@@ -47,7 +43,8 @@ public class UpdateMultipleFieldsLiveTest {
collection.updateMany(searchQuery, setQuery);
- Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
+ Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
+ .first();
assertNotNull(nameDoc);
assertFalse(nameDoc.isEmpty());
@@ -62,10 +59,10 @@ public class UpdateMultipleFieldsLiveTest {
@Test
public void updateMultipleFieldsUsingDocument() {
- collection.updateMany(Filters.eq("employee_id", 794875),
- Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
+ collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
- Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
+ Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
+ .first();
assertNotNull(nameDoc);
assertFalse(nameDoc.isEmpty());
@@ -78,3 +75,4 @@ public class UpdateMultipleFieldsLiveTest {
}
}
+
From 7c3cbf0d4f1af133e3dd7882358b492d003bc889 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 4 Mar 2022 03:29:27 +0000
Subject: [PATCH 196/235] [BAEL-5245] Lombok ToString annotation (#11870)
---
.../com/baeldung/lombok/tostring/Account.java | 56 ++++++++++++++++
.../baeldung/lombok/tostring/AccountType.java | 9 +++
.../lombok/tostring/RewardAccount.java | 27 ++++++++
.../lombok/tostring/SavingAccount.java | 17 +++++
.../lombok/tostring/ToStringUnitTest.java | 66 +++++++++++++++++++
5 files changed, 175 insertions(+)
create mode 100644 lombok-2/src/main/java/com/baeldung/lombok/tostring/Account.java
create mode 100644 lombok-2/src/main/java/com/baeldung/lombok/tostring/AccountType.java
create mode 100644 lombok-2/src/main/java/com/baeldung/lombok/tostring/RewardAccount.java
create mode 100644 lombok-2/src/main/java/com/baeldung/lombok/tostring/SavingAccount.java
create mode 100644 lombok-2/src/test/java/com/baeldung/lombok/tostring/ToStringUnitTest.java
diff --git a/lombok-2/src/main/java/com/baeldung/lombok/tostring/Account.java b/lombok-2/src/main/java/com/baeldung/lombok/tostring/Account.java
new file mode 100644
index 0000000000..641ad1e1a3
--- /dev/null
+++ b/lombok-2/src/main/java/com/baeldung/lombok/tostring/Account.java
@@ -0,0 +1,56 @@
+package com.baeldung.lombok.tostring;
+
+import lombok.ToString;
+
+@ToString
+public class Account {
+
+ private String name;
+
+ // render this field before any others (the highest ranked)
+ @ToString.Include(rank = 1)
+ private String id;
+
+ @ToString.Exclude
+ private String accountNumber;
+
+ // automatically excluded
+ private String $ignored;
+
+ @ToString.Include
+ String description() {
+ return "Account description";
+ }
+
+ public String getAccountNumber() {
+ return accountNumber;
+ }
+
+ public void setAccountNumber(String accountNumber) {
+ this.accountNumber = accountNumber;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String get$ignored() {
+ return $ignored;
+ }
+
+ public void set$ignored(String value) {
+ this.$ignored = value;
+ }
+}
diff --git a/lombok-2/src/main/java/com/baeldung/lombok/tostring/AccountType.java b/lombok-2/src/main/java/com/baeldung/lombok/tostring/AccountType.java
new file mode 100644
index 0000000000..7f99b5ca35
--- /dev/null
+++ b/lombok-2/src/main/java/com/baeldung/lombok/tostring/AccountType.java
@@ -0,0 +1,9 @@
+package com.baeldung.lombok.tostring;
+
+import lombok.ToString;
+
+@ToString
+public enum AccountType {
+ CHECKING,
+ SAVING
+}
diff --git a/lombok-2/src/main/java/com/baeldung/lombok/tostring/RewardAccount.java b/lombok-2/src/main/java/com/baeldung/lombok/tostring/RewardAccount.java
new file mode 100644
index 0000000000..9ac9c6afa6
--- /dev/null
+++ b/lombok-2/src/main/java/com/baeldung/lombok/tostring/RewardAccount.java
@@ -0,0 +1,27 @@
+package com.baeldung.lombok.tostring;
+
+import lombok.ToString;
+
+@ToString
+public class RewardAccount extends Account {
+
+ private String rewardAccountId;
+
+ private Object[] relatedAccounts;
+
+ public String getRewardAccountId() {
+ return rewardAccountId;
+ }
+
+ public void setRewardAccountId(String rewardAccountId) {
+ this.rewardAccountId = rewardAccountId;
+ }
+
+ public Object[] getRelatedAccounts() {
+ return relatedAccounts;
+ }
+
+ public void setRelatedAccounts(Object[] relatedAccounts) {
+ this.relatedAccounts = relatedAccounts;
+ }
+}
diff --git a/lombok-2/src/main/java/com/baeldung/lombok/tostring/SavingAccount.java b/lombok-2/src/main/java/com/baeldung/lombok/tostring/SavingAccount.java
new file mode 100644
index 0000000000..dfba31cf27
--- /dev/null
+++ b/lombok-2/src/main/java/com/baeldung/lombok/tostring/SavingAccount.java
@@ -0,0 +1,17 @@
+package com.baeldung.lombok.tostring;
+
+import lombok.ToString;
+
+@ToString(callSuper = true)
+public class SavingAccount extends Account {
+
+ private String savingAccountId;
+
+ public String getSavingAccountId() {
+ return savingAccountId;
+ }
+
+ public void setSavingAccountId(String savingAccountId) {
+ this.savingAccountId = savingAccountId;
+ }
+}
diff --git a/lombok-2/src/test/java/com/baeldung/lombok/tostring/ToStringUnitTest.java b/lombok-2/src/test/java/com/baeldung/lombok/tostring/ToStringUnitTest.java
new file mode 100644
index 0000000000..cb56ad912d
--- /dev/null
+++ b/lombok-2/src/test/java/com/baeldung/lombok/tostring/ToStringUnitTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.lombok.tostring;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class ToStringUnitTest {
+
+ @Test
+ void whenPrintObject_thenOutputIsCorrect() {
+ Account account = new Account();
+ account.setId("12345");
+ account.setName("An account");
+ account.setAccountNumber("11111"); // should not be present in output
+ account.set$ignored("ignored value"); // should not be present in output
+
+ assertThat(account.toString())
+ .isEqualTo("Account(id=12345, name=An account, description=Account description)");
+ }
+
+ @Test
+ void whenPrintSubclassWithSuper_thenOutputIsCorrect() {
+ SavingAccount savingAccount = new SavingAccount();
+ savingAccount.setSavingAccountId("5678");
+ savingAccount.setId("12345");
+ savingAccount.setName("An account");
+
+ assertThat(savingAccount.toString())
+ .isEqualTo("SavingAccount(super=Account(id=12345, name=An account, description=Account description), savingAccountId=5678)");
+ }
+
+@Test
+void whenPrintArrays_thenOutputIsCorrect() {
+ RewardAccount account = new RewardAccount();
+ account.setRewardAccountId("12345");
+
+ // circular ref, just for demonstration
+ Object[] relatedAccounts = new Object[2];
+ relatedAccounts[0] = "54321";
+ relatedAccounts[1] = relatedAccounts;
+
+ account.setRelatedAccounts(relatedAccounts);
+
+ assertThat(account.toString())
+ .isEqualTo("RewardAccount(rewardAccountId=12345, relatedAccounts=[54321, [...]])");
+}
+
+ @Test
+ void whenPrintSubclassWithoutSuper_thenOutputIsCorrect() {
+ RewardAccount rewardAccount = new RewardAccount();
+ rewardAccount.setRewardAccountId("12345");
+
+ assertThat(rewardAccount.toString())
+ .isEqualTo("RewardAccount(rewardAccountId=12345, relatedAccounts=null)");
+ }
+
+ @Test
+ void whenPrintEnum_thenOutputIsCorrect() {
+ assertThat(AccountType.CHECKING.toString())
+ .isEqualTo("AccountType.CHECKING");
+
+ assertThat(AccountType.SAVING.toString())
+ .isEqualTo("AccountType.SAVING");
+ }
+
+}
From cd9147679944ccda9d5f9d77a68c815065d53ef4 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 4 Mar 2022 15:47:50 +0000
Subject: [PATCH 197/235] [JAVA-10335] Upgrade plugin version to fix muleesb
build
---
muleesb/pom.xml | 9 +++++----
pom.xml | 4 ++--
2 files changed, 7 insertions(+), 6 deletions(-)
diff --git a/muleesb/pom.xml b/muleesb/pom.xml
index f6cfa7d5d1..d78cebada2 100644
--- a/muleesb/pom.xml
+++ b/muleesb/pom.xml
@@ -108,7 +108,7 @@
org.mule.tools.maven
mule-maven-plugin
- 2.2.1
+ ${mule-maven-plugin.version}
standalone
${mule.version}
@@ -203,7 +203,7 @@
mulesoft-release
mulesoft release repository
default
- https://repository.mulesoft.org/releases/
+ https://repository.mulesoft.org/nexus/content/repositories/public/
false
@@ -212,9 +212,10 @@
3.9.0
- 1.2
+ 1.8
1.3.6
- 1.7
+ 1.10
+ 2.2.1
diff --git a/pom.xml b/pom.xml
index edc5302390..1243eb4522 100644
--- a/pom.xml
+++ b/pom.xml
@@ -518,7 +518,7 @@
micronaut
microprofile
msf4j
-
+ muleesb
mustache
mybatis
@@ -1001,7 +1001,7 @@
micronaut
microprofile
msf4j
-
+ muleesb
mustache
mybatis
From ef88a1803f7bd1b163b02dc54e6f93ecdc8c6150 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Fri, 4 Mar 2022 21:17:23 +0000
Subject: [PATCH 198/235] [JAVA-10432] Rename and enable testng-command-line
module
---
testing-modules/pom.xml | 1 +
.../{testng_command_line => testng-command-line}/README.md | 0
.../{testng_command_line => testng-command-line}/pom.xml | 6 +++---
.../java/com/baeldung/testng}/DateSerializerService.java | 2 +-
.../com/baeldung/testng}/DateSerializerServiceUnitTest.java | 3 ++-
.../{testng_command_line => testng-command-line}/testng.xml | 2 +-
6 files changed, 8 insertions(+), 6 deletions(-)
rename testing-modules/{testng_command_line => testng-command-line}/README.md (100%)
rename testing-modules/{testng_command_line => testng-command-line}/pom.xml (97%)
rename testing-modules/{testng_command_line/src/main/java/com/baeldung/testing_modules/testng_command_line => testng-command-line/src/main/java/com/baeldung/testng}/DateSerializerService.java (82%)
rename testing-modules/{testng_command_line/src/test/java/com/baeldung/testing_modules/testng_command_line => testng-command-line/src/test/java/com/baeldung/testng}/DateSerializerServiceUnitTest.java (87%)
rename testing-modules/{testng_command_line => testng-command-line}/testng.xml (67%)
diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml
index 58ea74484e..3d5db76827 100644
--- a/testing-modules/pom.xml
+++ b/testing-modules/pom.xml
@@ -45,6 +45,7 @@
testing-libraries-2
testing-libraries
testng
+ testng-command-line
xmlunit-2
zerocode
diff --git a/testing-modules/testng_command_line/README.md b/testing-modules/testng-command-line/README.md
similarity index 100%
rename from testing-modules/testng_command_line/README.md
rename to testing-modules/testng-command-line/README.md
diff --git a/testing-modules/testng_command_line/pom.xml b/testing-modules/testng-command-line/pom.xml
similarity index 97%
rename from testing-modules/testng_command_line/pom.xml
rename to testing-modules/testng-command-line/pom.xml
index 4c3af7621c..efc49b187d 100644
--- a/testing-modules/testng_command_line/pom.xml
+++ b/testing-modules/testng-command-line/pom.xml
@@ -3,10 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
- com.baeldung.testing_modules
- testng_command_line
+ testng-command-line
1.0.0-SNAPSHOT
+ testng-command-line
+
com.baeldung
testing-modules
diff --git a/testing-modules/testng_command_line/src/main/java/com/baeldung/testing_modules/testng_command_line/DateSerializerService.java b/testing-modules/testng-command-line/src/main/java/com/baeldung/testng/DateSerializerService.java
similarity index 82%
rename from testing-modules/testng_command_line/src/main/java/com/baeldung/testing_modules/testng_command_line/DateSerializerService.java
rename to testing-modules/testng-command-line/src/main/java/com/baeldung/testng/DateSerializerService.java
index 2c4c1f3a4b..a9a7cc4ee6 100644
--- a/testing-modules/testng_command_line/src/main/java/com/baeldung/testing_modules/testng_command_line/DateSerializerService.java
+++ b/testing-modules/testng-command-line/src/main/java/com/baeldung/testng/DateSerializerService.java
@@ -1,4 +1,4 @@
-package com.baeldung.testing_modules.testng_command_line;
+package com.baeldung.testng;
import java.text.SimpleDateFormat;
import java.util.Date;
diff --git a/testing-modules/testng_command_line/src/test/java/com/baeldung/testing_modules/testng_command_line/DateSerializerServiceUnitTest.java b/testing-modules/testng-command-line/src/test/java/com/baeldung/testng/DateSerializerServiceUnitTest.java
similarity index 87%
rename from testing-modules/testng_command_line/src/test/java/com/baeldung/testing_modules/testng_command_line/DateSerializerServiceUnitTest.java
rename to testing-modules/testng-command-line/src/test/java/com/baeldung/testng/DateSerializerServiceUnitTest.java
index 4deb0297f0..2b9a9a0925 100644
--- a/testing-modules/testng_command_line/src/test/java/com/baeldung/testing_modules/testng_command_line/DateSerializerServiceUnitTest.java
+++ b/testing-modules/testng-command-line/src/test/java/com/baeldung/testng/DateSerializerServiceUnitTest.java
@@ -1,7 +1,8 @@
-package com.baeldung.testing_modules.testng_command_line;
+package com.baeldung.testng;
import java.util.Date;
+import com.baeldung.testng.DateSerializerService;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
diff --git a/testing-modules/testng_command_line/testng.xml b/testing-modules/testng-command-line/testng.xml
similarity index 67%
rename from testing-modules/testng_command_line/testng.xml
rename to testing-modules/testng-command-line/testng.xml
index eca48a6d39..4e029f9dc6 100644
--- a/testing-modules/testng_command_line/testng.xml
+++ b/testing-modules/testng-command-line/testng.xml
@@ -4,7 +4,7 @@
+ name="com.baeldung.testng.DateSerializerServiceUnitTest" />
From 3687b7bc643799f8221bf703a5168c7af36e389a Mon Sep 17 00:00:00 2001
From: andresluzu
Date: Fri, 4 Mar 2022 21:25:02 -0500
Subject: [PATCH 199/235] BAEL-5335: Introduction to OAuth2RestTemplate
(#11849)
---
.../oauth2resttemplate/AppController.java | 32 ++++++++
.../oauth2resttemplate/GithubRepo.java | 22 ++++++
.../oauth2resttemplate/SecurityConfig.java | 73 +++++++++++++++++++
...SpringSecurityOauth2ClientApplication.java | 15 ++++
...pplication-oauth2-rest-template.properties | 9 +++
.../templates/oauth2resttemplate/error.html | 9 +++
.../templates/oauth2resttemplate/home.html | 18 +++++
.../templates/oauth2resttemplate/index.html | 16 ++++
.../oauth2resttemplate/repositories.html | 14 ++++
9 files changed, 208 insertions(+)
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/AppController.java
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/GithubRepo.java
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SpringSecurityOauth2ClientApplication.java
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/resources/application-oauth2-rest-template.properties
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/error.html
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/home.html
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/index.html
create mode 100644 spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/repositories.html
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/AppController.java b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/AppController.java
new file mode 100644
index 0000000000..3c3efd950f
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/AppController.java
@@ -0,0 +1,32 @@
+package com.baeldung.oauth2resttemplate;
+
+import org.springframework.security.oauth2.client.OAuth2RestTemplate;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+
+import java.security.Principal;
+import java.util.Collection;
+
+@Controller
+public class AppController {
+
+ OAuth2RestTemplate restTemplate;
+
+ public AppController(OAuth2RestTemplate restTemplate) {
+ this.restTemplate = restTemplate;
+ }
+
+ @GetMapping("/home")
+ public String welcome(Model model, Principal principal) {
+ model.addAttribute("name", principal.getName());
+ return "home";
+ }
+
+ @GetMapping("/repos")
+ public String repos(Model model) {
+ Collection repos = restTemplate.getForObject("https://api.github.com/user/repos", Collection.class);
+ model.addAttribute("repos", repos);
+ return "repositories";
+ }
+}
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/GithubRepo.java b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/GithubRepo.java
new file mode 100644
index 0000000000..48cc05c1de
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/GithubRepo.java
@@ -0,0 +1,22 @@
+package com.baeldung.oauth2resttemplate;
+
+public class GithubRepo {
+ Long id;
+ String 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;
+ }
+}
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java
new file mode 100644
index 0000000000..fa274d1c9b
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java
@@ -0,0 +1,73 @@
+package com.baeldung.oauth2resttemplate;
+
+import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
+import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.Ordered;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.oauth2.client.OAuth2ClientContext;
+import org.springframework.security.oauth2.client.OAuth2RestTemplate;
+import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
+import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
+import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
+import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
+
+import javax.servlet.Filter;
+
+@Configuration
+@EnableOAuth2Client
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+ OAuth2ClientContext oauth2ClientContext;
+
+ public SecurityConfig(OAuth2ClientContext oauth2ClientContext) {
+ this.oauth2ClientContext = oauth2ClientContext;
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests().antMatchers("/", "/login**", "/error**")
+ .permitAll().anyRequest().authenticated()
+ .and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
+ .and().addFilterBefore(oauth2ClientFilter(), BasicAuthenticationFilter.class);
+ }
+
+ @Bean
+ public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
+ FilterRegistrationBean registration = new FilterRegistrationBean<>();
+ registration.setFilter(filter);
+ registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
+ return registration;
+ }
+
+ @Bean
+ public OAuth2RestTemplate restTemplate() {
+ return new OAuth2RestTemplate(githubClient(), oauth2ClientContext);
+ }
+
+ @Bean
+ @ConfigurationProperties("github.client")
+ public AuthorizationCodeResourceDetails githubClient() {
+ return new AuthorizationCodeResourceDetails();
+ }
+
+ private Filter oauth2ClientFilter() {
+ OAuth2ClientAuthenticationProcessingFilter oauth2ClientFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github");
+ OAuth2RestTemplate restTemplate = restTemplate();
+ oauth2ClientFilter.setRestTemplate(restTemplate);
+ UserInfoTokenServices tokenServices = new UserInfoTokenServices(githubResource().getUserInfoUri(), githubClient().getClientId());
+ tokenServices.setRestTemplate(restTemplate);
+ oauth2ClientFilter.setTokenServices(tokenServices);
+ return oauth2ClientFilter;
+ }
+
+ @Bean
+ @ConfigurationProperties("github.resource")
+ public ResourceServerProperties githubResource() {
+ return new ResourceServerProperties();
+ }
+}
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SpringSecurityOauth2ClientApplication.java b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SpringSecurityOauth2ClientApplication.java
new file mode 100644
index 0000000000..846169e5bf
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/java/com/baeldung/oauth2resttemplate/SpringSecurityOauth2ClientApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.oauth2resttemplate;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.PropertySource;
+
+@SpringBootApplication
+@PropertySource("classpath:application-oauth2-rest-template.properties")
+public class SpringSecurityOauth2ClientApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringSecurityOauth2ClientApplication.class, args);
+ }
+
+}
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/resources/application-oauth2-rest-template.properties b/spring-security-modules/spring-5-security-oauth/src/main/resources/application-oauth2-rest-template.properties
new file mode 100644
index 0000000000..15d34b76be
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/resources/application-oauth2-rest-template.properties
@@ -0,0 +1,9 @@
+github.client.clientId=[CLIENT_ID]
+github.client.clientSecret=[CLIENT_SECRET]
+github.client.userAuthorizationUri=https://github.com/login/oauth/authorize
+github.client.accessTokenUri=https://github.com/login/oauth/access_token
+github.client.clientAuthenticationScheme=form
+
+github.resource.userInfoUri=https://api.github.com/user
+
+spring.thymeleaf.prefix=classpath:/templates/oauth2resttemplate/
\ No newline at end of file
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/error.html b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/error.html
new file mode 100644
index 0000000000..45bcddf654
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/error.html
@@ -0,0 +1,9 @@
+
+
+
+ Error
+
+
+ An error occurred.
+
+
\ No newline at end of file
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/home.html b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/home.html
new file mode 100644
index 0000000000..3eba3615d6
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/home.html
@@ -0,0 +1,18 @@
+
+
+
+ Home
+
+
+
+ Welcome [[${name}]]
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/index.html b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/index.html
new file mode 100644
index 0000000000..4db3b78d23
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/index.html
@@ -0,0 +1,16 @@
+
+
+
+ OAuth2Client
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/repositories.html b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/repositories.html
new file mode 100644
index 0000000000..1eabf2270f
--- /dev/null
+++ b/spring-security-modules/spring-5-security-oauth/src/main/resources/templates/oauth2resttemplate/repositories.html
@@ -0,0 +1,14 @@
+
+
+
+ Repositories
+
+
+
+
Repos
+
+
+
+
\ No newline at end of file
From 9da940a252d11c7489101232c76c2f710fa2bbed Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Sun, 6 Mar 2022 00:41:44 +0000
Subject: [PATCH 200/235] [JAVA-10398] Rename intermittent failing test to
ManualTest
---
...st.java => IllegalMonitorStateExceptionManualTest.java} | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
rename core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/{IllegalMonitorStateExceptionUnitTest.java => IllegalMonitorStateExceptionManualTest.java} (91%)
diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionManualTest.java
similarity index 91%
rename from core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java
rename to core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionManualTest.java
index 857ab02c13..31807255e8 100644
--- a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java
+++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionManualTest.java
@@ -7,7 +7,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
-public class IllegalMonitorStateExceptionUnitTest {
+/**
+ * Needs to be run manually in order to demonstrate the IllegalMonitorStateException scenarios.
+ *
+ * There are some intermittent test failures in Jenkins that require further investigation.
+ */
+public class IllegalMonitorStateExceptionManualTest {
@Test
void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
From dafb4d1f580dfb30b3c85f7b7c9bb7c62449e260 Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Sun, 6 Mar 2022 09:59:16 +0530
Subject: [PATCH 201/235] BAEL-5401: Update Fields of Documents in MongoDB
Using the Java Driver (#11889)
---
.../baeldung/mongo/update/UpdateFields.java | 128 ++++++++++++++++
.../baeldung/update/UpdateFieldLiveTest.java | 143 ++++++++++++++++++
2 files changed, 271 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
new file mode 100644
index 0000000000..a1b051e74c
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
@@ -0,0 +1,128 @@
+package com.baeldung.mongo.update;
+
+import org.bson.Document;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.FindOneAndReplaceOptions;
+import com.mongodb.client.model.FindOneAndUpdateOptions;
+import com.mongodb.client.model.ReturnDocument;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class UpdateFields {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase database;
+ private static MongoCollection collection;
+
+ public static void updateOne() {
+
+ UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
+
+ System.out.println("updateResult:- " + updateResult);
+ }
+
+ public static void updateMany() {
+
+ UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
+
+ System.out.println("updateResult:- " + updateResult);
+
+ }
+
+ public static void replaceOne() {
+
+ Document replaceDocument = new Document();
+ replaceDocument.append("student_id", 8764)
+ .append("student_name", "Paul Starc")
+ .append("address", "Hostel 3")
+ .append("age", 18)
+ .append("roll_no", 199406);
+
+ UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
+
+ System.out.println("updateResult:- " + updateResult);
+
+ }
+
+ public static void findOneAndReplace() {
+
+ Document replaceDocument = new Document();
+ replaceDocument.append("student_id", 8764)
+ .append("student_name", "Paul Starc")
+ .append("address", "Hostel 4")
+ .append("age", 18)
+ .append("roll_no", 199406);
+ Document sort = new Document("roll_no", 1);
+ Document projection = new Document("_id", 0).append("student_id", 1)
+ .append("address", 1);
+ Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
+ .sort(sort)
+ .projection(projection)
+ .returnDocument(ReturnDocument.AFTER));
+
+ System.out.println("resultDocument:- " + resultDocument);
+
+ }
+
+ public static void findOneAndUpdate() {
+
+ Document sort = new Document("roll_no", 1);
+ Document projection = new Document("_id", 0).append("student_id", 1)
+ .append("address", 1);
+ Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
+ .sort(sort)
+ .projection(projection)
+ .returnDocument(ReturnDocument.AFTER));
+
+ System.out.println("resultDocument:- " + resultDocument);
+ }
+
+ public static void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ database = mongoClient.getDatabase("baeldung");
+ collection = database.getCollection("student");
+
+ }
+ }
+
+ public static void main(String[] args) {
+
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
+ setup();
+
+ //
+ // Update a document using updateOne method
+ //
+ updateOne();
+
+ //
+ // Update documents using updateMany method
+ //
+ updateMany();
+
+ //
+ // replace a document using replaceOne method
+ //
+ replaceOne();
+
+ //
+ // replace a document using findOneAndReplace method
+ //
+ findOneAndReplace();
+
+ //
+ // Update a document using findOneAndUpdate method
+ //
+ findOneAndUpdate();
+
+ }
+
+}
+
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
new file mode 100644
index 0000000000..47114e1f1a
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
@@ -0,0 +1,143 @@
+package com.baeldung.update;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+import org.bson.Document;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.FindOneAndReplaceOptions;
+import com.mongodb.client.model.FindOneAndUpdateOptions;
+import com.mongodb.client.model.ReturnDocument;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class UpdateFieldLiveTest {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase db;
+ private static MongoCollection collection;
+
+ @BeforeClass
+ public static void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ db = mongoClient.getDatabase("baeldung");
+ collection = db.getCollection("student");
+
+ collection.insertOne(Document.parse("{ \"student_id\": 8764,\"student_name\": \"Paul Starc\",\"address\": \"Hostel 1\",\"age\": 16,\"roll_no\":199406}"));
+ }
+ }
+
+ @Test
+ public void updateOne() {
+
+ UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
+
+ Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ String address = studentDetail.getString("address");
+ String expectedAdderess = "Hostel 2";
+
+ assertEquals(expectedAdderess, address);
+ }
+
+ @Test
+ public void updateMany() {
+
+ UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
+
+ Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ Boolean review = studentDetail.getBoolean("Review");
+ Boolean expectedAdderess = true;
+
+ assertEquals(expectedAdderess, review);
+
+ }
+
+ @Test
+ public void replaceOne() {
+
+ Document replaceDocument = new Document();
+ replaceDocument.append("student_id", 8764)
+ .append("student_name", "Paul Starc")
+ .append("address", "Hostel 3")
+ .append("age", 18)
+ .append("roll_no", 199406);
+
+ UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
+
+ Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ Integer age = studentDetail.getInteger("age");
+ Integer expectedAge = 18;
+
+ assertEquals(expectedAge, age);
+
+ }
+
+ @Test
+ public void findOneAndReplace() {
+
+ Document replaceDocument = new Document();
+ replaceDocument.append("student_id", 8764)
+ .append("student_name", "Paul Starc")
+ .append("address", "Hostel 4")
+ .append("age", 18)
+ .append("roll_no", 199406);
+ Document sort = new Document("roll_no", 1);
+ Document projection = new Document("_id", 0).append("student_id", 1)
+ .append("address", 1);
+ Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
+ .sort(sort)
+ .projection(projection)
+ .returnDocument(ReturnDocument.AFTER));
+
+ Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ Integer age = studentDetail.getInteger("age");
+ Integer expectedAge = 18;
+
+ assertEquals(expectedAge, age);
+
+ }
+
+ @Test
+ public void findOneAndUpdate() {
+
+ Document sort = new Document("roll_no", 1);
+ Document projection = new Document("_id", 0).append("student_id", 1)
+ .append("address", 1);
+ Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
+ .sort(sort)
+ .projection(projection)
+ .returnDocument(ReturnDocument.AFTER));
+
+ Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ }
+
+}
+
From f0d831095be920798663ede3d8a1a10dbc23280f Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 6 Mar 2022 11:56:55 +0500
Subject: [PATCH 202/235] Updated README.md
Fixed link for Introduction to Awaitility, from https://www.baeldung.com/awaitlity-testing to https://www.baeldung.com/awaitility-testing
---
libraries-testing/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libraries-testing/README.md b/libraries-testing/README.md
index 5498c73094..880c3dd2e6 100644
--- a/libraries-testing/README.md
+++ b/libraries-testing/README.md
@@ -8,7 +8,7 @@ This module contains articles about test libraries.
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
-- [Introduction to Awaitility](https://www.baeldung.com/awaitlity-testing)
+- [Introduction to Awaitility](https://www.baeldung.com/awaitility-testing)
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit)
From 20b50e8bea8f6966ec507e6c0444204464c4fcce Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 6 Mar 2022 12:54:13 +0500
Subject: [PATCH 203/235] Updated README.md
For Enabling Logging for Apache HttpClient, Correct URL from https://www.baeldung.com/java-httpclient-enable-logging to https://www.baeldung.com/apache-httpclient-enable-logging
---
httpclient-2/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/httpclient-2/README.md b/httpclient-2/README.md
index 7c2d5862bd..4f9805063c 100644
--- a/httpclient-2/README.md
+++ b/httpclient-2/README.md
@@ -11,5 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [How to Set TLS Version in Apache HttpClient](https://www.baeldung.com/apache-httpclient-tls)
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
-- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/java-httpclient-enable-logging)
+- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
- More articles: [[<-- prev]](../httpclient)
From 612bb329e572003a08d1cc028e3fc0ff8a87730d Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Sun, 6 Mar 2022 13:04:52 +0500
Subject: [PATCH 204/235] Updated README.md
For Adding Parameters to HttpClient Requests, corrected link from https://www.baeldung.com/java-httpclient-parameters to https://www.baeldung.com/apache-httpclient-parameters
---
httpclient-simple/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/httpclient-simple/README.md b/httpclient-simple/README.md
index 93fb22ac1e..8875af1ea0 100644
--- a/httpclient-simple/README.md
+++ b/httpclient-simple/README.md
@@ -11,7 +11,7 @@ This module contains articles about HTTPClient that are part of the HTTPClient E
- [Custom HTTP Header with the HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
- [HttpClient Basic Authentication](https://www.baeldung.com/httpclient-4-basic-authentication)
- [Posting with HttpClient](https://www.baeldung.com/httpclient-post-http-request)
-- [Adding Parameters to HttpClient Requests](https://www.baeldung.com/java-httpclient-parameters)
+- [Adding Parameters to HttpClient Requests](https://www.baeldung.com/apache-httpclient-parameters)
### Running the Tests
From 3fbad0691d0276daa18c613c30e970c64b0b98ab Mon Sep 17 00:00:00 2001
From: alemoles
Date: Mon, 7 Mar 2022 01:34:14 -0500
Subject: [PATCH 205/235] BAEL-5418 - Convert long to int type in Java (#8)
(#11895)
---
java-numbers-4/pom.xml | 5 +++
.../convertLongToInt/ConvertLongToInt.java | 44 +++++++++++++++++++
.../ConvertLongToIntUnitTest.java | 23 ++++++++++
3 files changed, 72 insertions(+)
create mode 100644 java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java
create mode 100644 java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java
diff --git a/java-numbers-4/pom.xml b/java-numbers-4/pom.xml
index 9b2e799840..40fe17cc0d 100644
--- a/java-numbers-4/pom.xml
+++ b/java-numbers-4/pom.xml
@@ -25,6 +25,11 @@
${commons-lang3.version}
test
+
+ com.google.guava
+ guava
+ ${guava.version}
+
diff --git a/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java b/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java
new file mode 100644
index 0000000000..0638505c2d
--- /dev/null
+++ b/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java
@@ -0,0 +1,44 @@
+package com.baeldung.convertLongToInt;
+
+import java.math.BigDecimal;
+import java.util.Optional;
+import java.util.function.Function;
+
+import com.google.common.primitives.Ints;
+
+public class ConvertLongToInt {
+
+ static Function convert = val -> Optional.ofNullable(val)
+ .map(Long::intValue)
+ .orElse(null);
+
+ public static int longToIntCast(long number) {
+ return (int) number;
+ }
+
+ public static int longToIntJavaWithMath(long number) {
+ return Math.toIntExact(number);
+ }
+
+ public static int longToIntJavaWithLambda(long number) {
+ return convert.apply(number);
+ }
+
+ public static int longToIntBoxingValues(long number) {
+ return Long.valueOf(number)
+ .intValue();
+ }
+
+ public static int longToIntGuava(long number) {
+ return Ints.checkedCast(number);
+ }
+
+ public static int longToIntGuavaSaturated(long number) {
+ return Ints.saturatedCast(number);
+ }
+
+ public static int longToIntWithBigDecimal(long number) {
+ return new BigDecimal(number).intValueExact();
+ }
+
+}
diff --git a/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java
new file mode 100644
index 0000000000..38fa37b664
--- /dev/null
+++ b/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java
@@ -0,0 +1,23 @@
+package com.baeldung.convertLongToInt;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class ConvertLongToIntUnitTest {
+
+ @Test
+ void longToInt() {
+ long number = 186762L;
+ int expected = 186762;
+
+ assertEquals(expected, ConvertLongToInt.longToIntCast(number));
+ assertEquals(expected, ConvertLongToInt.longToIntJavaWithMath(number));
+ assertEquals(expected, ConvertLongToInt.longToIntJavaWithLambda(number));
+ assertEquals(expected, ConvertLongToInt.longToIntBoxingValues(number));
+ assertEquals(expected, ConvertLongToInt.longToIntGuava(number));
+ assertEquals(expected, ConvertLongToInt.longToIntGuavaSaturated(number));
+ assertEquals(expected, ConvertLongToInt.longToIntWithBigDecimal(number));
+ }
+
+}
\ No newline at end of file
From 08e84780bfcd9170d5fb207a5de0c6d6328cc16a Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 17:50:33 +0500
Subject: [PATCH 206/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-read-file-into-map
---
core-java-modules/core-java-io-4/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-io-4/README.md b/core-java-modules/core-java-io-4/README.md
index be58338fd8..39b820b3ba 100644
--- a/core-java-modules/core-java-io-4/README.md
+++ b/core-java-modules/core-java-io-4/README.md
@@ -7,4 +7,5 @@ This module contains articles about core Java input and output (IO)
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
+- [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map)
- [[<-- Prev]](/core-java-modules/core-java-io-3)
From 6fe59e7aeab0385c05d423b948d46e0ee06412ea Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 17:54:47 +0500
Subject: [PATCH 207/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-rock-paper-scissors
---
core-java-modules/core-java-8-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md
index 12a060ccfe..c0bc63f21f 100644
--- a/core-java-modules/core-java-8-2/README.md
+++ b/core-java-modules/core-java-8-2/README.md
@@ -9,4 +9,5 @@ This module contains articles about Java 8 core features
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
+- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [[<-- Prev]](/core-java-modules/core-java-8)
From 3f71dcc5c757e3a40dd07c56caddb5df3ca22d8f Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 17:57:11 +0500
Subject: [PATCH 208/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-call-graphql-service
---
graphql/graphql-java/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/graphql/graphql-java/README.md b/graphql/graphql-java/README.md
index e3fd818400..f37506a9fd 100644
--- a/graphql/graphql-java/README.md
+++ b/graphql/graphql-java/README.md
@@ -5,3 +5,4 @@ This module contains articles about GraphQL with Java
## Relevant articles:
- [Introduction to GraphQL](https://www.baeldung.com/graphql)
+- [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service)
From b86e50ede4ebaac6d1f1f3bfe6ad5b2e73f3a1c8 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 18:00:52 +0500
Subject: [PATCH 209/235] Updated README.md
added link back to the article: https://www.baeldung.com/java-excel-find-last-row
---
apache-poi-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md
index 2fd0135b11..f55ec7eb6a 100644
--- a/apache-poi-2/README.md
+++ b/apache-poi-2/README.md
@@ -9,4 +9,5 @@ This module contains articles about Apache POI.
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
+- [Finding the Last Row in an Excel Spreadsheet From Java](https://www.baeldung.com/java-excel-find-last-row)
- More articles: [[<-- prev]](../apache-poi)
From dc6357d98eab194031d35ea7664b4bdfcafe1150 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 19:22:54 +0500
Subject: [PATCH 210/235] Updated README.md
added link back to the article: https://www.baeldung.com/mongodb-update-multiple-fields
---
persistence-modules/java-mongodb/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md
index fe30c2999e..2b7fcd3de0 100644
--- a/persistence-modules/java-mongodb/README.md
+++ b/persistence-modules/java-mongodb/README.md
@@ -13,3 +13,4 @@ This module contains articles about MongoDB in Java.
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
+- [Update Multiple Fields in a MongoDB Document](https://www.baeldung.com/mongodb-update-multiple-fields)
From db95e7bb6ad8ce3528ec2a1e7cef836b70949b53 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 19:27:14 +0500
Subject: [PATCH 211/235] Updated README.md
added link back to the article: https://www.baeldung.com/lombok-tostring
---
lombok-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/lombok-2/README.md b/lombok-2/README.md
index 25d097a7ea..650dc5ddab 100644
--- a/lombok-2/README.md
+++ b/lombok-2/README.md
@@ -7,4 +7,5 @@ This module contains articles about Project Lombok.
- [Using Lombok’s @Accessors Annotation](https://www.baeldung.com/lombok-accessors)
- [Declaring Val and Var Variables in Lombok](https://www.baeldung.com/java-lombok-val-var)
- [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations)
+- [Lombok's @ToString Annotation](https://www.baeldung.com/lombok-tostring)
- More articles: [[<-- prev]](../lombok)
From 3d92ca2c4169f0d206d20e8f002f5fc325bf47b3 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 19:31:42 +0500
Subject: [PATCH 212/235] Updated README.md
added a link back to the article: https://www.baeldung.com/java-bytebuffer
---
core-java-modules/core-java-nio-2/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md
index 9152a494d8..c405cb7c77 100644
--- a/core-java-modules/core-java-nio-2/README.md
+++ b/core-java-modules/core-java-nio-2/README.md
@@ -12,4 +12,5 @@ This module contains articles about core Java non-blocking input and output (IO)
- [Java NIO DatagramChannel](https://www.baeldung.com/java-nio-datagramchannel)
- [Java – Path vs File](https://www.baeldung.com/java-path-vs-file)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
+- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
- [[<-- Prev]](/core-java-modules/core-java-nio)
From 32c7041a18d3a649750c9f851710bd7dfb10b099 Mon Sep 17 00:00:00 2001
From: Asjad J <97493880+Asjad-J@users.noreply.github.com>
Date: Mon, 7 Mar 2022 19:35:42 +0500
Subject: [PATCH 213/235] Updated README.md
added a link back to the article: https://www.baeldung.com/spring-oauth2resttemplate
---
spring-security-modules/spring-5-security-oauth/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/spring-security-modules/spring-5-security-oauth/README.md b/spring-security-modules/spring-5-security-oauth/README.md
index 35e64da639..e5b149fee6 100644
--- a/spring-security-modules/spring-5-security-oauth/README.md
+++ b/spring-security-modules/spring-5-security-oauth/README.md
@@ -8,3 +8,4 @@ This module contains articles about Spring 5 OAuth Security
- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor)
- [Customizing Authorization and Token Requests with Spring Security 5.1 Client](https://www.baeldung.com/spring-security-custom-oauth-requests)
- [Social Login with Spring Security in a Jersey Application](https://www.baeldung.com/spring-security-social-login-jersey)
+- [Introduction to OAuth2RestTemplate](https://www.baeldung.com/spring-oauth2resttemplate)
From 0f82785c28f01746abd64065d717e261ed260227 Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Mon, 7 Mar 2022 15:40:21 +0100
Subject: [PATCH 214/235] JAVA-10334: Disable failing test
---
.../spring/statemachine/StateMachineIntegrationTest.java | 2 ++
1 file changed, 2 insertions(+)
diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java
index aab07225a3..5909340a82 100644
--- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java
+++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java
@@ -3,6 +3,7 @@ package com.baeldung.spring.statemachine;
import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -36,6 +37,7 @@ public class StateMachineIntegrationTest {
assertEquals("S2", stateMachine.getState().getId());
}
+ @Ignore("Fixing in JAVA-9808")
@Test
public void whenSimpleStringMachineActionState_thenActionExecuted() {
From 53afccfe3a5cfb746e70559d8337b215eb15944b Mon Sep 17 00:00:00 2001
From: Olsi Seferi <72546616+olsiseferi@users.noreply.github.com>
Date: Mon, 7 Mar 2022 17:58:13 +0100
Subject: [PATCH 215/235] ADDED FORWARD PROXY CONFIGURATION AND CLIENT (#11708)
---
nginx-forward-proxy/forward | 7 +
nginx-forward-proxy/package-lock.json | 339 ++++++++++++++++++++++++++
nginx-forward-proxy/package.json | 14 ++
nginx-forward-proxy/proxytest.js | 11 +
4 files changed, 371 insertions(+)
create mode 100644 nginx-forward-proxy/forward
create mode 100644 nginx-forward-proxy/package-lock.json
create mode 100644 nginx-forward-proxy/package.json
create mode 100644 nginx-forward-proxy/proxytest.js
diff --git a/nginx-forward-proxy/forward b/nginx-forward-proxy/forward
new file mode 100644
index 0000000000..4e8ca8b29f
--- /dev/null
+++ b/nginx-forward-proxy/forward
@@ -0,0 +1,7 @@
+server {
+ listen 8888;
+ location / {
+ resolver 8.8.8.8;
+ proxy_pass http://$http_host$uri$is_args$args;
+ }
+}
\ No newline at end of file
diff --git a/nginx-forward-proxy/package-lock.json b/nginx-forward-proxy/package-lock.json
new file mode 100644
index 0000000000..b70787ec67
--- /dev/null
+++ b/nginx-forward-proxy/package-lock.json
@@ -0,0 +1,339 @@
+{
+ "name": "nginx-forward-proxy",
+ "version": "1.0.0",
+ "lockfileVersion": 1,
+ "requires": true,
+ "dependencies": {
+ "ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "asn1": {
+ "version": "0.2.6",
+ "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
+ "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
+ "requires": {
+ "safer-buffer": "~2.1.0"
+ }
+ },
+ "assert-plus": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
+ "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU="
+ },
+ "asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
+ },
+ "aws-sign2": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
+ "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg="
+ },
+ "aws4": {
+ "version": "1.11.0",
+ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz",
+ "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA=="
+ },
+ "bcrypt-pbkdf": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
+ "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=",
+ "requires": {
+ "tweetnacl": "^0.14.3"
+ }
+ },
+ "caseless": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
+ "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw="
+ },
+ "combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "requires": {
+ "delayed-stream": "~1.0.0"
+ }
+ },
+ "core-util-is": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
+ "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
+ },
+ "dashdash": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
+ "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=",
+ "requires": {
+ "assert-plus": "^1.0.0"
+ }
+ },
+ "delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
+ },
+ "ecc-jsbn": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
+ "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=",
+ "requires": {
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.1.0"
+ }
+ },
+ "extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="
+ },
+ "extsprintf": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
+ "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU="
+ },
+ "fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
+ },
+ "fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="
+ },
+ "forever-agent": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
+ "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE="
+ },
+ "form-data": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
+ "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
+ "requires": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.6",
+ "mime-types": "^2.1.12"
+ }
+ },
+ "getpass": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
+ "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=",
+ "requires": {
+ "assert-plus": "^1.0.0"
+ }
+ },
+ "har-schema": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
+ "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI="
+ },
+ "har-validator": {
+ "version": "5.1.5",
+ "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz",
+ "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==",
+ "requires": {
+ "ajv": "^6.12.3",
+ "har-schema": "^2.0.0"
+ }
+ },
+ "http-signature": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
+ "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=",
+ "requires": {
+ "assert-plus": "^1.0.0",
+ "jsprim": "^1.2.2",
+ "sshpk": "^1.7.0"
+ }
+ },
+ "is-typedarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
+ "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo="
+ },
+ "isstream": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",
+ "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo="
+ },
+ "jsbn": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
+ "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM="
+ },
+ "json-schema": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="
+ },
+ "json-stringify-safe": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
+ "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus="
+ },
+ "jsprim": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
+ "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
+ "requires": {
+ "assert-plus": "1.0.0",
+ "extsprintf": "1.3.0",
+ "json-schema": "0.4.0",
+ "verror": "1.10.0"
+ }
+ },
+ "mime-db": {
+ "version": "1.51.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz",
+ "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g=="
+ },
+ "mime-types": {
+ "version": "2.1.34",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz",
+ "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==",
+ "requires": {
+ "mime-db": "1.51.0"
+ }
+ },
+ "oauth-sign": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
+ "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ=="
+ },
+ "performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns="
+ },
+ "psl": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz",
+ "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ=="
+ },
+ "punycode": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",
+ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A=="
+ },
+ "qs": {
+ "version": "6.5.3",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
+ "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA=="
+ },
+ "request": {
+ "version": "2.88.2",
+ "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
+ "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
+ "requires": {
+ "aws-sign2": "~0.7.0",
+ "aws4": "^1.8.0",
+ "caseless": "~0.12.0",
+ "combined-stream": "~1.0.6",
+ "extend": "~3.0.2",
+ "forever-agent": "~0.6.1",
+ "form-data": "~2.3.2",
+ "har-validator": "~5.1.3",
+ "http-signature": "~1.2.0",
+ "is-typedarray": "~1.0.0",
+ "isstream": "~0.1.2",
+ "json-stringify-safe": "~5.0.1",
+ "mime-types": "~2.1.19",
+ "oauth-sign": "~0.9.0",
+ "performance-now": "^2.1.0",
+ "qs": "~6.5.2",
+ "safe-buffer": "^5.1.2",
+ "tough-cookie": "~2.5.0",
+ "tunnel-agent": "^0.6.0",
+ "uuid": "^3.3.2"
+ }
+ },
+ "safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
+ },
+ "safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
+ },
+ "sshpk": {
+ "version": "1.17.0",
+ "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz",
+ "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==",
+ "requires": {
+ "asn1": "~0.2.3",
+ "assert-plus": "^1.0.0",
+ "bcrypt-pbkdf": "^1.0.0",
+ "dashdash": "^1.12.0",
+ "ecc-jsbn": "~0.1.1",
+ "getpass": "^0.1.1",
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.0.2",
+ "tweetnacl": "~0.14.0"
+ }
+ },
+ "tough-cookie": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
+ "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
+ "requires": {
+ "psl": "^1.1.28",
+ "punycode": "^2.1.1"
+ }
+ },
+ "tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=",
+ "requires": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "tweetnacl": {
+ "version": "0.14.5",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
+ "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q="
+ },
+ "uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "requires": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "uuid": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
+ "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A=="
+ },
+ "verror": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
+ "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=",
+ "requires": {
+ "assert-plus": "^1.0.0",
+ "core-util-is": "1.0.2",
+ "extsprintf": "^1.2.0"
+ }
+ }
+ }
+}
diff --git a/nginx-forward-proxy/package.json b/nginx-forward-proxy/package.json
new file mode 100644
index 0000000000..4691542900
--- /dev/null
+++ b/nginx-forward-proxy/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "nginx-forward-proxy",
+ "version": "1.0.0",
+ "description": "Simple Client for Connecting to a Forward Proxy",
+ "main": "proxytest.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "author": "Olsi Seferi",
+ "license": "ISC",
+ "dependencies": {
+ "request": "^2.88.2"
+ }
+}
diff --git a/nginx-forward-proxy/proxytest.js b/nginx-forward-proxy/proxytest.js
new file mode 100644
index 0000000000..dc55ef6620
--- /dev/null
+++ b/nginx-forward-proxy/proxytest.js
@@ -0,0 +1,11 @@
+var request = require('request');
+
+request({
+ 'url':'http://www.google.com/',
+ 'method': "GET",
+ 'proxy':'http://192.168.100.40:8888'
+},function (error, response, body) {
+ if (!error && response.statusCode == 200) {
+ console.log(body);
+ }
+})
From 2859935089915c46036c7d27b29c6913a2efe156 Mon Sep 17 00:00:00 2001
From: Haroon Khan
Date: Mon, 7 Mar 2022 16:32:43 +0000
Subject: [PATCH 216/235] [JAVA-10463] Split apache-poi module
---
apache-poi-2/README.md | 1 +
apache-poi-2/pom.xml | 2 +-
.../poi/excel/setformula/ExcelFormula.java | 51 ++++---
.../poi/excel/setformula/SetFormulaTest.xlsx | Bin
.../setformula/ExcelFormulaUnitTest.java | 11 +-
apache-poi/README.md | 1 -
.../baeldung/poi/excel/ExcelUtility.java.orig | 128 ------------------
.../poi/excel/ExcelUtilityUnitTest.java.orig | 112 ---------------
8 files changed, 33 insertions(+), 273 deletions(-)
rename {apache-poi => apache-poi-2}/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java (88%)
rename {apache-poi => apache-poi-2}/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx (100%)
rename {apache-poi => apache-poi-2}/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java (85%)
delete mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java.orig
delete mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java.orig
diff --git a/apache-poi-2/README.md b/apache-poi-2/README.md
index f55ec7eb6a..2c0deec575 100644
--- a/apache-poi-2/README.md
+++ b/apache-poi-2/README.md
@@ -10,4 +10,5 @@ This module contains articles about Apache POI.
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Finding the Last Row in an Excel Spreadsheet From Java](https://www.baeldung.com/java-excel-find-last-row)
+- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- More articles: [[<-- prev]](../apache-poi)
diff --git a/apache-poi-2/pom.xml b/apache-poi-2/pom.xml
index a46365c63c..30270cd7be 100644
--- a/apache-poi-2/pom.xml
+++ b/apache-poi-2/pom.xml
@@ -22,7 +22,7 @@
- 5.0.0
+ 5.2.0
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java b/apache-poi-2/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java
similarity index 88%
rename from apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java
rename to apache-poi-2/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java
index f5179b19c9..ccff1fa709 100644
--- a/apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java
+++ b/apache-poi-2/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java
@@ -1,26 +1,25 @@
-package com.baeldung.poi.excel.setformula;
-
-import org.apache.poi.xssf.usermodel.XSSFCell;
-import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
-import org.apache.poi.xssf.usermodel.XSSFSheet;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-public class ExcelFormula {
- public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
- XSSFSheet sheet = wb.getSheetAt(0);
- int lastCellNum = sheet.getRow(0).getLastCellNum();
- XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
- formulaCell.setCellFormula(formula);
- XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
- formulaEvaluator.evaluateFormulaCell(formulaCell);
- FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
- wb.write(fileOut);
- wb.close();
- fileOut.close();
- return formulaCell.getNumericCellValue();
- }
-}
+package com.baeldung.poi.excel.setformula;
+
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class ExcelFormula {
+ public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
+ XSSFSheet sheet = wb.getSheetAt(0);
+ int lastCellNum = sheet.getRow(0).getLastCellNum();
+ XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
+ formulaCell.setCellFormula(formula);
+ XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
+ formulaEvaluator.evaluateFormulaCell(formulaCell);
+ FileOutputStream fileOut = new FileOutputStream(fileLocation);
+ wb.write(fileOut);
+ wb.close();
+ fileOut.close();
+ return formulaCell.getNumericCellValue();
+ }
+}
diff --git a/apache-poi/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx b/apache-poi-2/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx
similarity index 100%
rename from apache-poi/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx
rename to apache-poi-2/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java b/apache-poi-2/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java
similarity index 85%
rename from apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java
rename to apache-poi-2/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java
index fa5baa37fa..7a0f15b3f7 100644
--- a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java
+++ b/apache-poi-2/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java
@@ -3,18 +3,19 @@ package com.baeldung.poi.excel.setformula;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
class ExcelFormulaUnitTest {
- private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
+ private static final String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
+
private String fileLocation;
private ExcelFormula excelFormula;
@@ -26,7 +27,7 @@ class ExcelFormulaUnitTest {
@Test
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
- FileInputStream inputStream = new FileInputStream(new File(fileLocation));
+ FileInputStream inputStream = new FileInputStream(fileLocation);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);
double resultColumnA = 0;
@@ -46,6 +47,6 @@ class ExcelFormulaUnitTest {
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
- Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
+ assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
}
}
diff --git a/apache-poi/README.md b/apache-poi/README.md
index ed30d9a4f3..9edf69d67c 100644
--- a/apache-poi/README.md
+++ b/apache-poi/README.md
@@ -8,7 +8,6 @@ This module contains articles about Apache POI.
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
-- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row)
- [Multiline Text in Excel Cell Using Apache POI](https://www.baeldung.com/apache-poi-write-multiline-text)
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java.orig b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java.orig
deleted file mode 100644
index c058f3abcf..0000000000
--- a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelUtility.java.orig
+++ /dev/null
@@ -1,128 +0,0 @@
-package com.baeldung.poi.excel;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-
-public class ExcelUtility {
-<<<<<<< HEAD
- private static final String ENDLINE = System.getProperty("line.separator");
-
- public static String readExcel(String filePath) throws IOException {
- File file = new File(filePath);
- FileInputStream inputStream = null;
- StringBuilder toReturn = new StringBuilder();
- try {
- inputStream = new FileInputStream(file);
- Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream);
- for (Sheet sheet : baeuldungWorkBook) {
- toReturn.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- toReturn.append("Worksheet :")
- .append(sheet.getSheetName())
- .append(ENDLINE);
- toReturn.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- int firstRow = sheet.getFirstRowNum();
- int lastRow = sheet.getLastRowNum();
- for (int index = firstRow + 1; index <= lastRow; index++) {
- Row row = sheet.getRow(index);
- toReturn.append("|| ");
- for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
- Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
- printCellValue(cell, toReturn);
- }
- toReturn.append(" ||")
- .append(ENDLINE);
- }
- }
- inputStream.close();
-
- } catch (IOException e) {
- throw e;
- }
- return toReturn.toString();
- }
-
- public static void printCellValue(Cell cell, StringBuilder toReturn) {
- CellType cellType = cell.getCellType()
- .equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType();
- if (cellType.equals(CellType.STRING)) {
- toReturn.append(cell.getStringCellValue())
- .append(" | ");
- }
- if (cellType.equals(CellType.NUMERIC)) {
- if (DateUtil.isCellDateFormatted(cell)) {
- toReturn.append(cell.getDateCellValue())
- .append(" | ");
- } else {
- toReturn.append(cell.getNumericCellValue())
- .append(" | ");
- }
- }
- if (cellType.equals(CellType.BOOLEAN)) {
- toReturn.append(cell.getBooleanCellValue())
- .append(" | ");
- }
- }
-=======
- private static final String ENDLINE = System.getProperty("line.separator");
-
- public static String readExcel(String filePath) throws IOException {
- File file = new File(filePath);
- FileInputStream inputStream = null;
- StringBuilder toReturn = new StringBuilder();
- try {
- inputStream = new FileInputStream(file);
- Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream);
- for (Sheet sheet : baeuldungWorkBook) {
- toReturn.append("--------------------------------------------------------------------").append(ENDLINE);
- toReturn.append("Worksheet :").append(sheet.getSheetName()).append(ENDLINE);
- toReturn.append("--------------------------------------------------------------------").append(ENDLINE);
- int firstRow = sheet.getFirstRowNum();
- int lastRow = sheet.getLastRowNum();
- for (int index = firstRow + 1; index <= lastRow; index++) {
- Row row = sheet.getRow(index);
- toReturn.append("|| ");
- for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
- Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
- printCellValue(cell, toReturn);
- }
- toReturn.append(" ||").append(ENDLINE);
- }
- }
- inputStream.close();
-
- } catch (IOException e) {
- throw e;
- }
- return toReturn.toString();
- }
-
- public static void printCellValue(Cell cell, StringBuilder toReturn) {
- CellType cellType = cell.getCellType().equals(CellType.FORMULA) ? cell.getCachedFormulaResultType()
- : cell.getCellType();
- if (cellType.equals(CellType.STRING)) {
- toReturn.append(cell.getStringCellValue()).append(" | ");
- }
- if (cellType.equals(CellType.NUMERIC)) {
- if (DateUtil.isCellDateFormatted(cell)) {
- toReturn.append(cell.getDateCellValue()).append(" | ");
- } else {
- toReturn.append(cell.getNumericCellValue()).append(" | ");
- }
- }
- if (cellType.equals(CellType.BOOLEAN)) {
- toReturn.append(cell.getBooleanCellValue()).append(" | ");
- }
- }
->>>>>>> master
-}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java.orig b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java.orig
deleted file mode 100644
index cfc3062b5a..0000000000
--- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelUtilityUnitTest.java.orig
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.baeldung.poi.excel;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.file.Paths;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class ExcelUtilityUnitTest {
-<<<<<<< HEAD
- private static final String FILE_NAME = "baeldung.xlsx";
- private String fileLocation;
- private static final String ENDLINE = System.getProperty("line.separator");
- private StringBuilder output;
-
- @Before
- public void setupUnitTest() throws IOException, URISyntaxException, ParseException {
- output = new StringBuilder();
- output.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- output.append("Worksheet :Sheet1")
- .append(ENDLINE);
- output.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- output.append("|| Name1 | Surname1 | 3.55696564113E11 | ")
- .append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
- .toString())
- .append(" | ‡ | ||")
- .append(ENDLINE);
- output.append("|| Name2 | Surname2 | 5.646513512E9 | ")
- .append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021")
- .toString())
- .append(" | false | ||")
- .append(ENDLINE);
- output.append("|| Name3 | Surname3 | 3.55696564113E11 | ")
- .append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021")
- .toString())
- .append(" | 7.17039641738E11 | ||")
- .append(ENDLINE);
- output.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- output.append("Worksheet :Sheet2")
- .append(ENDLINE);
- output.append("--------------------------------------------------------------------")
- .append(ENDLINE);
- output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||")
- .append(ENDLINE);
-
- fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
- .toURI())
- .toString();
- }
-
- @Test
- public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException {
- assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation));
-
- }
-
- @Test
- public void givenStringPath_whenReadExcel_thenThrowException() {
- assertThrows(IOException.class, () -> {
- ExcelUtility.readExcel("baeldung");
- });
- }
-=======
- private static final String FILE_NAME = "baeldung.xlsx";
- private String fileLocation;
- private static final String ENDLINE = System.getProperty("line.separator");
- private StringBuilder output;
-
- @Before
- public void setupUnitTest() throws IOException, URISyntaxException, ParseException {
- output = new StringBuilder();
- output.append("--------------------------------------------------------------------").append(ENDLINE);
- output.append("Worksheet :Sheet1").append(ENDLINE);
- output.append("--------------------------------------------------------------------").append(ENDLINE);
- output.append("|| Name1 | Surname1 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | ‡ | ||")
- .append(ENDLINE);
- output.append("|| Name2 | Surname2 | 5.646513512E9 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/12/2021").toString()).append(" | false | ||")
- .append(ENDLINE);
- output.append("|| Name3 | Surname3 | 3.55696564113E11 | ").append(new SimpleDateFormat("dd/MM/yyyy").parse("4/11/2021").toString()).append(" | 7.17039641738E11 | ||")
- .append(ENDLINE);
- output.append("--------------------------------------------------------------------").append(ENDLINE);
- output.append("Worksheet :Sheet2").append(ENDLINE);
- output.append("--------------------------------------------------------------------").append(ENDLINE);
- output.append("|| Name4 | Surname4 | 3.55675623232E11 | 13/04/2021 | ||").append(ENDLINE);
-
- fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
- }
-
- @Test
- public void givenStringPath_whenReadExcel_thenReturnStringValue() throws IOException {
- assertEquals(output.toString(), ExcelUtility.readExcel(fileLocation));
-
- }
-
- @Test
- public void givenStringPath_whenReadExcel_thenThrowException() {
- assertThrows(IOException.class, () -> {
- ExcelUtility.readExcel("baeldung");
- });
- }
->>>>>>> master
-
-}
From a735229a8433bea1ab0f3076b18a774caddfcd92 Mon Sep 17 00:00:00 2001
From: sanitaso
Date: Tue, 8 Mar 2022 15:10:36 +0100
Subject: [PATCH 217/235] change the module directory
---
.../SwaggerResponseApiApplication.java | 0
.../controller/ProductController.java | 1 -
.../swaggerresponseapi/model/Product.java | 28 +++++++
.../service/ProductService.java | 0
.../swaggerResponseAPI/.gitignore | 33 --------
.../swaggerResponseAPI/pom.xml | 70 -----------------
.../swaggerresponseapi/model/Product.java | 15 ----
.../src/main/resources/application.properties | 1 -
.../ProductIntegrationTest.java | 76 -------------------
.../SwaggerResponseApiApplicationTests.java | 13 ----
10 files changed, 28 insertions(+), 209 deletions(-)
rename spring-boot-modules/spring-boot-springdoc/{swaggerResponseAPI => }/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java (100%)
rename spring-boot-modules/spring-boot-springdoc/{swaggerResponseAPI => }/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java (92%)
create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
rename spring-boot-modules/spring-boot-springdoc/{swaggerResponseAPI => }/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java (100%)
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
delete mode 100644 spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
similarity index 100%
rename from spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
similarity index 92%
rename from spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
index 3e9a3291d9..364a7e8a66 100644
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
@@ -24,7 +24,6 @@ public class ProductController {
this.productService = productService;
}
- @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Product successfully added!") })
@PostMapping("/create")
public Product addProduct(@RequestBody Product product) {
return productService.addProducts(product);
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
new file mode 100644
index 0000000000..036ecbc853
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
@@ -0,0 +1,28 @@
+package com.baeldung.swaggerresponseapi.model;
+
+public class Product {
+ String code;
+ String name;
+
+ public Product(String code, String name) {
+ this.code = code;
+ this.name = name;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
similarity index 100%
rename from spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
rename to spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
deleted file mode 100644
index f60f3beecd..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/.gitignore
+++ /dev/null
@@ -1,33 +0,0 @@
-HELP.md
-target/
-.mvn/wrapper/
-!**/src/main/**/target/
-!**/src/test/**/target/
-mvnv*
-
-### STS ###
-.apt_generated
-.classpath
-.factorypath
-.project
-.settings
-.springBeans
-.sts4-cache
-
-### IntelliJ IDEA ###
-.idea
-*.iws
-*.iml
-*.ipr
-### NetBeans ###
-/nbproject/private/
-/nbbuild/
-/dist/
-/nbdist/
-/.nb-gradle/
-build/
-!**/src/main/**/build/
-!**/src/test/**/build/
-
-### VS Code ###
-.vscode/
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
deleted file mode 100644
index c168248df2..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/pom.xml
+++ /dev/null
@@ -1,70 +0,0 @@
-
-
- 4.0.0
-
- org.springframework.boot
- spring-boot-starter-parent
- 2.6.3
-
-
- com.baeldung
- swaggerResponseAPI
- 0.0.1-SNAPSHOT
- swaggerResponseAPI
- swaggerResponseAPI
-
- 11
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
- org.projectlombok
- lombok
- true
-
-
- org.springdoc
- springdoc-openapi-ui
- 1.6.6
-
-
- junit
- junit
- 4.13.2
- test
-
-
- com.fasterxml.jackson.core
- jackson-databind
- 2.13.0
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
- org.projectlombok
- lombok
-
-
-
-
-
-
-
-
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
deleted file mode 100644
index 0a100582fc..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.baeldung.swaggerresponseapi.model;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Getter
-@Setter
-@AllArgsConstructor
-@NoArgsConstructor
-public class Product {
- String code;
- String name;
-}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
deleted file mode 100644
index 8b13789179..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/main/resources/application.properties
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
deleted file mode 100644
index ef6a8953e2..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/ProductIntegrationTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package com.baeldung.swaggerresponseapi;
-
-import com.baeldung.swaggerresponseapi.controller.ProductController;
-import com.baeldung.swaggerresponseapi.model.Product;
-import com.baeldung.swaggerresponseapi.service.ProductService;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
-import org.springframework.boot.test.mock.mockito.MockBean;
-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.result.MockMvcResultMatchers;
-
-import java.util.Arrays;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.BDDMockito.given;
-import static org.mockito.Mockito.reset;
-import static org.hamcrest.CoreMatchers.is;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
-import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-
-@RunWith(SpringRunner.class)
-@WebMvcTest(ProductController.class)
-public class ProductIntegrationTest {
-
- @Autowired
- MockMvc mock;
-
- @MockBean
- private ProductService productService;
-
- @Test
- public void givenProduct_whenAddNewProduct_thenReturnValidStatusCode() throws Exception {
- Product product = new Product("1001", "Milk");
- given(productService.addProducts(any(Product.class))).willReturn(product);
-
- mock.perform(post("/create").contentType(MediaType.APPLICATION_JSON)
- .content(toJsonString(product)))
- .andDo(print())
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.code").value("1001"));
-
- reset(productService);
- }
-
- @Test
- public void givenProductsList_whenGetAllProducts_thenReturnValidProducts() throws Exception {
- Product product1 = new Product("1001", "Milk");
- Product product2 = new Product("2002", "Butter");
-
- given(productService.getProductsList()).willReturn(Arrays.asList(product1, product2));
-
- mock.perform(get("/products").contentType(MediaType.APPLICATION_JSON))
- .andExpect(status().isOk())
- .andDo(print())
- .andExpect(jsonPath("$[0].code", is(product1.getCode())))
- .andExpect(jsonPath("$[1].name", is(product2.getName())));
-
- reset(productService);
- }
-
- public String toJsonString(Product product) throws JsonProcessingException {
- ObjectMapper om = new ObjectMapper();
- String json = om.writeValueAsString(product);
- return json;
- }
-}
diff --git a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java b/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
deleted file mode 100644
index 9e8c6ee0fa..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/swaggerResponseAPI/src/test/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplicationTests.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.baeldung.swaggerresponseapi;
-
-import org.junit.jupiter.api.Test;
-import org.springframework.boot.test.context.SpringBootTest;
-
-@SpringBootTest
-class SwaggerResponseApiApplicationTests {
-
- @Test
- void contextLoads() {
- }
-
-}
From bc543e9c79f33db2a671a2555fede3dd842ebe38 Mon Sep 17 00:00:00 2001
From: sanitaso
Date: Tue, 8 Mar 2022 15:13:42 +0100
Subject: [PATCH 218/235] remove dir
---
.../SwaggerResponseApiApplication.java | 13 -------
.../controller/ProductController.java | 38 -------------------
.../swaggerresponseapi/model/Product.java | 28 --------------
.../service/ProductService.java | 21 ----------
4 files changed, 100 deletions(-)
delete mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
delete mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
delete mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
delete mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
deleted file mode 100644
index 913544b459..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.baeldung.swaggerresponseapi;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class SwaggerResponseApiApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SwaggerResponseApiApplication.class, args);
- }
-
-}
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
deleted file mode 100644
index 364a7e8a66..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.baeldung.swaggerresponseapi.controller;
-
-import com.baeldung.swaggerresponseapi.model.Product;
-import com.baeldung.swaggerresponseapi.service.ProductService;
-
-import io.swagger.v3.oas.annotations.media.ArraySchema;
-import io.swagger.v3.oas.annotations.media.Content;
-import io.swagger.v3.oas.annotations.media.Schema;
-import io.swagger.v3.oas.annotations.responses.ApiResponse;
-import io.swagger.v3.oas.annotations.responses.ApiResponses;
-
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.util.List;
-
-@RestController
-public class ProductController {
- private final ProductService productService;
-
- public ProductController(ProductService productService) {
- this.productService = productService;
- }
-
- @PostMapping("/create")
- public Product addProduct(@RequestBody Product product) {
- return productService.addProducts(product);
- }
-
- @ApiResponses(value = { @ApiResponse(content = { @Content(mediaType = "application/json",
- array = @ArraySchema(schema = @Schema(implementation = Product.class))) }) })
- @GetMapping("/products")
- public List getProductsList() {
- return productService.getProductsList();
- }
-}
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
deleted file mode 100644
index 036ecbc853..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.baeldung.swaggerresponseapi.model;
-
-public class Product {
- String code;
- String name;
-
- public Product(String code, String name) {
- this.code = code;
- this.name = name;
- }
-
- public String getCode() {
- return code;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
-
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
deleted file mode 100644
index 5e7533d6f4..0000000000
--- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.baeldung.swaggerresponseapi.service;
-
-import com.baeldung.swaggerresponseapi.model.Product;
-import org.springframework.stereotype.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@Service
-public class ProductService {
- List productsList = new ArrayList<>();
-
- public Product addProducts(Product product) {
- productsList.add(product);
- return product;
- }
-
- public List getProductsList() {
- return productsList;
- }
-}
From e3966f2efde01da3696cb110aefaae9c2e75becd Mon Sep 17 00:00:00 2001
From: sanitaso
Date: Tue, 8 Mar 2022 15:15:11 +0100
Subject: [PATCH 219/235] add dir
---
.../SwaggerResponseApiApplication.java | 13 +++++++
.../controller/ProductController.java | 38 +++++++++++++++++++
.../swaggerresponseapi/model/Product.java | 28 ++++++++++++++
.../service/ProductService.java | 21 ++++++++++
4 files changed, 100 insertions(+)
create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
new file mode 100644
index 0000000000..913544b459
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/SwaggerResponseApiApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.swaggerresponseapi;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SwaggerResponseApiApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SwaggerResponseApiApplication.class, args);
+ }
+
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
new file mode 100644
index 0000000000..364a7e8a66
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/controller/ProductController.java
@@ -0,0 +1,38 @@
+package com.baeldung.swaggerresponseapi.controller;
+
+import com.baeldung.swaggerresponseapi.model.Product;
+import com.baeldung.swaggerresponseapi.service.ProductService;
+
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.responses.ApiResponses;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+
+@RestController
+public class ProductController {
+ private final ProductService productService;
+
+ public ProductController(ProductService productService) {
+ this.productService = productService;
+ }
+
+ @PostMapping("/create")
+ public Product addProduct(@RequestBody Product product) {
+ return productService.addProducts(product);
+ }
+
+ @ApiResponses(value = { @ApiResponse(content = { @Content(mediaType = "application/json",
+ array = @ArraySchema(schema = @Schema(implementation = Product.class))) }) })
+ @GetMapping("/products")
+ public List getProductsList() {
+ return productService.getProductsList();
+ }
+}
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
new file mode 100644
index 0000000000..036ecbc853
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/model/Product.java
@@ -0,0 +1,28 @@
+package com.baeldung.swaggerresponseapi.model;
+
+public class Product {
+ String code;
+ String name;
+
+ public Product(String code, String name) {
+ this.code = code;
+ this.name = name;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+
diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
new file mode 100644
index 0000000000..5e7533d6f4
--- /dev/null
+++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/swaggerresponseapi/service/ProductService.java
@@ -0,0 +1,21 @@
+package com.baeldung.swaggerresponseapi.service;
+
+import com.baeldung.swaggerresponseapi.model.Product;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+public class ProductService {
+ List productsList = new ArrayList<>();
+
+ public Product addProducts(Product product) {
+ productsList.add(product);
+ return product;
+ }
+
+ public List getProductsList() {
+ return productsList;
+ }
+}
From c1751dc317e3a363611c5a9306a7521cc9b1ad2a Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Wed, 9 Mar 2022 02:19:19 +0530
Subject: [PATCH 220/235] BAEL-5360: Check Collection Existence in MongoDB
(#11905)
* BAEL-5360: Check Collection Existence in MongoDB
* BAEL-5360: update test names using the bdd scheme
---
.../baeldung/mongo/CollectionExistence.java | 100 ++++++++++++++++++
.../mongo/CollectionExistenceLiveTest.java | 98 +++++++++++++++++
2 files changed, 198 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
new file mode 100644
index 0000000000..074913af4e
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
@@ -0,0 +1,100 @@
+package com.baeldung.mongo;
+
+import java.util.ArrayList;
+
+import org.bson.Document;
+
+import com.mongodb.DB;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+
+public class CollectionExistence {
+
+ private static MongoClient mongoClient;
+
+ private static String testCollectionName;
+ private static String databaseName;
+
+ public static void setUp() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ }
+ databaseName = "baeldung";
+ testCollectionName = "student";
+ }
+
+ public static void collectionExistsSolution() {
+
+ DB db = mongoClient.getDB(databaseName);
+
+ System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName));
+
+ }
+
+ public static void createCollectionSolution() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+
+ try {
+ database.createCollection(testCollectionName);
+
+ } catch (Exception exception) {
+ System.err.println("Collection already Exists");
+ }
+
+ }
+
+ public static void listCollectionNamesSolution() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ boolean collectionExists = database.listCollectionNames()
+ .into(new ArrayList())
+ .contains(testCollectionName);
+
+ System.out.println("collectionExists:- " + collectionExists);
+
+ }
+
+ public static void countSolution() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+
+ MongoCollection collection = database.getCollection(testCollectionName);
+
+ System.out.println(collection.count());
+
+ }
+
+ public static void main(String args[]) {
+
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
+ setUp();
+
+ //
+ // Check the db existence using DB class's method
+ //
+ collectionExistsSolution();
+
+ //
+ // Check the db existence using the createCollection method of MongoDatabase class
+ //
+ createCollectionSolution();
+
+ //
+ // Check the db existence using the listCollectionNames method of MongoDatabase class
+ //
+ listCollectionNamesSolution();
+
+ //
+ // Check the db existence using the count method of MongoDatabase class
+ //
+ countSolution();
+
+ }
+
+}
+
+
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
new file mode 100644
index 0000000000..ad839d1219
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
@@ -0,0 +1,98 @@
+package com.baeldung.mongo;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+
+import org.bson.Document;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.mongodb.DB;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+
+public class CollectionExistenceLiveTest {
+
+ private MongoClient mongoClient;
+ private String testCollectionName;
+ private String databaseName;
+
+ @Before
+ public void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ databaseName = "baeldung";
+ testCollectionName = "student";
+
+ // Create a new collection if it doesn't exists.
+ try {
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ database.createCollection(testCollectionName);
+
+ } catch (Exception exception) {
+
+ System.out.println("Collection already Exists");
+ }
+
+ }
+ }
+
+ @Test
+ public void givenCreateCollection_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ Boolean collectionStatus = false;
+ Boolean expectedStatus = true;
+
+ try {
+ database.createCollection(testCollectionName);
+
+ } catch (Exception exception) {
+ collectionStatus = true;
+ System.err.println("Collection already Exists");
+ }
+
+ assertEquals(expectedStatus, collectionStatus);
+
+ }
+
+ @Test
+ public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
+
+ DB db = mongoClient.getDB(databaseName);
+ Boolean collectionStatus = db.collectionExists(testCollectionName);
+
+ Boolean expectedStatus = true;
+ assertEquals(expectedStatus, collectionStatus);
+
+ }
+
+ @Test
+ public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ boolean collectionExists = database.listCollectionNames()
+ .into(new ArrayList())
+ .contains(testCollectionName);
+
+ Boolean expectedStatus = true;
+ assertEquals(expectedStatus, collectionExists);
+
+ }
+
+ @Test
+ public void givenCount_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+
+ MongoCollection collection = database.getCollection(testCollectionName);
+ Boolean collectionExists = collection.count() > 0 ? true : false;
+
+ Boolean expectedStatus = false;
+ assertEquals(expectedStatus, collectionExists);
+
+ }
+}
+
From c1d1134fb362fa4d61939a0834e48e92cf7db19c Mon Sep 17 00:00:00 2001
From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com>
Date: Tue, 8 Mar 2022 21:52:10 +0100
Subject: [PATCH 221/235] BAEL-4569: Formatting Email Text (#11910)
---
.../src/main/java/com/baeldung/mail/EmailService.java | 5 +++++
.../java/com/baeldung/mail/EmailServiceLiveTest.java | 10 +++++++++-
2 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/mail/EmailService.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/mail/EmailService.java
index 3d1e25e7a4..3e40cf53f7 100644
--- a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/mail/EmailService.java
+++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/mail/EmailService.java
@@ -67,12 +67,17 @@ public class EmailService {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
+ String msgStyled = "This is my bold-red email using JavaMailer";
+ MimeBodyPart mimeBodyPartWithStyledText = new MimeBodyPart();
+ mimeBodyPartWithStyledText.setContent(msgStyled, "text/html; charset=utf-8");
+
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(getFile());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
+ multipart.addBodyPart(mimeBodyPartWithStyledText);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/mail/EmailServiceLiveTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/mail/EmailServiceLiveTest.java
index 7f543bc612..cec4cfcb55 100644
--- a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/mail/EmailServiceLiveTest.java
+++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/mail/EmailServiceLiveTest.java
@@ -36,6 +36,7 @@ public class EmailServiceLiveTest {
MimeMessage receivedMessage = receivedMessages[0];
assertEquals("Mail Subject", subjectFromMessage(receivedMessage));
assertEquals("This is my first email using JavaMailer", emailTextFrom(receivedMessage));
+ assertEquals("This is my bold-red email using JavaMailer", emailStyledTextFrom(receivedMessage));
assertEquals("sample attachment content", attachmentContentsFrom(receivedMessage));
}
@@ -50,9 +51,16 @@ public class EmailServiceLiveTest {
.toString();
}
+ private static String emailStyledTextFrom(MimeMessage receivedMessage) throws IOException, MessagingException {
+ return ((MimeMultipart) receivedMessage.getContent())
+ .getBodyPart(1)
+ .getContent()
+ .toString();
+ }
+
private static String attachmentContentsFrom(MimeMessage receivedMessage) throws Exception {
return ((MimeMultipart) receivedMessage.getContent())
- .getBodyPart(1)
+ .getBodyPart(2)
.getContent()
.toString();
}
From 410ccd500b20498c73f384a4569ea92c10dba85d Mon Sep 17 00:00:00 2001
From: kwoyke
Date: Wed, 9 Mar 2022 18:08:22 +0100
Subject: [PATCH 222/235] JAVA-10399: Fix assertion to include start date
(#11893)
---
.../src/test/java/com/baeldung/random/RandomDatesUnitTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java
index 6005cf93c2..68b4fd4938 100644
--- a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java
+++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java
@@ -22,6 +22,6 @@ class RandomDatesUnitTest {
LocalDate end = LocalDate.now();
LocalDate random = RandomDates.between(start, end);
- assertThat(random).isAfter(start).isBefore(end);
+ assertThat(random).isAfterOrEqualTo(start).isBefore(end);
}
}
From f0f014b99cce3f6e144f832f7e9edd66e0556402 Mon Sep 17 00:00:00 2001
From: Bhaskara
Date: Thu, 10 Mar 2022 03:31:39 +0530
Subject: [PATCH 223/235] Added code for BAEL-1355 (#11908)
* Added code for BAEL-1355
* Formatted the code
* Added jakarta-ee to parent pom
Co-authored-by: Bhaskara Navuluri
---
jakarta-ee/pom.xml | 111 +++++++++++++++++
.../java/com/baeldung/eclipse/krazo/User.java | 84 +++++++++++++
.../eclipse/krazo/UserApplication.java | 11 ++
.../eclipse/krazo/UserController.java | 85 +++++++++++++
jakarta-ee/src/main/webapp/WEB-INF/beans.xml | 6 +
.../src/main/webapp/WEB-INF/views/success.jsp | 47 +++++++
.../src/main/webapp/WEB-INF/views/user.jsp | 89 ++++++++++++++
jakarta-ee/src/main/webapp/styles.css | 28 +++++
.../com/baeldung/eclipse/krazo/AppTest.java | 16 +++
.../eclipse/krazo/UserControllerUnitTest.java | 116 ++++++++++++++++++
pom.xml | 86 ++++++-------
11 files changed, 637 insertions(+), 42 deletions(-)
create mode 100644 jakarta-ee/pom.xml
create mode 100644 jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/User.java
create mode 100644 jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserApplication.java
create mode 100644 jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserController.java
create mode 100644 jakarta-ee/src/main/webapp/WEB-INF/beans.xml
create mode 100644 jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp
create mode 100644 jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp
create mode 100644 jakarta-ee/src/main/webapp/styles.css
create mode 100644 jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/AppTest.java
create mode 100644 jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/UserControllerUnitTest.java
diff --git a/jakarta-ee/pom.xml b/jakarta-ee/pom.xml
new file mode 100644
index 0000000000..074ca1eec8
--- /dev/null
+++ b/jakarta-ee/pom.xml
@@ -0,0 +1,111 @@
+
+ 4.0.0
+
+ com.baeldung
+ mvc-2.0
+ 1.0-SNAPSHOT
+ war
+
+ mvc-2.0
+
+
+ 9.0.0
+ 2.0.0
+ 2.0.0
+ 5.8.2
+ C:/glassfish6
+ admin
+ mvn-domain
+ 1.10.19
+
+ ${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords
+
+
+
+
+
+ jakarta.platform
+ jakarta.jakartaee-web-api
+ ${jakartaee-api.version}
+ provided
+
+
+
+ jakarta.mvc
+ jakarta.mvc-api
+ ${jakarta.mvc-api.version}
+
+
+
+ org.eclipse.krazo
+ krazo-jersey
+ ${krazo.version}
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit.jupiter.version}
+ test
+
+
+ org.mockito
+ mockito-all
+ ${mockito.version}
+ test
+
+
+
+
+
+ mvc-2.0
+
+
+ org.glassfish.maven.plugin
+ maven-glassfish-plugin
+ 2.1
+
+ ${local.glassfish.home}
+ admin
+
+ password
+
+
+ ${local.glassfish.domain}
+ 8080
+ 4848
+
+
+
+
+ ${project.artifactId}
+ target/${project.build.finalName}.war
+
+
+
+ true
+ false
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.0
+
+ 1.8
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+
+ false
+
+
+
+
+
diff --git a/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/User.java b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/User.java
new file mode 100644
index 0000000000..a2253b6aa6
--- /dev/null
+++ b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/User.java
@@ -0,0 +1,84 @@
+package com.baeldung.eclipse.krazo;
+
+import jakarta.enterprise.context.RequestScoped;
+import jakarta.inject.Named;
+import jakarta.mvc.RedirectScoped;
+import jakarta.mvc.binding.MvcBinding;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Null;
+import jakarta.validation.constraints.Size;
+import jakarta.ws.rs.FormParam;
+
+import java.io.Serializable;
+
+@Named("user")
+@RedirectScoped
+public class User implements Serializable {
+ @MvcBinding
+ @Null
+ private String id;
+
+ @MvcBinding
+ @NotNull
+ @Size(min = 1, message = "Name cannot be blank")
+ @FormParam("name")
+ private String name;
+
+ @MvcBinding
+ @Min(value = 18, message = "The minimum age of the user should be 18 years")
+ @FormParam("age")
+ private int age;
+
+ @MvcBinding
+ @Email(message = "The email cannot be blank and should be in a valid format")
+ @Size(min=3, message = "Email cannot be empty")
+ @FormParam("email")
+ private String email;
+
+ @MvcBinding
+ @Null
+ @FormParam("phone")
+ private String phone;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+}
diff --git a/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserApplication.java b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserApplication.java
new file mode 100644
index 0000000000..5a272806cb
--- /dev/null
+++ b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserApplication.java
@@ -0,0 +1,11 @@
+package com.baeldung.eclipse.krazo;
+
+import jakarta.ws.rs.ApplicationPath;
+import jakarta.ws.rs.core.Application;
+
+/**
+ * Default JAX-RS application listening on /app
+ */
+@ApplicationPath("/app")
+public class UserApplication extends Application {
+}
diff --git a/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserController.java b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserController.java
new file mode 100644
index 0000000000..92ddf73571
--- /dev/null
+++ b/jakarta-ee/src/main/java/com/baeldung/eclipse/krazo/UserController.java
@@ -0,0 +1,85 @@
+package com.baeldung.eclipse.krazo;
+
+import jakarta.inject.Inject;
+import jakarta.mvc.Controller;
+import jakarta.mvc.Models;
+import jakarta.mvc.binding.BindingResult;
+import jakarta.mvc.security.CsrfProtected;
+import jakarta.validation.Valid;
+import jakarta.ws.rs.BeanParam;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * The class contains two controllers and a REST API
+ */
+@Path("users")
+public class UserController {
+ @Inject
+ private BindingResult bindingResult;
+
+ private static final List users = new ArrayList<>();
+
+ @Inject
+ private Models models;
+
+ /**
+ * This is a controller. It displays a initial form to the user.
+ * @return The view name
+ */
+ @GET
+ @Controller
+ public String showForm() {
+ return "user.jsp";
+ }
+
+ /**
+ * The method handles the form submits
+ * Handles HTTP POST and is CSRF protected. The client invoking this controller should provide a CSRF token.
+ * @param user The user details that has to be stored
+ * @return Returns a view name
+ */
+ @POST
+ @Controller
+ @CsrfProtected
+ public String saveUser(@Valid @BeanParam User user) {
+ if (bindingResult.isFailed()) {
+ models.put("errors", bindingResult.getAllErrors());
+ return "user.jsp";
+ }
+ String id = UUID.randomUUID().toString();
+ user.setId(id);
+ users.add(user);
+ return "redirect:users/success";
+ }
+
+ /**
+ * Handles a redirect view
+ * @return The view name
+ */
+ @GET
+ @Controller
+ @Path("success")
+ public String saveUserSuccess() {
+ return "success.jsp";
+ }
+
+ /**
+ * The REST API that returns all the user details in the JSON format
+ * @return The list of users that are saved. The List is converted into Json Array.
+ * If no user is present a empty array is returned
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public List getUsers() {
+ return users;
+ }
+
+}
diff --git a/jakarta-ee/src/main/webapp/WEB-INF/beans.xml b/jakarta-ee/src/main/webapp/WEB-INF/beans.xml
new file mode 100644
index 0000000000..d068fbd3e4
--- /dev/null
+++ b/jakarta-ee/src/main/webapp/WEB-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
+
diff --git a/jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp b/jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp
new file mode 100644
index 0000000000..19d45e46ba
--- /dev/null
+++ b/jakarta-ee/src/main/webapp/WEB-INF/views/success.jsp
@@ -0,0 +1,47 @@
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+
+
+
+ MVC 2.0
+
+
+
+
+
+
+
+
+
+
+
+ Baeldung - Eclipse Krazo
+
+
+
+
+
+
+
+
+
+
+
+
+
User created successfully!
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp b/jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp
new file mode 100644
index 0000000000..a36655950d
--- /dev/null
+++ b/jakarta-ee/src/main/webapp/WEB-INF/views/user.jsp
@@ -0,0 +1,89 @@
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+
+
+
+ MVC 2.0
+
+
+
+
+
+
+
+
+
+
+
+ Baeldung - Eclipse Krazo
+
+
+
+
+
+
+
+
+
+
+ User Details
+
+
+
+
+
+
+ ${error.paramName}
+ ${error.message}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jakarta-ee/src/main/webapp/styles.css b/jakarta-ee/src/main/webapp/styles.css
new file mode 100644
index 0000000000..9cc9e62f12
--- /dev/null
+++ b/jakarta-ee/src/main/webapp/styles.css
@@ -0,0 +1,28 @@
+body, html {
+ font-family: Raleway, serif;
+ font-weight: 300;
+}
+
+.bg-dark {
+ background-color: #63b175 !important;
+ font-weight: 600 !important;
+}
+
+body {
+ padding-top: 80px;
+}
+
+@media (max-width: 979px) {
+ body {
+ padding-top: 0;
+ }
+}
+
+label {
+ font-weight: bold;
+}
+
+.hr-dark {
+ border-top: 2px solid #000;
+ margin-bottom: 20px;
+}
\ No newline at end of file
diff --git a/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/AppTest.java b/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/AppTest.java
new file mode 100644
index 0000000000..6934d1fca2
--- /dev/null
+++ b/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/AppTest.java
@@ -0,0 +1,16 @@
+package com.baeldung.eclipse.krazo;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Dummy Test
+ */
+public class AppTest {
+
+ @Test
+ public void test() {
+ assertTrue(true);
+ }
+}
diff --git a/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/UserControllerUnitTest.java b/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/UserControllerUnitTest.java
new file mode 100644
index 0000000000..5e79924ed7
--- /dev/null
+++ b/jakarta-ee/src/test/java/com/baeldung/eclipse/krazo/UserControllerUnitTest.java
@@ -0,0 +1,116 @@
+package com.baeldung.eclipse.krazo;
+
+import com.baeldung.eclipse.krazo.User;
+import com.baeldung.eclipse.krazo.UserController;
+import jakarta.mvc.Models;
+import jakarta.mvc.binding.BindingResult;
+import org.eclipse.krazo.core.ModelsImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
+
+/**
+ * The class contains unit tests. We do only unit tests. Most of the classes are mocked
+ */
+@DisplayName("Eclipse Krazo MVC 2.0 Test Suite")
+class UserControllerUnitTest {
+
+ @InjectMocks
+ UserController userController = new UserController();
+
+ @Mock
+ Models models;
+
+ @Mock
+ BindingResult bindingResult;
+
+ @BeforeEach
+ public void setUpClass() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ @DisplayName("Test Show Form")
+ void whenShowForm_thenReturnViewName() {
+ assertNotNull(userController.showForm());
+ assertEquals("user.jsp", userController.showForm());
+ }
+
+ @Test
+ @DisplayName("Test Save User Success")
+ void whenSaveUser_thenReturnSuccess() {
+ when(bindingResult.isFailed()).thenReturn(false);
+
+ User user = new User();
+
+ assertNotNull(userController.saveUser(user));
+ assertDoesNotThrow(() -> userController.saveUser(user));
+ assertEquals("redirect:users/success", userController.saveUser(user));
+ }
+
+ @Test
+ @DisplayName("Test Save User Binding Errors")
+ void whenSaveUser_thenReturnError() {
+ when(bindingResult.isFailed()).thenReturn(true);
+ Models testModels = new ModelsImpl();
+ when(models.put(anyString(), any())).thenReturn(testModels);
+ User user = getUser();
+ assertNotNull(userController.saveUser(user));
+ assertDoesNotThrow(() -> userController.saveUser(user));
+ assertEquals("user.jsp", userController.saveUser(user));
+ }
+
+ @Test
+ @DisplayName("Test Save User Success View")
+ void whenSaveUserSuccess_thenRedirectSuccess() {
+ assertNotNull(userController.saveUserSuccess());
+ assertDoesNotThrow(() -> userController.saveUserSuccess());
+ assertEquals("success.jsp", userController.saveUserSuccess());
+ }
+
+ @Test
+ @DisplayName("Test Get Users API")
+ void whenGetUser_thenReturnUsers() {
+ when(bindingResult.isFailed()).thenReturn(false);
+
+ User user= getUser();
+
+ assertNotNull(user);
+ assertEquals(30, user.getAge());
+ assertEquals("john doe", user.getName());
+ assertEquals("anymail", user.getEmail());
+ assertEquals("99887766554433", user.getPhone());
+ assertEquals("1", user.getId());
+
+ userController.saveUser(user);
+ userController.saveUser(user);
+ userController.saveUser(user);
+
+ assertNotNull(userController.getUsers());
+ assertDoesNotThrow(() -> userController.getUsers());
+ assertEquals(3, userController.getUsers().size());
+
+ }
+
+ private User getUser() {
+ User user = new User();
+ user.setId("1");
+ user.setName("john doe");
+ user.setAge(30);
+ user.setEmail("anymail");
+ user.setPhone("99887766554433");
+ return user;
+ }
+
+}
diff --git a/pom.xml b/pom.xml
index 197e946974..b6767c629b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -462,6 +462,7 @@
jaxb
jee-7
jee-7-security
+ jakarta-ee
jersey
jgit
jgroups
@@ -555,9 +556,9 @@
rxjava-observables
rxjava-operators
- atomikos
- reactive-systems
- slack
+ atomikos
+ reactive-systems
+ slack
@@ -945,6 +946,7 @@
jaxb
jee-7
jee-7-security
+ jakarta-ee
jersey
jgit
jgroups
@@ -1038,9 +1040,9 @@
rxjava-observables
rxjava-operators
- atomikos
- reactive-systems
- slack
+ atomikos
+ reactive-systems
+ slack
@@ -1311,43 +1313,43 @@
- core-java-modules/core-java-9
- core-java-modules/core-java-9-improvements
- core-java-modules/core-java-9-jigsaw
+ core-java-modules/core-java-9
+ core-java-modules/core-java-9-improvements
+ core-java-modules/core-java-9-jigsaw
- core-java-modules/core-java-9-streams
- core-java-modules/core-java-10
- core-java-modules/core-java-11
- core-java-modules/core-java-11-2
-
-
-
-
- core-java-modules/core-java-collections-set
- core-java-modules/core-java-collections-maps-4
- core-java-modules/core-java-date-operations-1
- core-java-modules/core-java-datetime-conversion
- core-java-modules/core-java-datetime-string
- core-java-modules/core-java-io-conversions-2
- core-java-modules/core-java-jpms
- core-java-modules/core-java-os
- core-java-modules/core-java-string-algorithms-3
- core-java-modules/core-java-string-operations-3
- core-java-modules/core-java-string-operations-4
- core-java-modules/core-java-time-measurements
- core-java-modules/core-java-networking-3
- core-java-modules/multimodulemavenproject
- ddd-modules
- httpclient-2
- libraries-concurrency
- persistence-modules/sirix
- persistence-modules/spring-data-cassandra-2
- quarkus-vs-springboot
- quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-camel
- testing-modules/testing-assertions
- persistence-modules/fauna
+ core-java-modules/core-java-9-streams
+ core-java-modules/core-java-10
+ core-java-modules/core-java-11
+ core-java-modules/core-java-11-2
+
+
+
+
+ core-java-modules/core-java-collections-set
+ core-java-modules/core-java-collections-maps-4
+ core-java-modules/core-java-date-operations-1
+ core-java-modules/core-java-datetime-conversion
+ core-java-modules/core-java-datetime-string
+ core-java-modules/core-java-io-conversions-2
+ core-java-modules/core-java-jpms
+ core-java-modules/core-java-os
+ core-java-modules/core-java-string-algorithms-3
+ core-java-modules/core-java-string-operations-3
+ core-java-modules/core-java-string-operations-4
+ core-java-modules/core-java-time-measurements
+ core-java-modules/core-java-networking-3
+ core-java-modules/multimodulemavenproject
+ ddd-modules
+ httpclient-2
+ libraries-concurrency
+ persistence-modules/sirix
+ persistence-modules/spring-data-cassandra-2
+ quarkus-vs-springboot
+ quarkus-jandex
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
+ testing-modules/testing-assertions
+ persistence-modules/fauna
From fbb90aa41a6524acfd1d5f9ab526200a3f948f11 Mon Sep 17 00:00:00 2001
From: anuragkumawat
Date: Thu, 10 Mar 2022 16:27:42 +0530
Subject: [PATCH 224/235] JAVA-10379 Work done on feedback
---
.../HibernateManyToManyAnnotationMainIntegrationTest.java | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
index 71051c821c..5255cb040f 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
@@ -52,9 +52,11 @@ public class HibernateManyToManyAnnotationMainIntegrationTest {
for(Employee employee : employeeList) {
assertNotNull(employee.getProjects());
+ assertEquals(2, employee.getProjects().size());
}
for(Project project : projectList) {
assertNotNull(project.getEmployees());
+ assertEquals(2, project.getEmployees().size());
}
}
@@ -70,6 +72,11 @@ public class HibernateManyToManyAnnotationMainIntegrationTest {
for (String emp : employeeData) {
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
employee.setProjects(projects);
+
+ for (Project proj : projects) {
+ proj.getEmployees().add(employee);
+ }
+
session.persist(employee);
}
}
From 227afb71cf18ce3e78a5d6a5ae2a7c233b322b0b Mon Sep 17 00:00:00 2001
From: Krzysiek
Date: Thu, 10 Mar 2022 15:08:46 +0100
Subject: [PATCH 225/235] JAVA-10271: Fix circular dependency issue
---
.../java/com/baeldung/keycloak/KeycloakConfig.java | 14 ++++++++++++++
.../java/com/baeldung/keycloak/SecurityConfig.java | 5 -----
2 files changed, 14 insertions(+), 5 deletions(-)
create mode 100644 spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java
diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java
new file mode 100644
index 0000000000..6a3dc45717
--- /dev/null
+++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java
@@ -0,0 +1,14 @@
+package com.baeldung.keycloak;
+
+import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class KeycloakConfig {
+
+ @Bean
+ public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
+ return new KeycloakSpringBootConfigResolver();
+ }
+}
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 78023aff8f..826f475a6e 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
@@ -23,11 +23,6 @@ class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
auth.authenticationProvider(keycloakAuthenticationProvider);
}
- @Bean
- public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
- return new KeycloakSpringBootConfigResolver();
- }
-
// Specifies the session authentication strategy
@Bean
@Override
From fee01d60fbd97dd80cc1ada797ff6e0fb8c11f28 Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Fri, 11 Mar 2022 00:20:08 +0530
Subject: [PATCH 226/235] BAEL-5374: push Into Array in MongoDB (#11916)
---
.../com/baeldung/mongo/PushOperations.java | 99 +++++++++++++++++++
.../baeldung/mongo/PushOperationLiveTest.java | 92 +++++++++++++++++
2 files changed, 191 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/PushOperations.java
create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/PushOperationLiveTest.java
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/PushOperations.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/PushOperations.java
new file mode 100644
index 0000000000..fa1f9ddc96
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/PushOperations.java
@@ -0,0 +1,99 @@
+package com.baeldung.mongo;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import org.bson.Document;
+
+import com.mongodb.BasicDBObject;
+import com.mongodb.DBObject;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class PushOperations {
+
+ private static MongoClient mongoClient;
+ private static String testCollectionName;
+ private static String databaseName;
+
+ public static void setUp() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ }
+
+ databaseName = "baeldung";
+ testCollectionName = "orders";
+
+ }
+
+ public static void pushOperationUsingDBObject() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ MongoCollection collection = database.getCollection(testCollectionName);
+ DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
+ .append("price", 800));
+ BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
+ BasicDBObject updateQuery = new BasicDBObject();
+ updateQuery.append("$push", listItem);
+ UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
+
+ System.out.println("updateResult:- " + updateResult);
+ }
+
+ public static void pushOperationUsingDocument() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ MongoCollection collection = database.getCollection(testCollectionName);
+
+ Document item = new Document().append("itemName", "PIZZA MANIA")
+ .append("quantity", 1)
+ .append("price", 800);
+ UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
+
+ System.out.println("updateResult:- " + updateResult);
+ }
+
+ public static void addToSetOperation() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ MongoCollection collection = database.getCollection(testCollectionName);
+
+ Document item = new Document().append("itemName", "PIZZA MANIA")
+ .append("quantity", 1)
+ .append("price", 800);
+ UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
+ System.out.println("updateResult:- " + updateResult);
+ }
+
+ public static void main(String args[]) {
+
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
+ setUp();
+
+ //
+ // Push document into the array using DBObject
+ //
+
+ pushOperationUsingDBObject();
+
+ //
+ // Push document into the array using Document.
+ //
+
+ pushOperationUsingDocument();
+
+ //
+ // Push document into the array using addToSet operator.
+ //
+ addToSetOperation();
+
+ }
+
+}
+
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/PushOperationLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/PushOperationLiveTest.java
new file mode 100644
index 0000000000..bd8523b301
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/PushOperationLiveTest.java
@@ -0,0 +1,92 @@
+package com.baeldung.mongo;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+import org.bson.Document;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.mongodb.BasicDBObject;
+import com.mongodb.DBObject;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class PushOperationLiveTest {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase db;
+ private static MongoCollection collection;
+
+ @BeforeClass
+ public static void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ db = mongoClient.getDatabase("baeldung");
+ collection = db.getCollection("orders");
+
+ collection.insertOne(
+ Document.parse("{\n" + " \"customerId\": 1023,\n" + " \"orderTimestamp\": NumberLong(\"1646460073000\"),\n" + " \"shippingDestination\": \"336, Street No.1 Pawai Mumbai\",\n" + " \"purchaseOrder\": 1000,\n"
+ + " \"contactNumber\":\"9898987676\",\n" + " \"items\": [ \n" + " {\n" + " \"itemName\": \"BERGER\",\n" + " \"quantity\": 1,\n" + " \"price\": 500\n" + " },\n"
+ + " {\n" + " \"itemName\": \"VEG PIZZA\",\n" + " \"quantity\": 1,\n" + " \"price\": 800\n" + " } \n" + " ]\n" + " }"));
+ }
+ }
+
+ @Test
+ public void givenOrderCollection_whenPushOperationUsingDBObject_thenCheckingForDocument() {
+
+ DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
+ .append("price", 800));
+ BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
+ BasicDBObject updateQuery = new BasicDBObject();
+ updateQuery.append("$push", listItem);
+ UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
+
+ Document orderDetail = collection.find(Filters.eq("customerId", 1023))
+ .first();
+ assertNotNull(orderDetail);
+ assertFalse(orderDetail.isEmpty());
+
+ }
+
+ @Test
+ public void givenOrderCollection_whenPushOperationUsingDocument_thenCheckingForDocument() {
+
+ Document item = new Document().append("itemName", "PIZZA MANIA")
+ .append("quantity", 1)
+ .append("price", 800);
+ UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
+
+ Document orderDetail = collection.find(Filters.eq("customerId", 1023))
+ .first();
+ assertNotNull(orderDetail);
+ assertFalse(orderDetail.isEmpty());
+
+ }
+
+ @Test
+ public void givenOrderCollection_whenAddToSetOperation_thenCheckingForDocument() {
+
+ Document item = new Document().append("itemName", "PIZZA MANIA")
+ .append("quantity", 1)
+ .append("price", 800);
+ UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
+
+ Document orderDetail = collection.find(Filters.eq("customerId", 1023))
+ .first();
+ assertNotNull(orderDetail);
+ assertFalse(orderDetail.isEmpty());
+ }
+
+ @AfterClass
+ public static void cleanUp() {
+ mongoClient.close();
+ }
+
+}
+
From c6bd572edaa27d9878a5eb7a7c5c3a6448ada31c Mon Sep 17 00:00:00 2001
From: thibaultfaure
Date: Thu, 10 Mar 2022 23:34:39 -0300
Subject: [PATCH 227/235] BAEL-4524 Acquire a Lock By Key in Java (#11872)
---
.../com/baeldung/lockbykey/ExampleUsage.java | 43 ++++++
.../com/baeldung/lockbykey/LockByKey.java | 41 +++++
.../lockbykey/SimpleExclusiveLockByKey.java | 18 +++
.../SimultaneousEntriesLockByKey.java | 25 +++
.../baeldung/lockbykey/LockByKeyUnitTest.java | 106 +++++++++++++
.../SimpleExclusiveLockByKeyUnitTest.java | 51 ++++++
.../SimultaneousEntriesLockByKeyUnitTest.java | 146 ++++++++++++++++++
7 files changed, 430 insertions(+)
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/ExampleUsage.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/LockByKey.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimpleExclusiveLockByKey.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKey.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/LockByKeyUnitTest.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimpleExclusiveLockByKeyUnitTest.java
create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKeyUnitTest.java
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/ExampleUsage.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/ExampleUsage.java
new file mode 100644
index 0000000000..23cfb8455a
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/ExampleUsage.java
@@ -0,0 +1,43 @@
+package com.baeldung.lockbykey;
+
+/**
+ * This class shows examples of how you should use the lock
+ *
+ */
+public class ExampleUsage {
+
+ void doWithSimpleExclusiveLock(String key) {
+ SimpleExclusiveLockByKey simpleExclusiveLockByKey = new SimpleExclusiveLockByKey();
+ if (simpleExclusiveLockByKey.tryLock(key)) {
+ try {
+ // do stuff
+ } finally {
+ // it is very important to unlock in the finally block to avoid locking keys forever
+ simpleExclusiveLockByKey.unlock(key);
+ }
+ }
+ }
+
+ // A concrete example can be found in the unit tests
+ void doWithLock(String key) {
+ LockByKey lockByKey = new LockByKey();
+ lockByKey.lock(key);
+ try {
+ // do stuff
+ } finally {
+ lockByKey.unlock(key);
+ }
+ }
+
+ // It works exactly the same as with locks
+ void doWithSemaphore(String key) {
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ try {
+ // do stuff
+ } finally {
+ lockByKey.unlock(key);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/LockByKey.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/LockByKey.java
new file mode 100644
index 0000000000..f81aa6779e
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/LockByKey.java
@@ -0,0 +1,41 @@
+package com.baeldung.lockbykey;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class LockByKey {
+
+ private static class LockWrapper {
+ private final Lock lock = new ReentrantLock();
+ private final AtomicInteger numberOfThreadsInQueue = new AtomicInteger(1);
+
+ private LockWrapper addThreadInQueue() {
+ numberOfThreadsInQueue.incrementAndGet();
+ return this;
+ }
+
+ private int removeThreadFromQueue() {
+ return numberOfThreadsInQueue.decrementAndGet();
+ }
+
+ }
+
+ private static ConcurrentHashMap locks = new ConcurrentHashMap();
+
+ public void lock(String key) {
+ LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue());
+ lockWrapper.lock.lock();
+ }
+
+ public void unlock(String key) {
+ LockWrapper lockWrapper = locks.get(key);
+ lockWrapper.lock.unlock();
+ if (lockWrapper.removeThreadFromQueue() == 0) {
+ // NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal
+ locks.remove(key, lockWrapper);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimpleExclusiveLockByKey.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimpleExclusiveLockByKey.java
new file mode 100644
index 0000000000..9182f9c038
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimpleExclusiveLockByKey.java
@@ -0,0 +1,18 @@
+package com.baeldung.lockbykey;
+
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class SimpleExclusiveLockByKey {
+
+ private static Set usedKeys= ConcurrentHashMap.newKeySet();
+
+ public boolean tryLock(String key) {
+ return usedKeys.add(key);
+ }
+
+ public void unlock(String key) {
+ usedKeys.remove(key);
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKey.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKey.java
new file mode 100644
index 0000000000..9532f973fa
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKey.java
@@ -0,0 +1,25 @@
+package com.baeldung.lockbykey;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Semaphore;
+
+public class SimultaneousEntriesLockByKey {
+
+ private static final int ALLOWED_THREADS = 2;
+
+ private static ConcurrentHashMap semaphores = new ConcurrentHashMap();
+
+ public void lock(String key) {
+ Semaphore semaphore = semaphores.compute(key, (k, v) -> v == null ? new Semaphore(ALLOWED_THREADS) : v);
+ semaphore.acquireUninterruptibly();
+ }
+
+ public void unlock(String key) {
+ Semaphore semaphore = semaphores.get(key);
+ semaphore.release();
+ if (semaphore.availablePermits() == ALLOWED_THREADS) {
+ semaphores.remove(key, semaphore);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/LockByKeyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/LockByKeyUnitTest.java
new file mode 100644
index 0000000000..4e43a8fb49
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/LockByKeyUnitTest.java
@@ -0,0 +1,106 @@
+package com.baeldung.lockbykey;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.Test;
+
+public class LockByKeyUnitTest {
+
+ @Test
+ void givenNoLockedKey_WhenLock_ThenSuccess() throws InterruptedException {
+ AtomicBoolean threadWasExecuted = new AtomicBoolean(false);
+ Thread thread = new Thread(() -> {
+ String key = "key";
+ LockByKey lockByKey = new LockByKey();
+ lockByKey.lock(key);
+ try {
+ threadWasExecuted.set(true);
+ } finally {
+ lockByKey.unlock(key);
+ }
+ });
+ try {
+ thread.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(threadWasExecuted.get());
+ }
+ }
+
+ @Test
+ void givenLockedKey_WhenLock_ThenFailure() throws InterruptedException {
+ String key = "key";
+ LockByKey lockByKey = new LockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ LockByKey otherLockByKey = new LockByKey();
+ otherLockByKey.lock(key);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(key);
+ }
+ });
+ try {
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertFalse(anotherThreadWasExecuted.get());
+ lockByKey.unlock(key);
+ }
+ }
+
+ @Test
+ void givenAnotherKeyLocked_WhenLock_ThenSuccess() throws InterruptedException {
+ String key = "key";
+ LockByKey lockByKey = new LockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ String anotherKey = "anotherKey";
+ LockByKey otherLockByKey = new LockByKey();
+ otherLockByKey.lock(anotherKey);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(anotherKey);
+ }
+ });
+ try {
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(anotherThreadWasExecuted.get());
+ lockByKey.unlock(key);
+ }
+ }
+
+ @Test
+ void givenUnlockedKey_WhenLock_ThenSuccess() throws InterruptedException {
+ String key = "key";
+ LockByKey lockByKey = new LockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ LockByKey otherLockByKey = new LockByKey();
+ otherLockByKey.lock(key);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(key);
+ }
+ });
+ try {
+ lockByKey.unlock(key);
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(anotherThreadWasExecuted.get());
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimpleExclusiveLockByKeyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimpleExclusiveLockByKeyUnitTest.java
new file mode 100644
index 0000000000..deba728664
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimpleExclusiveLockByKeyUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.lockbykey;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Field;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class SimpleExclusiveLockByKeyUnitTest {
+
+ @BeforeEach
+ void cleanUpLocks() throws Exception {
+ Field field = SimpleExclusiveLockByKey.class.getDeclaredField("usedKeys");
+ field.setAccessible(true);
+ field.set(null, ConcurrentHashMap.newKeySet());
+ }
+
+ @Test
+ void givenNoLockedKey_WhenTryLock_ThenSuccess() {
+ SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
+ assertTrue(lockByKey.tryLock("key"));
+ }
+
+ @Test
+ void givenLockedKey_WhenTryLock_ThenFailure() {
+ String key = "key";
+ SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
+ lockByKey.tryLock(key);
+ assertFalse(lockByKey.tryLock(key));
+ }
+
+ @Test
+ void givenAnotherKeyLocked_WhenTryLock_ThenSuccess() {
+ SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
+ lockByKey.tryLock("other");
+ assertTrue(lockByKey.tryLock("key"));
+ }
+
+ @Test
+ void givenUnlockedKey_WhenTryLock_ThenSuccess() {
+ String key = "key";
+ SimpleExclusiveLockByKey lockByKey = new SimpleExclusiveLockByKey();
+ lockByKey.tryLock(key);
+ lockByKey.unlock(key);
+ assertTrue(lockByKey.tryLock(key));
+ }
+
+}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKeyUnitTest.java b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKeyUnitTest.java
new file mode 100644
index 0000000000..ec4e7f4d80
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/test/java/com/baeldung/lockbykey/SimultaneousEntriesLockByKeyUnitTest.java
@@ -0,0 +1,146 @@
+package com.baeldung.lockbykey;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.Test;
+
+public class SimultaneousEntriesLockByKeyUnitTest {
+
+ @Test
+ void givenNoKeyUsed_WhenLock_ThenSuccess() throws InterruptedException {
+ AtomicBoolean threadWasExecuted = new AtomicBoolean(false);
+ Thread thread = new Thread(() -> {
+ String key = "key";
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ try {
+ threadWasExecuted.set(true);
+ } finally {
+ lockByKey.unlock(key);
+ }
+ });
+ try {
+ thread.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(threadWasExecuted.get());
+ }
+ }
+
+ @Test
+ void givenKeyLockedWithRemainingPermits_WhenLock_ThenSuccess() throws InterruptedException {
+ String key = "key";
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ SimultaneousEntriesLockByKey otherLockByKeyWithSemaphore = new SimultaneousEntriesLockByKey();
+ otherLockByKeyWithSemaphore.lock(key);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKeyWithSemaphore.unlock(key);
+ }
+ });
+ try {
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(anotherThreadWasExecuted.get());
+ lockByKey.unlock(key);
+ }
+ }
+
+ @Test
+ void givenKeyLockedWithNoRemainingPermits_WhenLock_ThenFailure() throws InterruptedException {
+ String key = "key";
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey1 = new Thread(() -> {
+ SimultaneousEntriesLockByKey otherLockByKeyWithSemaphore = new SimultaneousEntriesLockByKey();
+ otherLockByKeyWithSemaphore.lock(key);
+ try {
+ Thread.sleep(200); // make sure this thread will release the lock after the assertion
+ } catch (InterruptedException e) {
+
+ } finally {
+ otherLockByKeyWithSemaphore.unlock(key);
+ }
+ });
+ Thread threadLockingOnAnotherKey2 = new Thread(() -> {
+ SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
+ try {
+ Thread.sleep(50); // make sure thread1 will acquire the key first
+ } catch (InterruptedException e) {
+ }
+ otherLockByKey.lock(key);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(key);
+ }
+ });
+ try {
+ threadLockingOnAnotherKey1.start();
+ threadLockingOnAnotherKey2.start();
+ Thread.sleep(100);
+ } finally {
+ assertFalse(anotherThreadWasExecuted.get());
+ lockByKey.unlock(key);
+ }
+ }
+
+ @Test
+ void givenAnotherKeyLocked_WhenLock_ThenSuccess() throws InterruptedException {
+ String key = "key";
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ String anotherKey = "anotherKey";
+ SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
+ otherLockByKey.lock(anotherKey);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(anotherKey);
+ }
+ });
+ try {
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(anotherThreadWasExecuted.get());
+ lockByKey.unlock(key);
+ }
+ }
+
+ @Test
+ void givenUnlockedKey_WhenLock_ThenSuccess() throws InterruptedException {
+ String key = "key";
+ SimultaneousEntriesLockByKey lockByKey = new SimultaneousEntriesLockByKey();
+ lockByKey.lock(key);
+ AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
+ Thread threadLockingOnAnotherKey = new Thread(() -> {
+ SimultaneousEntriesLockByKey otherLockByKey = new SimultaneousEntriesLockByKey();
+ otherLockByKey.lock(key);
+ try {
+ anotherThreadWasExecuted.set(true);
+ } finally {
+ otherLockByKey.unlock(key);
+ }
+ });
+ try {
+ lockByKey.unlock(key);
+ threadLockingOnAnotherKey.start();
+ Thread.sleep(100);
+ } finally {
+ assertTrue(anotherThreadWasExecuted.get());
+ }
+ }
+
+}
From bfd778c028f6c9fc75d9d05d9452d7ab4f3d1931 Mon Sep 17 00:00:00 2001
From: lucaCambi77
Date: Fri, 11 Mar 2022 03:48:37 +0100
Subject: [PATCH 228/235] BAEL-5395 - Authentication with Spring Security and
MongoDB (#11883)
* auth with spring security and mongodb
* fix PMD
* fix missing application property in tests
* fix: code style
* fix: static finale case
* fix: omit Javadoc
---
.../spring-security-web-boot-3/pom.xml | 12 +-
.../mongoauth/MongoAuthApplication.java | 18 +++
.../mongoauth/config/MongoConfig.java | 40 ++++++
.../mongoauth/config/SecurityConfig.java | 59 +++++++++
.../controller/ResourceController.java | 23 ++++
.../com/baeldung/mongoauth/domain/Role.java | 13 ++
.../com/baeldung/mongoauth/domain/User.java | 83 ++++++++++++
.../baeldung/mongoauth/domain/UserRole.java | 21 ++++
.../mongoauth/repository/UserRepository.java | 13 ++
.../service/MongoAuthUserDetailService.java | 41 ++++++
.../mongoauth/service/SecurityService.java | 5 +
.../service/SecurityServiceImpl.java | 39 ++++++
.../src/main/resources/application.properties | 1 +
.../MongoAuthApplicationIntegrationTest.java | 118 ++++++++++++++++++
14 files changed, 485 insertions(+), 1 deletion(-)
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/MongoAuthApplication.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/MongoConfig.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/SecurityConfig.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/controller/ResourceController.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/Role.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/User.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/UserRole.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/repository/UserRepository.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/MongoAuthUserDetailService.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityService.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityServiceImpl.java
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/main/resources/application.properties
create mode 100644 spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/mongoauth/MongoAuthApplicationIntegrationTest.java
diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml
index 5f2a455294..5da993acd9 100644
--- a/spring-security-modules/spring-security-web-boot-3/pom.xml
+++ b/spring-security-modules/spring-security-web-boot-3/pom.xml
@@ -1,5 +1,6 @@
-
+
4.0.0
spring-security-web-boot-3
0.0.1-SNAPSHOT
@@ -23,6 +24,15 @@
org.springframework.boot
spring-boot-starter-web
+
+ org.springframework.boot
+ spring-boot-starter-data-mongodb
+
+
+ de.flapdoodle.embed
+ de.flapdoodle.embed.mongo
+ 3.3.1
+
commons-io
commons-io
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/MongoAuthApplication.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/MongoAuthApplication.java
new file mode 100644
index 0000000000..53624c0dd8
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/MongoAuthApplication.java
@@ -0,0 +1,18 @@
+package com.baeldung.mongoauth;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Import;
+
+import com.baeldung.mongoauth.config.MongoConfig;
+import com.baeldung.mongoauth.config.SecurityConfig;
+
+@SpringBootApplication
+@Import({ SecurityConfig.class, MongoConfig.class })
+public class MongoAuthApplication {
+
+ public static void main(String... args) {
+ SpringApplication.run(MongoAuthApplication.class, args);
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/MongoConfig.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/MongoConfig.java
new file mode 100644
index 0000000000..ddef7800de
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/MongoConfig.java
@@ -0,0 +1,40 @@
+package com.baeldung.mongoauth.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.mongodb.core.MongoTemplate;
+import org.springframework.util.SocketUtils;
+
+import com.mongodb.client.MongoClients;
+
+import de.flapdoodle.embed.mongo.MongodExecutable;
+import de.flapdoodle.embed.mongo.MongodStarter;
+import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig;
+import de.flapdoodle.embed.mongo.config.MongodConfig;
+import de.flapdoodle.embed.mongo.config.Net;
+import de.flapdoodle.embed.mongo.distribution.Version;
+import de.flapdoodle.embed.process.runtime.Network;
+
+@Configuration
+public class MongoConfig {
+
+ private static final String CONNECTION_STRING = "mongodb://%s:%d";
+ private static final String HOST = "localhost";
+
+ @Bean
+ public MongoTemplate mongoTemplate() throws Exception {
+
+ int randomPort = SocketUtils.findAvailableTcpPort();
+
+ ImmutableMongodConfig mongoDbConfig = MongodConfig.builder()
+ .version(Version.Main.PRODUCTION)
+ .net(new Net(HOST, randomPort, Network.localhostIsIPv6()))
+ .build();
+
+ MongodStarter starter = MongodStarter.getDefaultInstance();
+ MongodExecutable mongodExecutable = starter.prepare(mongoDbConfig);
+ mongodExecutable.start();
+ return new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, HOST, randomPort)), "mongo_auth");
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/SecurityConfig.java
new file mode 100644
index 0000000000..050d917492
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/config/SecurityConfig.java
@@ -0,0 +1,59 @@
+package com.baeldung.mongoauth.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+
+@Configuration
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true)
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ private final UserDetailsService userDetailsService;
+
+ public SecurityConfig(UserDetailsService userDetailsService) {
+ this.userDetailsService = userDetailsService;
+ }
+
+ @Bean
+ public AuthenticationManager customAuthenticationManager() throws Exception {
+ return authenticationManager();
+ }
+
+ @Bean
+ public BCryptPasswordEncoder bCryptPasswordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+
+ @Override
+ protected void configure(@Autowired AuthenticationManagerBuilder auth) throws Exception {
+ auth.userDetailsService(userDetailsService)
+ .passwordEncoder(bCryptPasswordEncoder());
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf()
+ .disable()
+ .authorizeRequests()
+ .and()
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest()
+ .permitAll()
+ .and()
+ .sessionManagement()
+ .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/controller/ResourceController.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/controller/ResourceController.java
new file mode 100644
index 0000000000..a5d9e91083
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/controller/ResourceController.java
@@ -0,0 +1,23 @@
+package com.baeldung.mongoauth.controller;
+
+import javax.annotation.security.RolesAllowed;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class ResourceController {
+
+ @RolesAllowed("ROLE_ADMIN")
+ @GetMapping("/admin")
+ public String admin() {
+ return "Hello Admin!";
+ }
+
+ @RolesAllowed({ "ROLE_ADMIN", "ROLE_USER" })
+ @GetMapping("/user")
+ public String user() {
+ return "Hello User!";
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/Role.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/Role.java
new file mode 100644
index 0000000000..e475e68460
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/Role.java
@@ -0,0 +1,13 @@
+package com.baeldung.mongoauth.domain;
+
+public class Role {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/User.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/User.java
new file mode 100644
index 0000000000..ffaea836a4
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/User.java
@@ -0,0 +1,83 @@
+package com.baeldung.mongoauth.domain;
+
+import java.util.Objects;
+import java.util.Set;
+
+import org.bson.types.ObjectId;
+import org.springframework.data.mongodb.core.mapping.Document;
+import org.springframework.data.mongodb.core.mapping.MongoId;
+import org.springframework.security.core.userdetails.UserDetails;
+
+@Document
+public class User implements UserDetails {
+ private @MongoId ObjectId id;
+ private String username;
+ private String password;
+ private Set userRoles;
+
+ public ObjectId getId() {
+ return id;
+ }
+
+ @Override
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public void setUserRoles(Set userRoles) {
+ this.userRoles = userRoles;
+ }
+
+ @Override
+ public Set getAuthorities() {
+ return this.userRoles;
+ }
+
+ @Override
+ public String getUsername() {
+ return this.username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ @Override
+ public boolean isAccountNonExpired() {
+ return false;
+ }
+
+ @Override
+ public boolean isAccountNonLocked() {
+ return false;
+ }
+
+ @Override
+ public boolean isCredentialsNonExpired() {
+ return false;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return false;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ User user = (User) o;
+ return Objects.equals(username, user.username);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(username);
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/UserRole.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/UserRole.java
new file mode 100644
index 0000000000..ccfa3bd605
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/domain/UserRole.java
@@ -0,0 +1,21 @@
+package com.baeldung.mongoauth.domain;
+
+import org.springframework.security.core.GrantedAuthority;
+
+public class UserRole implements GrantedAuthority {
+
+ private Role role;
+
+ @Override
+ public String getAuthority() {
+ return role.getName();
+ }
+
+ public Role getRole() {
+ return role;
+ }
+
+ public void setRole(Role role) {
+ this.role = role;
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/repository/UserRepository.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/repository/UserRepository.java
new file mode 100644
index 0000000000..c68f77ffbf
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/repository/UserRepository.java
@@ -0,0 +1,13 @@
+package com.baeldung.mongoauth.repository;
+
+import org.springframework.data.mongodb.repository.MongoRepository;
+import org.springframework.data.mongodb.repository.Query;
+
+import com.baeldung.mongoauth.domain.User;
+
+public interface UserRepository extends MongoRepository {
+
+ @Query("{username:'?0'}")
+ User findUserByUsername(String username);
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/MongoAuthUserDetailService.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/MongoAuthUserDetailService.java
new file mode 100644
index 0000000000..5838504d40
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/MongoAuthUserDetailService.java
@@ -0,0 +1,41 @@
+package com.baeldung.mongoauth.service;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+import com.baeldung.mongoauth.repository.UserRepository;
+
+@Service
+public class MongoAuthUserDetailService implements UserDetailsService {
+
+ private final UserRepository userRepository;
+
+ public MongoAuthUserDetailService(UserRepository userRepository) {
+ this.userRepository = userRepository;
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
+
+ com.baeldung.mongoauth.domain.User user = userRepository.findUserByUsername(userName);
+
+ Set grantedAuthorities = new HashSet<>();
+
+ user.getAuthorities()
+ .forEach(role -> {
+ grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole()
+ .getName()));
+ });
+
+ return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
+ }
+
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityService.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityService.java
new file mode 100644
index 0000000000..4204e4708b
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityService.java
@@ -0,0 +1,5 @@
+package com.baeldung.mongoauth.service;
+
+public interface SecurityService {
+ boolean login(String username, String password);
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityServiceImpl.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityServiceImpl.java
new file mode 100644
index 0000000000..f86ffaa26a
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/mongoauth/service/SecurityServiceImpl.java
@@ -0,0 +1,39 @@
+package com.baeldung.mongoauth.service;
+
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.stereotype.Service;
+
+@Service
+public class SecurityServiceImpl implements SecurityService {
+
+ private final AuthenticationManager authenticationManager;
+
+ private final UserDetailsService userDetailsService;
+
+ public SecurityServiceImpl(AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
+ this.authenticationManager = authenticationManager;
+ this.userDetailsService = userDetailsService;
+ }
+
+ @Override
+ public boolean login(String username, String password) {
+ UserDetails userDetails = userDetailsService.loadUserByUsername(username);
+
+ UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
+
+ authenticationManager.authenticate(usernamePasswordAuthenticationToken);
+
+ if (usernamePasswordAuthenticationToken.isAuthenticated()) {
+ SecurityContextHolder.getContext()
+ .setAuthentication(usernamePasswordAuthenticationToken);
+
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/application.properties b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application.properties
new file mode 100644
index 0000000000..a5b5fb9804
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application.properties
@@ -0,0 +1 @@
+spring.mongodb.embedded.version=4.4.9
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/mongoauth/MongoAuthApplicationIntegrationTest.java b/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/mongoauth/MongoAuthApplicationIntegrationTest.java
new file mode 100644
index 0000000000..b7994cad9e
--- /dev/null
+++ b/spring-security-modules/spring-security-web-boot-3/src/test/java/com/baeldung/mongoauth/MongoAuthApplicationIntegrationTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.mongoauth;
+
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
+import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.util.Collections;
+import java.util.HashSet;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.data.mongodb.core.MongoTemplate;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import com.baeldung.mongoauth.domain.Role;
+import com.baeldung.mongoauth.domain.User;
+import com.baeldung.mongoauth.domain.UserRole;
+
+@SpringBootTest(classes = { MongoAuthApplication.class })
+@AutoConfigureMockMvc
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
+class MongoAuthApplicationIntegrationTest {
+
+ @Autowired
+ private WebApplicationContext context;
+
+ @Autowired
+ private MongoTemplate mongoTemplate;
+
+ @Autowired
+ private BCryptPasswordEncoder bCryptPasswordEncoder;
+
+ private MockMvc mvc;
+
+ private static final String USER_NAME = "user@gmail.com";
+ private static final String ADMIN_NAME = "admin@gmail.com";
+ private static final String PASSWORD = "password";
+
+ @BeforeEach
+ public void setup() {
+
+ setUp();
+
+ mvc = MockMvcBuilders.webAppContextSetup(context)
+ .apply(springSecurity())
+ .build();
+ }
+
+ private void setUp() {
+ Role roleUser = new Role();
+ roleUser.setName("ROLE_USER");
+ mongoTemplate.save(roleUser);
+
+ User user = new User();
+ user.setUsername(USER_NAME);
+ user.setPassword(bCryptPasswordEncoder.encode(PASSWORD));
+
+ UserRole userRole = new UserRole();
+ userRole.setRole(roleUser);
+ user.setUserRoles(new HashSet<>(Collections.singletonList(userRole)));
+ mongoTemplate.save(user);
+
+ User admin = new User();
+ admin.setUsername(ADMIN_NAME);
+ admin.setPassword(bCryptPasswordEncoder.encode(PASSWORD));
+
+ Role roleAdmin = new Role();
+ roleAdmin.setName("ROLE_ADMIN");
+ mongoTemplate.save(roleAdmin);
+
+ UserRole adminRole = new UserRole();
+ adminRole.setRole(roleAdmin);
+ admin.setUserRoles(new HashSet<>(Collections.singletonList(adminRole)));
+ mongoTemplate.save(admin);
+ }
+
+ @Test
+ void givenUserCredentials_whenInvokeUserAuthorizedEndPoint_thenReturn200() throws Exception {
+ mvc.perform(get("/user").with(httpBasic(USER_NAME, PASSWORD)))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void givenUserNotExists_whenInvokeEndPoint_thenReturn401() throws Exception {
+ mvc.perform(get("/user").with(httpBasic("not_existing_user", "password")))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ void givenUserExistsAndWrongPassword_whenInvokeEndPoint_thenReturn401() throws Exception {
+ mvc.perform(get("/user").with(httpBasic(USER_NAME, "wrong_password")))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ void givenUserCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn403() throws Exception {
+ mvc.perform(get("/admin").with(httpBasic(USER_NAME, PASSWORD)))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void givenAdminCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn200() throws Exception {
+ mvc.perform(get("/admin").with(httpBasic(ADMIN_NAME, PASSWORD)))
+ .andExpect(status().isOk());
+
+ mvc.perform(get("/user").with(httpBasic(ADMIN_NAME, PASSWORD)))
+ .andExpect(status().isOk());
+ }
+
+}
From 538c845739ad530589a507fcc49ed50d98ea244a Mon Sep 17 00:00:00 2001
From: kwoyke
Date: Fri, 11 Mar 2022 17:09:33 +0100
Subject: [PATCH 229/235] JAVA-10130: Add/enable missing modules (#11887)
* JAVA-10130: Add apache-pot-2 module to the main pom.xml
* JAVA-10130: Add missing core-java-* modules to the main pom.xml
* JAVA-10130: Add maven-generate-war to the maven-modules pom.xml
* JAVA-10130: Add hibernate-mapping-2 to the persistence-modules pom.xml
* JAVA-10130: Add spring-data-jpa-enterprise-2 to the persistence-modules pom.xml
* JAVA-10130: Add spring-5-autowiring-beans module to the main pom.xml
* JAVA-10130: Add spring-cloud-docker module to the spring-cloud pom.xml
* JAVA-10130: Enable spring-cloud-openfeign module
* JAVA-10130: Add spring-data-rest-2 module to the main pom.xml
* JAVA-10130: Add wildfly-mdb module to the wildfly pom.xml
* JAVA-10130: Add aws-app-sync to the integration-lite-first profile
* JAVA-10130: Add core-java-string-algorithms-3
* JAVA-10130: Add graphql/graphql-dgs
* JAVA-10130: Add spring-di-3 and spring-threads
* JAVA-10130: Add spring-5-webflux-2 and cleanup the main pom.xml
* JAVA-10130: Add language-interop and libraries-rpc
* JAVA-10130: Disable spring-cloud-openfeign module
* JAVA-10478: Add docker module to the main pom.xml
* JAVA-10478: Move docker module to jdk9+ profile
* JAVA-10478: Remove spring-5-autowiring-beans from the main pom.xml
---
maven-modules/pom.xml | 1 +
persistence-modules/pom.xml | 2 +
pom.xml | 89 ++++++++++++++++++++++---------------
spring-cloud/pom.xml | 4 +-
spring-ejb/wildfly/pom.xml | 1 +
5 files changed, 60 insertions(+), 37 deletions(-)
diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml
index 37be581804..0d65e5f9f4 100644
--- a/maven-modules/pom.xml
+++ b/maven-modules/pom.xml
@@ -19,6 +19,7 @@
maven-copy-files
maven-custom-plugin
maven-exec-plugin
+
maven-integration-test
maven-multi-source
maven-plugins
diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml
index 152e58d57b..64a9519a8b 100644
--- a/persistence-modules/pom.xml
+++ b/persistence-modules/pom.xml
@@ -27,6 +27,7 @@
hbase
hibernate5
hibernate-mapping
+ hibernate-mapping-2
hibernate-ogm
hibernate-annotations
hibernate-exceptions
@@ -73,6 +74,7 @@
spring-data-jpa-crud
spring-data-jpa-crud-2
spring-data-jpa-enterprise
+ spring-data-jpa-enterprise-2
spring-data-jpa-filtering
spring-data-jpa-query
spring-data-jpa-query-2
diff --git a/pom.xml b/pom.xml
index b6767c629b..a6202230d4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,9 +7,6 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
-
- spring-5-webflux-2
-
parent-modules
pom
@@ -355,6 +352,7 @@
apache-libraries
apache-olingo
apache-poi
+ apache-poi-2
apache-rocketmq
apache-shiro
apache-spark
@@ -653,6 +651,7 @@
spring-cucumber
spring-data-rest
+ spring-data-rest-2
spring-data-rest-querydsl
spring-di
spring-di-2
@@ -841,6 +840,7 @@
apache-libraries
apache-olingo
apache-poi
+ apache-poi-2
apache-rocketmq
apache-shiro
apache-spark
@@ -855,6 +855,7 @@
atomix
aws
+ aws-app-sync
aws-lambda
aws-reactive
@@ -906,6 +907,7 @@
graphql/graphql-java
+ graphql/graphql-dgs
grpc
gson
guava-modules
@@ -967,6 +969,7 @@
ksqldb
+ language-interop
libraries-2
libraries-3
@@ -981,6 +984,7 @@
libraries-http-2
libraries-io
libraries-primitive
+ libraries-rpc
libraries-security
libraries-server
libraries-server-2
@@ -1096,6 +1100,7 @@
spring-5-reactive-oauth
spring-5-reactive-security
spring-5-webflux
+ spring-5-webflux-2
spring-reactive
spring-activiti
@@ -1128,9 +1133,11 @@
spring-cucumber
spring-data-rest
+ spring-data-rest-2
spring-data-rest-querydsl
spring-di
spring-di-2
+ spring-di-3
spring-drools
spring-ejb
@@ -1168,6 +1175,8 @@
spring-static-resources
spring-swagger-codegen
+ spring-threads
+
spring-vault
spring-vertx
@@ -1317,39 +1326,43 @@
core-java-modules/core-java-9-improvements
core-java-modules/core-java-9-jigsaw
- core-java-modules/core-java-9-streams
- core-java-modules/core-java-10
- core-java-modules/core-java-11
- core-java-modules/core-java-11-2
-
-
-
-
- core-java-modules/core-java-collections-set
- core-java-modules/core-java-collections-maps-4
- core-java-modules/core-java-date-operations-1
- core-java-modules/core-java-datetime-conversion
- core-java-modules/core-java-datetime-string
- core-java-modules/core-java-io-conversions-2
- core-java-modules/core-java-jpms
- core-java-modules/core-java-os
- core-java-modules/core-java-string-algorithms-3
- core-java-modules/core-java-string-operations-3
- core-java-modules/core-java-string-operations-4
- core-java-modules/core-java-time-measurements
- core-java-modules/core-java-networking-3
- core-java-modules/multimodulemavenproject
- ddd-modules
- httpclient-2
- libraries-concurrency
- persistence-modules/sirix
- persistence-modules/spring-data-cassandra-2
- quarkus-vs-springboot
- quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-camel
- testing-modules/testing-assertions
- persistence-modules/fauna
+ core-java-modules/core-java-9-streams
+ core-java-modules/core-java-10
+ core-java-modules/core-java-11
+ core-java-modules/core-java-11-2
+
+
+
+
+
+
+ core-java-modules/core-java-collections-set
+ core-java-modules/core-java-collections-maps-4
+ core-java-modules/core-java-date-operations-1
+ core-java-modules/core-java-datetime-conversion
+ core-java-modules/core-java-datetime-string
+ core-java-modules/core-java-io-conversions-2
+ core-java-modules/core-java-jpms
+ core-java-modules/core-java-os
+ core-java-modules/core-java-string-algorithms-3
+ core-java-modules/core-java-string-operations-3
+ core-java-modules/core-java-string-operations-4
+ core-java-modules/core-java-time-measurements
+ core-java-modules/core-java-networking-3
+ core-java-modules/multimodulemavenproject
+ core-java-modules/core-java-strings
+ ddd-modules
+ docker
+ httpclient-2
+ libraries-concurrency
+ persistence-modules/sirix
+ persistence-modules/spring-data-cassandra-2
+ quarkus-vs-springboot
+ quarkus-jandex
+ spring-boot-modules/spring-boot-cassandre
+ spring-boot-modules/spring-boot-camel
+ testing-modules/testing-assertions
+ persistence-modules/fauna
@@ -1388,6 +1401,8 @@
+
+
core-java-modules/core-java-collections-set
core-java-modules/core-java-collections-maps-4
core-java-modules/core-java-date-operations-1
@@ -1396,6 +1411,7 @@
core-java-modules/core-java-io-conversions-2
core-java-modules/core-java-jpms
core-java-modules/core-java-os
+ core-java-modules/core-java-string-algorithms-3
core-java-modules/core-java-string-operations-3
core-java-modules/core-java-string-operations-4
core-java-modules/core-java-time-measurements
@@ -1403,6 +1419,7 @@
core-java-modules/multimodulemavenproject
core-java-modules/core-java-strings
ddd-modules
+ docker
httpclient-2
libraries-concurrency
persistence-modules/sirix
diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml
index ac810c9a77..75010fbd34 100644
--- a/spring-cloud/pom.xml
+++ b/spring-cloud/pom.xml
@@ -45,9 +45,11 @@
spring-cloud-ribbon-retry
spring-cloud-circuit-breaker
spring-cloud-eureka-self-preservation
-
+
+
spring-cloud-sentinel
spring-cloud-dapr
+ spring-cloud-docker
diff --git a/spring-ejb/wildfly/pom.xml b/spring-ejb/wildfly/pom.xml
index ae90f71b7c..8a6d41ea82 100644
--- a/spring-ejb/wildfly/pom.xml
+++ b/spring-ejb/wildfly/pom.xml
@@ -21,6 +21,7 @@
wildfly-jpa
wildfly-ejb-interfaces
wildfly-ejb
+ wildfly-mdb
From 612dc0be7c8c8a1ba46c565a8ef114f151ed74d3 Mon Sep 17 00:00:00 2001
From: Gaetano Piazzolla
Date: Sat, 12 Mar 2022 19:21:34 +0100
Subject: [PATCH 230/235] BAEL-5358 - Case Insensitive Sorting in MongoDB
(#11815)
* [BAEL-5358] - MongoDB Case Insensitive Ordering.
* [BAEL-5358] - removed comment, indent
* [BAEL-5358] - using junit5 and testcontainers
* [BAEL-5358] - fixed issues for PR
* [BAEL-5358] - removed method-> inline
---
persistence-modules/java-mongodb/pom.xml | 12 ++
.../CaseInsensitiveOrderingLiveTest.java | 108 ++++++++++++++++++
2 files changed, 120 insertions(+)
create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/ordering/caseinsensitive/CaseInsensitiveOrderingLiveTest.java
diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml
index 03229e72bd..88f0d18a5b 100644
--- a/persistence-modules/java-mongodb/pom.xml
+++ b/persistence-modules/java-mongodb/pom.xml
@@ -30,6 +30,18 @@
core
${morphia.version}
+
+ org.testcontainers
+ mongodb
+ 1.16.3
+ test
+
+
+ org.testcontainers
+ junit-jupiter
+ 1.16.3
+ test
+
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/ordering/caseinsensitive/CaseInsensitiveOrderingLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/ordering/caseinsensitive/CaseInsensitiveOrderingLiveTest.java
new file mode 100644
index 0000000000..ec2c332018
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/ordering/caseinsensitive/CaseInsensitiveOrderingLiveTest.java
@@ -0,0 +1,108 @@
+package com.baeldung.ordering.caseinsensitive;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.*;
+import com.mongodb.client.model.Collation;
+import com.mongodb.client.model.Projections;
+import com.mongodb.client.model.Sorts;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.MongoDBContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static com.mongodb.client.model.Aggregates.project;
+import static com.mongodb.client.model.Aggregates.sort;
+import static com.mongodb.client.model.Sorts.ascending;
+import static org.junit.Assert.assertEquals;
+
+@Testcontainers
+class CaseInsensitiveOrderingLiveTest {
+
+ private static MongoCollection userCollections;
+
+ @Container
+ private static final MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
+
+ @BeforeAll
+ private static void setup() {
+
+ MongoClient mongoClient = new MongoClient(mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getMappedPort(27017));
+ MongoDatabase database = mongoClient.getDatabase("test");
+ userCollections = database.getCollection("users");
+
+ List list = new ArrayList<>();
+ list.add(Document.parse("{'name': 'ben', surname: 'ThisField' }"));
+ list.add(Document.parse("{'name': 'aen', surname: 'Does' }"));
+ list.add(Document.parse("{'name': 'Ben', surname: 'Not' }"));
+ list.add(Document.parse("{'name': 'cen', surname: 'Matter' }"));
+ list.add(Document.parse("{'name': 'Aen', surname: 'Really' }"));
+ list.add(Document.parse("{'name': 'Cen', surname: 'TrustMe' }"));
+
+ userCollections.insertMany(list);
+ }
+
+ @Test
+ void givenMongoCollection_whenUsingFindWithSort_caseIsConsideredByDefault() {
+ FindIterable nameDoc = userCollections.find().sort(ascending("name"));
+ MongoCursor cursor = nameDoc.cursor();
+
+ List expectedNamesOrdering = Arrays.asList("Aen", "Ben", "Cen", "aen", "ben", "cen");
+ List actualNamesOrdering = new ArrayList<>();
+ while (cursor.hasNext()) {
+ Document document = cursor.next();
+ actualNamesOrdering.add(document.get("name").toString());
+ }
+
+ assertEquals(expectedNamesOrdering, actualNamesOrdering);
+ }
+
+ @Test
+ void givenMongoCollection_whenUsingFindWithSortAndCollation_caseIsNotConsidered() {
+ FindIterable nameDoc = userCollections.find().sort(ascending("name"))
+ .collation(Collation.builder().locale("en").build());
+ MongoCursor cursor = nameDoc.cursor();
+ List expectedNamesOrdering = Arrays.asList("aen", "Aen", "ben", "Ben", "cen", "Cen");
+ List actualNamesOrdering = new ArrayList<>();
+ while (cursor.hasNext()) {
+ Document document = cursor.next();
+ actualNamesOrdering.add(document.get("name").toString());
+ }
+
+ assertEquals(expectedNamesOrdering, actualNamesOrdering);
+
+ }
+
+ @Test
+ void givenMongoCollection_whenUsingFindWithSortAndAggregate_caseIsNotConsidered() {
+
+ Bson projectBson = project(
+ Projections.fields(
+ Projections.include("name", "surname"),
+ Projections.computed("lowerName", Projections.computed("$toLower", "$name"))));
+
+ AggregateIterable nameDoc = userCollections.aggregate(
+ Arrays.asList(projectBson,
+ sort(Sorts.ascending("lowerName"))));
+
+ MongoCursor cursor = nameDoc.cursor();
+
+ List expectedNamesOrdering = Arrays.asList("aen", "Aen", "ben", "Ben", "cen", "Cen");
+ List actualNamesOrdering = new ArrayList<>();
+ while (cursor.hasNext()) {
+ Document document = cursor.next();
+ actualNamesOrdering.add(document.get("name").toString());
+ }
+
+ assertEquals(expectedNamesOrdering, actualNamesOrdering);
+ }
+
+
+}
From d30c353d35339d74b9b883045e21728435368266 Mon Sep 17 00:00:00 2001
From: Kai Yuan
Date: Sat, 12 Mar 2022 20:09:18 +0100
Subject: [PATCH 231/235] pretty-print xml in java (#11899)
* pretty-print xml in java
* simplified pom.xml
---
pom.xml | 1 +
xml-2/.gitignore | 1 +
xml-2/README.md | 5 +
xml-2/pom.xml | 50 ++++++++++
.../xml/prettyprint/XmlPrettyPrinter.java | 91 +++++++++++++++++++
xml-2/src/main/resources/logback.xml | 13 +++
xml-2/src/main/resources/xml/emails.xml | 4 +
xml-2/src/main/resources/xml/prettyprint.xsl | 11 +++
8 files changed, 176 insertions(+)
create mode 100644 xml-2/.gitignore
create mode 100644 xml-2/README.md
create mode 100644 xml-2/pom.xml
create mode 100644 xml-2/src/main/java/com/baeldung/xml/prettyprint/XmlPrettyPrinter.java
create mode 100644 xml-2/src/main/resources/logback.xml
create mode 100644 xml-2/src/main/resources/xml/emails.xml
create mode 100644 xml-2/src/main/resources/xml/prettyprint.xsl
diff --git a/pom.xml b/pom.xml
index a6202230d4..daaf9db6d2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1206,6 +1206,7 @@
wicket
wildfly
xml
+ xml-2
xstream
diff --git a/xml-2/.gitignore b/xml-2/.gitignore
new file mode 100644
index 0000000000..68b918851c
--- /dev/null
+++ b/xml-2/.gitignore
@@ -0,0 +1 @@
+xml/.idea
diff --git a/xml-2/README.md b/xml-2/README.md
new file mode 100644
index 0000000000..e3c6ed6443
--- /dev/null
+++ b/xml-2/README.md
@@ -0,0 +1,5 @@
+## XML
+
+This module contains articles about eXtensible Markup Language (XML)
+
+### Relevant Articles:
\ No newline at end of file
diff --git a/xml-2/pom.xml b/xml-2/pom.xml
new file mode 100644
index 0000000000..025ad682ad
--- /dev/null
+++ b/xml-2/pom.xml
@@ -0,0 +1,50 @@
+
+
+ 4.0.0
+ xml-2
+ 0.1-SNAPSHOT
+ xml-2
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+ org.dom4j
+ dom4j
+ ${dom4j.version}
+
+
+
+
+ xml-2
+
+
+ src/main/resources
+ true
+
+
+
+
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+
+
+
+
+ 2.1.3
+
+
+
\ No newline at end of file
diff --git a/xml-2/src/main/java/com/baeldung/xml/prettyprint/XmlPrettyPrinter.java b/xml-2/src/main/java/com/baeldung/xml/prettyprint/XmlPrettyPrinter.java
new file mode 100644
index 0000000000..85fd751325
--- /dev/null
+++ b/xml-2/src/main/java/com/baeldung/xml/prettyprint/XmlPrettyPrinter.java
@@ -0,0 +1,91 @@
+package com.baeldung.xml.prettyprint;
+
+import org.dom4j.DocumentHelper;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.XMLWriter;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import java.io.*;
+
+public class XmlPrettyPrinter {
+
+ public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {
+
+ try {
+ final InputSource src = new InputSource(new StringReader(xmlString));
+ final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
+
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ transformerFactory.setAttribute("indent-number", indent);
+ Transformer transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(readPrettyPrintXslt())));
+ // Using the default transformer will create empty lines in Java9+
+// Transformer transformer = transformerFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ // Alternatively, we can set indent-size on the transformer object
+ // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
+ Writer out = new StringWriter();
+ transformer.transform(new DOMSource(document), new StreamResult(out));
+ return out.toString();
+ } catch (Exception e) {
+ throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
+ }
+ }
+
+
+ public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
+ try {
+ final OutputFormat format = OutputFormat.createPrettyPrint();
+ format.setEncoding("UTF-8");
+ format.setIndentSize(indent);
+ format.setSuppressDeclaration(skipDeclaration);
+
+ final org.dom4j.Document document = DocumentHelper.parseText(xmlString);
+ final StringWriter sw = new StringWriter();
+ final XMLWriter writer = new XMLWriter(sw, format);
+ writer.write(document);
+ return sw.toString();
+ } catch (Exception e) {
+ throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
+ }
+ }
+
+ public static void main(String[] args) throws IOException {
+ InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
+ String xmlString = readFromInputStream(inputStream);
+ System.out.println("Pretty printing by Transformer");
+ System.out.println("=============================================");
+ System.out.println(prettyPrintByTransformer(xmlString, 2, true));
+ System.out.println("=============================================");
+ System.out.println("Pretty printing by Dom4j");
+ System.out.println("=============================================");
+ System.out.println(prettyPrintByDom4j(xmlString, 8, false));
+ System.out.println("=============================================");
+ }
+
+
+ private static String readPrettyPrintXslt() throws IOException {
+ InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl");
+ return readFromInputStream(inputStream);
+ }
+
+ private static String readFromInputStream(InputStream inputStream) throws IOException {
+ StringBuilder resultStringBuilder = new StringBuilder();
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ resultStringBuilder.append(line).append("\n");
+ }
+ }
+ return resultStringBuilder.toString();
+ }
+}
diff --git a/xml-2/src/main/resources/logback.xml b/xml-2/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/xml-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/xml-2/src/main/resources/xml/emails.xml b/xml-2/src/main/resources/xml/emails.xml
new file mode 100644
index 0000000000..03338a28fc
--- /dev/null
+++ b/xml-2/src/main/resources/xml/emails.xml
@@ -0,0 +1,4 @@
+ Kai Amanda 2018-03-05
+I am flying to you
+Jerry Tom 1992-08-08 Hey Tom, catch me if you can!
+
\ No newline at end of file
diff --git a/xml-2/src/main/resources/xml/prettyprint.xsl b/xml-2/src/main/resources/xml/prettyprint.xsl
new file mode 100644
index 0000000000..3941269f40
--- /dev/null
+++ b/xml-2/src/main/resources/xml/prettyprint.xsl
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
From b8176a265a2bf1bd7f32ee34a3059347409d86d0 Mon Sep 17 00:00:00 2001
From: sampadawagde
Date: Sun, 13 Mar 2022 14:48:44 +0530
Subject: [PATCH 232/235] JAVA-10138 - Fix formatting of POMs
---
apache-olingo/pom.xml | 2 +-
.../core-java-9-new-features/pom.xml | 44 +++++-----
.../core-java-concurrency-basic-3/pom.xml | 2 +-
.../core-java-date-operations-1/pom.xml | 1 -
core-java-modules/core-java-jar/pom.xml | 2 +-
core-java-modules/core-java-jvm/pom.xml | 15 ++--
.../core-java-serialization/pom.xml | 1 -
.../core-java-string-algorithms-3/pom.xml | 1 +
core-java-modules/core-java/pom.xml | 1 -
core-java-modules/pom.xml | 2 +-
ddd-modules/infrastructure/pom.xml | 4 +-
ddd-modules/mainapp/pom.xml | 3 +-
ddd-modules/ordercontext/pom.xml | 4 +-
ddd-modules/pom.xml | 8 +-
ddd-modules/sharedkernel/pom.xml | 4 +-
ddd-modules/shippingcontext/pom.xml | 4 +-
geotools/pom.xml | 16 ++--
graphql/graphql-dgs/pom.xml | 6 +-
httpclient-2/pom.xml | 5 +-
java-collections-maps-3/pom.xml | 1 -
javax-servlets-2/pom.xml | 3 +-
javaxval/pom.xml | 38 ++-------
jta/pom.xml | 2 +-
ksqldb/pom.xml | 1 -
libraries-concurrency/pom.xml | 6 +-
lombok-2/pom.xml | 2 +-
lombok/pom.xml | 15 +---
.../maven-classifier-example-consumer/pom.xml | 38 ++++-----
.../maven-classifier-example-provider/pom.xml | 81 ++++++++++---------
maven-modules/maven-classifier/pom.xml | 7 +-
maven-modules/maven-generate-war/pom.xml | 2 +-
.../maven-simple/parent-project/core/pom.xml | 2 +-
.../maven-simple/parent-project/pom.xml | 3 +-
.../parent-project/service/pom.xml | 2 +-
.../parent-project/webapp/pom.xml | 2 +-
metrics/pom.xml | 2 +-
netty/pom.xml | 11 ++-
patterns/enterprise-patterns/pom.xml | 40 ++++-----
.../hibernate-mapping-2/pom.xml | 32 ++++----
persistence-modules/java-cassandra/pom.xml | 2 +-
persistence-modules/spring-data-jdbc/pom.xml | 2 +-
.../spring-data-jpa-query-3/pom.xml | 2 +-
.../spring-hibernate-5/pom.xml | 32 ++++----
.../pom.xml | 2 +-
spring-5-data-reactive/pom.xml | 2 +-
spring-5-reactive-3/pom.xml | 1 +
spring-activiti/pom.xml | 2 +-
.../spring-boot-multiple-datasources/pom.xml | 6 +-
.../spring-boot-swagger-keycloak/pom.xml | 2 +-
.../spring-boot-swagger/pom.xml | 2 +-
.../zookeeper-config/pom.xml | 2 +-
.../pom.xml | 12 +--
spring-cloud/spring-cloud-eureka/pom.xml | 16 ++--
spring-cloud/spring-cloud-functions/pom.xml | 2 +-
spring-cloud/spring-cloud-gateway/pom.xml | 43 +++++-----
spring-cloud/spring-cloud-kubernetes/pom.xml | 18 ++---
.../spring-cloud-load-balancer/pom.xml | 6 +-
.../spring-cloud-loadbalancer-client/pom.xml | 36 +++++----
.../spring-cloud-loadbalancer-server/pom.xml | 15 ++--
.../eureka-client/pom.xml | 2 +-
.../eureka-server/pom.xml | 2 +-
.../zuul-server/pom.xml | 4 +-
.../spring-zuul-rate-limiting/pom.xml | 2 +-
spring-ejb/ejb-beans/pom.xml | 1 -
spring-reactive/pom.xml | 7 +-
.../spring-5-security-oauth/pom.xml | 7 +-
.../spring-security-legacy-oidc/pom.xml | 6 +-
.../spring-security-web-boot-1/pom.xml | 1 -
.../spring-security-web-boot-3/pom.xml | 5 +-
spring-web-modules/pom.xml | 2 +-
.../spring-mvc-basics-5/pom.xml | 2 +-
testing-modules/cucumber/pom.xml | 1 -
testing-modules/testng_command_line/pom.xml | 7 +-
73 files changed, 308 insertions(+), 361 deletions(-)
diff --git a/apache-olingo/pom.xml b/apache-olingo/pom.xml
index 5de0dfd511..25aab0ec97 100644
--- a/apache-olingo/pom.xml
+++ b/apache-olingo/pom.xml
@@ -83,4 +83,4 @@
2.0.11
-
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-new-features/pom.xml b/core-java-modules/core-java-9-new-features/pom.xml
index ce90a0f04a..78ffaff010 100644
--- a/core-java-modules/core-java-9-new-features/pom.xml
+++ b/core-java-modules/core-java-9-new-features/pom.xml
@@ -34,6 +34,28 @@
+
+ core-java-9-new-features
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+
+
+
+ apache.snapshots
+ https://repository.apache.org/snapshots/
+
+
+
incubator-features
@@ -126,28 +148,6 @@
-
- core-java-9-new-features
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${maven.compiler.source}
- ${maven.compiler.target}
-
-
-
-
-
-
-
- apache.snapshots
- https://repository.apache.org/snapshots/
-
-
-
3.0.0
4.0.2
diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml
index 20615e3250..7771d1200c 100644
--- a/core-java-modules/core-java-concurrency-basic-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml
@@ -24,4 +24,4 @@
-
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml
index ea9f94fa56..c5d46723d8 100644
--- a/core-java-modules/core-java-date-operations-1/pom.xml
+++ b/core-java-modules/core-java-date-operations-1/pom.xml
@@ -25,7 +25,6 @@
commons-lang3
${commons-lang3.version}
-
com.darwinsys
hirondelle-date4j
diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml
index 714a370287..19da9b8a56 100644
--- a/core-java-modules/core-java-jar/pom.xml
+++ b/core-java-modules/core-java-jar/pom.xml
@@ -259,7 +259,7 @@
-
+
diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml
index e4c0f949c2..d26c72323f 100644
--- a/core-java-modules/core-java-jvm/pom.xml
+++ b/core-java-modules/core-java-jvm/pom.xml
@@ -64,13 +64,6 @@
-
- 3.27.0-GA
- 1.8.0
- 0.10
- 8.0.1
- 6.5.0
-
@@ -181,4 +174,12 @@
+
+ 3.27.0-GA
+ 1.8.0
+ 0.10
+ 8.0.1
+ 6.5.0
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml
index 315ed8cdad..c82ae9d1d6 100644
--- a/core-java-modules/core-java-serialization/pom.xml
+++ b/core-java-modules/core-java-serialization/pom.xml
@@ -64,7 +64,6 @@
true
-
org.apache.maven.plugins
diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml
index dc8ad3851d..147ea22375 100644
--- a/core-java-modules/core-java-string-algorithms-3/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-3/pom.xml
@@ -54,4 +54,5 @@
1.7
3.12.0
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml
index 188c6a6f63..bb19b525d0 100644
--- a/core-java-modules/core-java/pom.xml
+++ b/core-java-modules/core-java/pom.xml
@@ -69,7 +69,6 @@
true
-
org.apache.maven.plugins
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index 60319b4de4..2f684beea0 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -137,4 +137,4 @@
-
+
\ No newline at end of file
diff --git a/ddd-modules/infrastructure/pom.xml b/ddd-modules/infrastructure/pom.xml
index abf90935c3..232e5ff4b4 100644
--- a/ddd-modules/infrastructure/pom.xml
+++ b/ddd-modules/infrastructure/pom.xml
@@ -1,13 +1,11 @@
-
4.0.0
com.baeldung.dddmodules.infrastructure
infrastructure
1.0
-
jar
diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml
index 6b913df979..a2d3b8f3ea 100644
--- a/ddd-modules/mainapp/pom.xml
+++ b/ddd-modules/mainapp/pom.xml
@@ -1,6 +1,5 @@
-
4.0.0
diff --git a/ddd-modules/ordercontext/pom.xml b/ddd-modules/ordercontext/pom.xml
index 8dee3a5148..eaf44badd3 100644
--- a/ddd-modules/ordercontext/pom.xml
+++ b/ddd-modules/ordercontext/pom.xml
@@ -1,6 +1,5 @@
-
4.0.0
@@ -13,7 +12,6 @@
com.baeldung.dddmodules
ddd-modules
1.0
- ../
diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml
index 134a9d0566..d2932ee515 100644
--- a/ddd-modules/pom.xml
+++ b/ddd-modules/pom.xml
@@ -1,6 +1,5 @@
-
4.0.0
@@ -14,7 +13,6 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../
@@ -70,10 +68,8 @@
9
9
-
3.8.1
-
1.0
-
+
\ No newline at end of file
diff --git a/ddd-modules/sharedkernel/pom.xml b/ddd-modules/sharedkernel/pom.xml
index 1afddf1e22..3966e1c26e 100644
--- a/ddd-modules/sharedkernel/pom.xml
+++ b/ddd-modules/sharedkernel/pom.xml
@@ -1,6 +1,5 @@
-
4.0.0
@@ -13,7 +12,6 @@
com.baeldung.dddmodules
ddd-modules
1.0
- ../
diff --git a/ddd-modules/shippingcontext/pom.xml b/ddd-modules/shippingcontext/pom.xml
index 25b5882ef1..a6e6167b69 100644
--- a/ddd-modules/shippingcontext/pom.xml
+++ b/ddd-modules/shippingcontext/pom.xml
@@ -1,6 +1,5 @@
-
4.0.0
@@ -13,7 +12,6 @@
com.baeldung.dddmodules
ddd-modules
1.0
- ../
diff --git a/geotools/pom.xml b/geotools/pom.xml
index b9a6a7c91f..05cae922a4 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -15,6 +15,14 @@
1.0.0-SNAPSHOT
+
+
+ osgeo-release
+ OSGeo Repository
+ https://repo.osgeo.org/repository/release/
+
+
+
org.geotools
@@ -33,14 +41,6 @@
-
-
- osgeo-release
- OSGeo Repository
- https://repo.osgeo.org/repository/release/
-
-
-
15.2
15.2
diff --git a/graphql/graphql-dgs/pom.xml b/graphql/graphql-dgs/pom.xml
index 1dc3630276..6165ae839f 100644
--- a/graphql/graphql-dgs/pom.xml
+++ b/graphql/graphql-dgs/pom.xml
@@ -33,26 +33,22 @@
spring-boot-starter
2.6.2
-
org.springframework.boot
spring-boot-starter-test
2.6.2
test
-
com.netflix.graphql.dgs.codegen
graphql-dgs-codegen-client-core
5.1.14
-
org.springframework.boot
spring-boot-starter-web
2.6.2
-
com.netflix.graphql.dgs
graphql-dgs-spring-boot-starter
@@ -88,4 +84,4 @@
-
+
\ No newline at end of file
diff --git a/httpclient-2/pom.xml b/httpclient-2/pom.xml
index 85fc1d87e7..287ff27e35 100644
--- a/httpclient-2/pom.xml
+++ b/httpclient-2/pom.xml
@@ -1,6 +1,7 @@
-
+
4.0.0
httpclient-2
0.1-SNAPSHOT
diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml
index a54061404d..729b357b76 100644
--- a/java-collections-maps-3/pom.xml
+++ b/java-collections-maps-3/pom.xml
@@ -22,7 +22,6 @@
junit-jupiter-api
5.8.1
-
org.springframework
spring-core
diff --git a/javax-servlets-2/pom.xml b/javax-servlets-2/pom.xml
index 34c00c3d05..5d8310f2b2 100644
--- a/javax-servlets-2/pom.xml
+++ b/javax-servlets-2/pom.xml
@@ -57,4 +57,5 @@
4.5.13
4.0.1
-
+
+
\ No newline at end of file
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 4131ddeb97..e6ecee6cfb 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -37,35 +37,13 @@
-
+
6.0.13.Final
@@ -77,4 +55,4 @@
5.0.2.RELEASE
-
+
\ No newline at end of file
diff --git a/jta/pom.xml b/jta/pom.xml
index e62c480c81..906d28a7ea 100644
--- a/jta/pom.xml
+++ b/jta/pom.xml
@@ -15,7 +15,7 @@
0.0.1-SNAPSHOT
../parent-boot-2
-
+
diff --git a/ksqldb/pom.xml b/ksqldb/pom.xml
index ee4906090f..e55398d635 100644
--- a/ksqldb/pom.xml
+++ b/ksqldb/pom.xml
@@ -11,7 +11,6 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
- ../pom.xml
diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml
index d8f48a1959..eb581ce3a0 100644
--- a/libraries-concurrency/pom.xml
+++ b/libraries-concurrency/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
libraries-concurrency
libraries-concurrency
@@ -78,5 +78,5 @@
0.8.0
-
+
\ No newline at end of file
diff --git a/lombok-2/pom.xml b/lombok-2/pom.xml
index 3c67e959a4..bde328444e 100644
--- a/lombok-2/pom.xml
+++ b/lombok-2/pom.xml
@@ -22,4 +22,4 @@
-
+
\ No newline at end of file
diff --git a/lombok/pom.xml b/lombok/pom.xml
index d4f89ab4f2..24a04783d1 100644
--- a/lombok/pom.xml
+++ b/lombok/pom.xml
@@ -62,18 +62,9 @@
false
-
+
diff --git a/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
index cbf046ed5a..b280f21b4b 100644
--- a/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
+++ b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml
@@ -1,22 +1,16 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ maven-classifier-example-consumer
+
maven-classifier
com.baeldung
0.0.1-SNAPSHOT
- 4.0.0
-
- maven-classifier-example-consumer
-
-
- 8
- 8
-
-
com.baeldung
@@ -29,13 +23,14 @@
0.0.1-SNAPSHOT
arbitrary
-
-
-
-
-
-
-
+
+
+
+
+
+
+
com.baeldung
maven-classifier-example-provider
@@ -50,4 +45,9 @@
-
+
+ 8
+ 8
+
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml b/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
index 12cb4fa1a2..111996c995 100644
--- a/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
+++ b/maven-modules/maven-classifier/maven-classifier-example-provider/pom.xml
@@ -1,9 +1,10 @@
-
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
+ maven-classifier-example-provider
+ 0.0.1-SNAPSHOT
maven-classifier
@@ -11,15 +12,6 @@
0.0.1-SNAPSHOT
- maven-classifier-example-provider
- 0.0.1-SNAPSHOT
-
-
- 8
- 8
-
-
-
@@ -39,21 +31,22 @@
true
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -76,18 +69,19 @@
test-jar
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
@@ -119,4 +113,11 @@
-
+
+
+ 8
+ 8
+
+
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-classifier/pom.xml b/maven-modules/maven-classifier/pom.xml
index 6b75f60893..ba5f248ff6 100644
--- a/maven-modules/maven-classifier/pom.xml
+++ b/maven-modules/maven-classifier/pom.xml
@@ -1,9 +1,8 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
maven-classifier
pom
0.0.1-SNAPSHOT
@@ -24,4 +23,4 @@
8
-
+
\ No newline at end of file
diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml
index b388cfdadd..51eb54846c 100644
--- a/maven-modules/maven-generate-war/pom.xml
+++ b/maven-modules/maven-generate-war/pom.xml
@@ -6,8 +6,8 @@
com.baeldung
maven-generate-war
0.0.1-SNAPSHOT
- war
maven-generate-war
+ war
Spring boot project to demonstrate war file generation
diff --git a/maven-modules/maven-simple/parent-project/core/pom.xml b/maven-modules/maven-simple/parent-project/core/pom.xml
index ec25c9ace5..963f8edf6c 100644
--- a/maven-modules/maven-simple/parent-project/core/pom.xml
+++ b/maven-modules/maven-simple/parent-project/core/pom.xml
@@ -13,4 +13,4 @@
1.0-SNAPSHOT
-
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/parent-project/pom.xml b/maven-modules/maven-simple/parent-project/pom.xml
index a68f8e63bc..0b8fbdffab 100644
--- a/maven-modules/maven-simple/parent-project/pom.xml
+++ b/maven-modules/maven-simple/parent-project/pom.xml
@@ -19,4 +19,5 @@
service
webapp
-
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/parent-project/service/pom.xml b/maven-modules/maven-simple/parent-project/service/pom.xml
index 1953ec8638..04cb1151e1 100644
--- a/maven-modules/maven-simple/parent-project/service/pom.xml
+++ b/maven-modules/maven-simple/parent-project/service/pom.xml
@@ -13,4 +13,4 @@
1.0-SNAPSHOT
-
+
\ No newline at end of file
diff --git a/maven-modules/maven-simple/parent-project/webapp/pom.xml b/maven-modules/maven-simple/parent-project/webapp/pom.xml
index bd13c5aeb8..ece8a0dd11 100644
--- a/maven-modules/maven-simple/parent-project/webapp/pom.xml
+++ b/maven-modules/maven-simple/parent-project/webapp/pom.xml
@@ -13,4 +13,4 @@
1.0-SNAPSHOT
-
+
\ No newline at end of file
diff --git a/metrics/pom.xml b/metrics/pom.xml
index abdfb14dc6..37b10ef484 100644
--- a/metrics/pom.xml
+++ b/metrics/pom.xml
@@ -92,4 +92,4 @@
1.1.0
-
+
\ No newline at end of file
diff --git a/netty/pom.xml b/netty/pom.xml
index 817b1f2e70..c235ec9f4a 100644
--- a/netty/pom.xml
+++ b/netty/pom.xml
@@ -1,6 +1,7 @@
-
+
4.0.0
netty
0.0.1-SNAPSHOT
@@ -11,20 +12,18 @@
parent-modules
1.0.0-SNAPSHOT
-
+
io.netty
netty-all
${netty.version}
-
-
+
org.conscrypt
conscrypt-openjdk-uber
${conscrypt-openjdk-uber.version}
-
diff --git a/patterns/enterprise-patterns/pom.xml b/patterns/enterprise-patterns/pom.xml
index 999b359170..2228cc9505 100644
--- a/patterns/enterprise-patterns/pom.xml
+++ b/patterns/enterprise-patterns/pom.xml
@@ -16,6 +16,25 @@
wire-tap
+
+
+
+ org.apache.camel.springboot
+ camel-spring-boot-dependencies
+ ${camel.version}
+ pom
+ import
+
+
+ org.apache.logging.log4j
+ log4j-bom
+ ${log4j2.version}
+ import
+ pom
+
+
+
+
org.apache.camel.springboot
@@ -39,25 +58,6 @@
-
-
-
- org.apache.camel.springboot
- camel-spring-boot-dependencies
- ${camel.version}
- pom
- import
-
-
- org.apache.logging.log4j
- log4j-bom
- ${log4j2.version}
- import
- pom
-
-
-
-
@@ -70,7 +70,7 @@
3.7.4
2.2.2.RELEASE
- 2.17.1
+ 2.17.1
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml
index 10c07c95eb..47b00797bc 100644
--- a/persistence-modules/hibernate-mapping-2/pom.xml
+++ b/persistence-modules/hibernate-mapping-2/pom.xml
@@ -54,22 +54,22 @@
com.h2database
h2
${h2.version}
-
-
- com.sun.xml.bind
- jaxb-core
- ${com.sun.xml.version}
-
-
- javax.xml.bind
- jaxb-api
- ${javax.xml.bind.version}
-
-
- com.sun.xml.bind
- jaxb-impl
- ${com.sun.xml.version}
-
+
+
+ com.sun.xml.bind
+ jaxb-core
+ ${com.sun.xml.version}
+
+
+ javax.xml.bind
+ jaxb-api
+ ${javax.xml.bind.version}
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ ${com.sun.xml.version}
+
diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml
index b0b98b040a..0dd148e528 100644
--- a/persistence-modules/java-cassandra/pom.xml
+++ b/persistence-modules/java-cassandra/pom.xml
@@ -77,4 +77,4 @@
4.1.71.Final
-
+
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jdbc/pom.xml b/persistence-modules/spring-data-jdbc/pom.xml
index 168b171337..630fe141b3 100644
--- a/persistence-modules/spring-data-jdbc/pom.xml
+++ b/persistence-modules/spring-data-jdbc/pom.xml
@@ -36,4 +36,4 @@
-
+
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-query-3/pom.xml b/persistence-modules/spring-data-jpa-query-3/pom.xml
index 66a4486bc8..135d31aaba 100644
--- a/persistence-modules/spring-data-jpa-query-3/pom.xml
+++ b/persistence-modules/spring-data-jpa-query-3/pom.xml
@@ -29,4 +29,4 @@
-
+
\ No newline at end of file
diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml
index ba18c5a221..3f5d00733d 100644
--- a/persistence-modules/spring-hibernate-5/pom.xml
+++ b/persistence-modules/spring-hibernate-5/pom.xml
@@ -107,22 +107,22 @@
com.h2database
h2
${h2.version}
-
-
- com.sun.xml.bind
- jaxb-core
- ${com.sun.xml.version}
-
-
- javax.xml.bind
- jaxb-api
- ${javax.xml.bind.version}
-
-
- com.sun.xml.bind
- jaxb-impl
- ${com.sun.xml.version}
-
+
+
+ com.sun.xml.bind
+ jaxb-core
+ ${com.sun.xml.version}
+
+
+ javax.xml.bind
+ jaxb-api
+ ${javax.xml.bind.version}
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ ${com.sun.xml.version}
+
diff --git a/quarkus-jandex/hello-sender-application-properties/pom.xml b/quarkus-jandex/hello-sender-application-properties/pom.xml
index f63bb9be81..6658123bee 100644
--- a/quarkus-jandex/hello-sender-application-properties/pom.xml
+++ b/quarkus-jandex/hello-sender-application-properties/pom.xml
@@ -23,4 +23,4 @@
-
+
\ No newline at end of file
diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml
index 023eda856b..24971c0289 100644
--- a/spring-5-data-reactive/pom.xml
+++ b/spring-5-data-reactive/pom.xml
@@ -13,7 +13,7 @@
0.0.1-SNAPSHOT
../parent-boot-2
-
+
diff --git a/spring-5-reactive-3/pom.xml b/spring-5-reactive-3/pom.xml
index 89af34732f..fea72cc736 100644
--- a/spring-5-reactive-3/pom.xml
+++ b/spring-5-reactive-3/pom.xml
@@ -41,4 +41,5 @@
1.0.1.RELEASE
+
\ No newline at end of file
diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml
index 2ede13a152..898f88285b 100644
--- a/spring-activiti/pom.xml
+++ b/spring-activiti/pom.xml
@@ -16,7 +16,7 @@
0.0.1-SNAPSHOT
../parent-boot-1
-
+
diff --git a/spring-boot-modules/spring-boot-multiple-datasources/pom.xml b/spring-boot-modules/spring-boot-multiple-datasources/pom.xml
index d66095bc2c..9355de8a36 100644
--- a/spring-boot-modules/spring-boot-multiple-datasources/pom.xml
+++ b/spring-boot-modules/spring-boot-multiple-datasources/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
spring-boot-multiple-datasources
0.1.0-SNAPSHOT
@@ -55,4 +55,4 @@
2.6.3
-
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
index a7f3e01014..de2c8c68c4 100644
--- a/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger-keycloak/pom.xml
@@ -72,4 +72,4 @@
2.17.1
-
+
\ No newline at end of file
diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml
index b6ed50534e..749442c225 100644
--- a/spring-boot-modules/spring-boot-swagger/pom.xml
+++ b/spring-boot-modules/spring-boot-swagger/pom.xml
@@ -84,4 +84,4 @@
3.1.1
-
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
index bdd75d0635..7700a2219d 100644
--- a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
+++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml
@@ -45,7 +45,7 @@
2.0.0.RELEASE
3.4.13
- 2.17.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml b/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
index e22ad6b7c9..5000adc164 100644
--- a/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
+++ b/spring-cloud/spring-cloud-eureka-self-preservation/pom.xml
@@ -14,7 +14,12 @@
spring-cloud
1.0.0-SNAPSHOT
-
+
+
+ spring-cloud-eureka-server
+ spring-cloud-eureka-client
+
+
@@ -27,11 +32,6 @@
-
- spring-cloud-eureka-server
- spring-cloud-eureka-client
-
-
org.springframework.boot
diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml
index 795eab7d6e..63190f7f20 100644
--- a/spring-cloud/spring-cloud-eureka/pom.xml
+++ b/spring-cloud/spring-cloud-eureka/pom.xml
@@ -14,7 +14,14 @@
spring-cloud
1.0.0-SNAPSHOT
-
+
+
+ spring-cloud-eureka-server
+ spring-cloud-eureka-client
+ spring-cloud-eureka-feign-client
+ spring-cloud-eureka-feign-client-integration-test
+
+
@@ -27,13 +34,6 @@
-
- spring-cloud-eureka-server
- spring-cloud-eureka-client
- spring-cloud-eureka-feign-client
- spring-cloud-eureka-feign-client-integration-test
-
-
org.springframework.boot
diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml
index 3dc68e2824..d9f90c7a56 100644
--- a/spring-cloud/spring-cloud-functions/pom.xml
+++ b/spring-cloud/spring-cloud-functions/pom.xml
@@ -10,7 +10,7 @@
jar
Demo project for Spring Cloud Function
-
+
com.baeldung.spring.cloud
spring-cloud
1.0.0-SNAPSHOT
diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml
index a352bbd4e4..e8949cc039 100644
--- a/spring-cloud/spring-cloud-gateway/pom.xml
+++ b/spring-cloud/spring-cloud-gateway/pom.xml
@@ -83,31 +83,28 @@
org.springframework.boot
spring-boot-devtools
-
org.springframework.boot
spring-boot-starter-oauth2-resource-server
-
org.springframework.boot
spring-boot-starter-oauth2-client
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.8.1
-
- ${java.version}
- ${java.version}
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.1
+
+ ${java.version}
+ ${java.version}
+
+
org.springframework.boot
spring-boot-maven-plugin
@@ -123,15 +120,6 @@
-
-
-
- 6.0.2.Final
- 0.7.2
- 9.19
-
-
-
quotes-application
@@ -177,7 +165,6 @@
-
gateway-url-rewrite
@@ -192,6 +179,16 @@
-
+
+
+
+
+
+ 6.0.2.Final
+ 0.7.2
+ 9.19
+
+
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml
index c41c500a1b..698bdce1e5 100644
--- a/spring-cloud/spring-cloud-kubernetes/pom.xml
+++ b/spring-cloud/spring-cloud-kubernetes/pom.xml
@@ -15,6 +15,15 @@
1.0.0-SNAPSHOT
+
+ kubernetes-minikube/demo-frontend
+ kubernetes-minikube/demo-backend
+ kubernetes-selfhealing/liveness-example
+ kubernetes-selfhealing/readiness-example
+ kubernetes-guide/client-service
+ kubernetes-guide/travel-agency-service
+
+
@@ -27,15 +36,6 @@
-
- kubernetes-minikube/demo-frontend
- kubernetes-minikube/demo-backend
- kubernetes-selfhealing/liveness-example
- kubernetes-selfhealing/readiness-example
- kubernetes-guide/client-service
- kubernetes-guide/travel-agency-service
-
-
2021.0.0
diff --git a/spring-cloud/spring-cloud-load-balancer/pom.xml b/spring-cloud/spring-cloud-load-balancer/pom.xml
index 65cf83de09..3b81def641 100644
--- a/spring-cloud/spring-cloud-load-balancer/pom.xml
+++ b/spring-cloud/spring-cloud-load-balancer/pom.xml
@@ -19,7 +19,7 @@
spring-cloud-loadbalancer-server
spring-cloud-loadbalancer-client
-
+
@@ -44,7 +44,7 @@
2.6.1
2021.0.0
- 2.17.1
+ 2.17.1
-
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-client/pom.xml b/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-client/pom.xml
index fc6e2854aa..c141452695 100644
--- a/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-client/pom.xml
+++ b/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-client/pom.xml
@@ -3,17 +3,30 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
+ com.baeldung.springcloud.loadbalancer
+ spring-cloud-loadbalancer-client
+ 0.0.1-SNAPSHOT
+ spring-cloud-loadbalancer-client
+ Spring Cloud Load Balancer Demo - Client
+
com.baeldung.spring.cloud
spring-cloud-loadbalancer
1.0.0-SNAPSHOT
- com.baeldung.springcloud.loadbalancer
- spring-cloud-loadbalancer-client
- 0.0.1-SNAPSHOT
- spring-cloud-loadbalancer-client
- Spring Cloud Load Balancer Demo - Client
+
+
+
+ org.springframework.cloud
+ spring-cloud-dependencies
+ ${spring-cloud.version}
+ pom
+ import
+
+
+
+
org.springframework.boot
@@ -30,17 +43,6 @@
test
-
-
-
- org.springframework.cloud
- spring-cloud-dependencies
- ${spring-cloud.version}
- pom
- import
-
-
-
@@ -51,4 +53,4 @@
-
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-server/pom.xml b/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-server/pom.xml
index 139996994d..3e61ecc90d 100644
--- a/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-server/pom.xml
+++ b/spring-cloud/spring-cloud-load-balancer/spring-cloud-loadbalancer-server/pom.xml
@@ -3,24 +3,23 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
- com.baeldung.spring.cloud
- spring-cloud-loadbalancer
- 1.0.0-SNAPSHOT
-
-
com.baeldung.spring.cloud.loadbalancer
spring-cloud-loadbalancer-server
0.0.1-SNAPSHOT
spring-cloud-loadbalancer-server
Spring Cloud Load Balancer Demo - Server
+
+ com.baeldung.spring.cloud
+ spring-cloud-loadbalancer
+ 1.0.0-SNAPSHOT
+
+
org.springframework.boot
spring-boot-starter-web
-
org.springframework.boot
spring-boot-starter-test
@@ -37,4 +36,4 @@
-
+
\ No newline at end of file
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
index b2cb66744b..3960cfde5d 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml
@@ -52,7 +52,7 @@
test
-
+
2.17.1
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
index 466291650c..c9bc120e4d 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml
@@ -52,7 +52,7 @@
test
-
+
2.17.1
diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
index 27afc3eb69..76d899447f 100644
--- a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
+++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml
@@ -60,8 +60,8 @@
test
-
-
+
+
2.17.1
diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
index 4727859ea2..5df22c78c8 100644
--- a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
+++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml
@@ -13,7 +13,7 @@
spring-cloud-zuul
0.0.1-SNAPSHOT
-
+
diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml
index 6f20d949b0..37b67beec4 100644
--- a/spring-ejb/ejb-beans/pom.xml
+++ b/spring-ejb/ejb-beans/pom.xml
@@ -38,7 +38,6 @@
tomee-embedded
${tomee-embedded.version}
-
org.springframework
spring-context
diff --git a/spring-reactive/pom.xml b/spring-reactive/pom.xml
index d31ee04d82..d755c03ae0 100644
--- a/spring-reactive/pom.xml
+++ b/spring-reactive/pom.xml
@@ -1,8 +1,9 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
+ spring-reactive
com.baeldung
@@ -11,8 +12,6 @@
../parent-boot-2
- spring-reactive
-
org.springframework.boot
diff --git a/spring-security-modules/spring-5-security-oauth/pom.xml b/spring-security-modules/spring-5-security-oauth/pom.xml
index 706cdb3082..8449b01ec0 100644
--- a/spring-security-modules/spring-5-security-oauth/pom.xml
+++ b/spring-security-modules/spring-5-security-oauth/pom.xml
@@ -15,8 +15,8 @@
0.0.1-SNAPSHOT
../../parent-boot-2
-
-
+
+
org.apache.logging.log4j
@@ -27,7 +27,6 @@
-
@@ -85,7 +84,7 @@
is available -->
2.5.2
com.baeldung.oauth2.SpringOAuthApplication
- 2.17.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-legacy-oidc/pom.xml b/spring-security-modules/spring-security-legacy-oidc/pom.xml
index 9dd898f9dd..e98486b0ff 100644
--- a/spring-security-modules/spring-security-legacy-oidc/pom.xml
+++ b/spring-security-modules/spring-security-legacy-oidc/pom.xml
@@ -14,8 +14,8 @@
0.0.1-SNAPSHOT
../../parent-boot-2
-
-
+
+
org.apache.logging.log4j
@@ -62,7 +62,7 @@
1.0.9.RELEASE
0.3.0
2.4.7
- 2.17.1
+ 2.17.1
\ No newline at end of file
diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml
index 3f6001686d..18cdd0ae5c 100644
--- a/spring-security-modules/spring-security-web-boot-1/pom.xml
+++ b/spring-security-modules/spring-security-web-boot-1/pom.xml
@@ -179,7 +179,6 @@
-
entryPoints
diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml
index 5f2a455294..59fcf9949f 100644
--- a/spring-security-modules/spring-security-web-boot-3/pom.xml
+++ b/spring-security-modules/spring-security-web-boot-3/pom.xml
@@ -1,5 +1,7 @@
-
+
4.0.0
spring-security-web-boot-3
0.0.1-SNAPSHOT
@@ -63,5 +65,4 @@
3.6.0
-
\ No newline at end of file
diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml
index d66d9cb35a..a5c23c1649 100644
--- a/spring-web-modules/pom.xml
+++ b/spring-web-modules/pom.xml
@@ -50,4 +50,4 @@
spring-web-url
-
+
\ No newline at end of file
diff --git a/spring-web-modules/spring-mvc-basics-5/pom.xml b/spring-web-modules/spring-mvc-basics-5/pom.xml
index 3b64f15c4b..5e8cd1b44e 100644
--- a/spring-web-modules/spring-mvc-basics-5/pom.xml
+++ b/spring-web-modules/spring-mvc-basics-5/pom.xml
@@ -41,7 +41,7 @@
- spring-mvc-basics
+ spring-mvc-basics-5
org.springframework.boot
diff --git a/testing-modules/cucumber/pom.xml b/testing-modules/cucumber/pom.xml
index 531b16ddec..ffa5c0d250 100644
--- a/testing-modules/cucumber/pom.xml
+++ b/testing-modules/cucumber/pom.xml
@@ -12,7 +12,6 @@
parent-boot-2
0.0.1-SNAPSHOT
../../parent-boot-2
-
diff --git a/testing-modules/testng_command_line/pom.xml b/testing-modules/testng_command_line/pom.xml
index 4c3af7621c..0f3201a432 100644
--- a/testing-modules/testng_command_line/pom.xml
+++ b/testing-modules/testng_command_line/pom.xml
@@ -3,10 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
com.baeldung.testing_modules
testng_command_line
1.0.0-SNAPSHOT
+
com.baeldung
testing-modules
@@ -78,7 +78,6 @@
-
ExecuteTestSuite
@@ -101,6 +100,7 @@
+
UTF-8
1.8
@@ -112,4 +112,5 @@
3.8.0
2.22.1
-
+
+
\ No newline at end of file
From d2cea2ef063383ec62b3cb85f496c1154a63fd6d Mon Sep 17 00:00:00 2001
From: sampadawagde
Date: Sun, 13 Mar 2022 14:53:36 +0530
Subject: [PATCH 233/235] resolve conflicts
---
spring-security-modules/spring-security-web-boot-3/pom.xml | 5 ++---
testing-modules/testng_command_line/pom.xml | 7 +++----
2 files changed, 5 insertions(+), 7 deletions(-)
diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml
index 59fcf9949f..5f2a455294 100644
--- a/spring-security-modules/spring-security-web-boot-3/pom.xml
+++ b/spring-security-modules/spring-security-web-boot-3/pom.xml
@@ -1,7 +1,5 @@
-
+
4.0.0
spring-security-web-boot-3
0.0.1-SNAPSHOT
@@ -65,4 +63,5 @@
3.6.0
+
\ No newline at end of file
diff --git a/testing-modules/testng_command_line/pom.xml b/testing-modules/testng_command_line/pom.xml
index 0f3201a432..4c3af7621c 100644
--- a/testing-modules/testng_command_line/pom.xml
+++ b/testing-modules/testng_command_line/pom.xml
@@ -3,10 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
+
com.baeldung.testing_modules
testng_command_line
1.0.0-SNAPSHOT
-
com.baeldung
testing-modules
@@ -78,6 +78,7 @@
+
ExecuteTestSuite
@@ -100,7 +101,6 @@
-
UTF-8
1.8
@@ -112,5 +112,4 @@
3.8.0
2.22.1
-
-
\ No newline at end of file
+
From aa35c80c419bb4c4829583e0504a4d007d594a84 Mon Sep 17 00:00:00 2001
From: Ralf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com>
Date: Mon, 14 Mar 2022 20:23:35 +0100
Subject: [PATCH 234/235] BAEL-5457: Add Hikari configuration to datasource
(#11923)
---
.../todos/TodoDatasourceConfiguration.java | 1 +
.../main/resources/application-multipledatasources.properties | 1 +
2 files changed, 2 insertions(+)
diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
index b6a16eb7e4..c599c26d01 100644
--- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
+++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/TodoDatasourceConfiguration.java
@@ -19,6 +19,7 @@ public class TodoDatasourceConfiguration {
@Bean
@Primary
+ @ConfigurationProperties("spring.datasource.todos.hikari")
public DataSource todosDataSource() {
return todosDataSourceProperties()
.initializeDataSourceBuilder()
diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties b/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
index 0f2b643498..d9f859ea40 100644
--- a/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
+++ b/persistence-modules/spring-data-jdbc/src/main/resources/application-multipledatasources.properties
@@ -3,6 +3,7 @@ spring.datasource.todos.url=jdbc:h2:mem:todos
spring.datasource.todos.username=sa
spring.datasource.todos.password=null
spring.datasource.todos.driverClassName=org.h2.Driver
+spring.datasource.todos.hikari.connectionTimeout=44444
spring.datasource.topics.url=jdbc:h2:mem:topics
spring.datasource.topics.username=sa
spring.datasource.topics.password=null
From f74056e1d78537e1eb1bceadefa23d9101a4deec Mon Sep 17 00:00:00 2001
From: Kapil Khandelwal
Date: Tue, 15 Mar 2022 01:04:49 +0530
Subject: [PATCH 235/235] BAEL-5371: Create a new module java-mongodb-2 in
persistence-modules and add push and set operations in Same MongoDB Update
(#11924)
---
persistence-modules/java-mongodb-2/.gitignore | 5 ++
persistence-modules/java-mongodb-2/README.md | 5 ++
persistence-modules/java-mongodb-2/pom.xml | 53 ++++++++++++++++++
.../mongo/update/PustSetOperation.java | 54 +++++++++++++++++++
.../src/main/resources/logback.xml | 13 +++++
.../update/PustSetOperationLiveTest.java | 53 ++++++++++++++++++
persistence-modules/pom.xml | 3 +-
7 files changed, 185 insertions(+), 1 deletion(-)
create mode 100644 persistence-modules/java-mongodb-2/.gitignore
create mode 100644 persistence-modules/java-mongodb-2/README.md
create mode 100644 persistence-modules/java-mongodb-2/pom.xml
create mode 100644 persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/PustSetOperation.java
create mode 100644 persistence-modules/java-mongodb-2/src/main/resources/logback.xml
create mode 100644 persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/PustSetOperationLiveTest.java
diff --git a/persistence-modules/java-mongodb-2/.gitignore b/persistence-modules/java-mongodb-2/.gitignore
new file mode 100644
index 0000000000..79ba317cb5
--- /dev/null
+++ b/persistence-modules/java-mongodb-2/.gitignore
@@ -0,0 +1,5 @@
+.classpath
+.project
+.settings
+target
+build
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb-2/README.md b/persistence-modules/java-mongodb-2/README.md
new file mode 100644
index 0000000000..1b49e11499
--- /dev/null
+++ b/persistence-modules/java-mongodb-2/README.md
@@ -0,0 +1,5 @@
+## MongoDB
+
+This module contains articles about MongoDB in Java.
+
+
diff --git a/persistence-modules/java-mongodb-2/pom.xml b/persistence-modules/java-mongodb-2/pom.xml
new file mode 100644
index 0000000000..ffc8da0b64
--- /dev/null
+++ b/persistence-modules/java-mongodb-2/pom.xml
@@ -0,0 +1,53 @@
+
+
+ 4.0.0
+ java-mongodb-2
+ 1.0-SNAPSHOT
+ java-mongodb-2
+
+
+ com.baeldung
+ persistence-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ de.flapdoodle.embedmongo
+ de.flapdoodle.embedmongo
+ ${flapdoodle.version}
+ test
+
+
+ org.mongodb
+ mongo-java-driver
+ ${mongo.version}
+
+
+ dev.morphia.morphia
+ core
+ ${morphia.version}
+
+
+ org.testcontainers
+ mongodb
+ 1.16.3
+ test
+
+
+ org.testcontainers
+ junit-jupiter
+ 1.16.3
+ test
+
+
+
+
+ 3.12.1
+ 1.11
+ 1.5.3
+
+
+
diff --git a/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/PustSetOperation.java b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/PustSetOperation.java
new file mode 100644
index 0000000000..bb7eca4f23
--- /dev/null
+++ b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/PustSetOperation.java
@@ -0,0 +1,54 @@
+package com.baeldung.mongo.update;
+
+import org.bson.Document;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class PustSetOperation {
+
+ private static MongoClient mongoClient;
+
+ private static String testCollectionName;
+ private static String databaseName;
+
+ public static void setUp() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ }
+ databaseName = "baeldung";
+ testCollectionName = "marks";
+ }
+
+ public static void pushSetSolution() {
+
+ MongoDatabase database = mongoClient.getDatabase(databaseName);
+ MongoCollection collection = database.getCollection(testCollectionName);
+
+ Document subjectData = new Document().append("subjectId", 126)
+ .append("subjectName", "Java Programming")
+ .append("marks", 70);
+ UpdateResult updateQueryResult = collection.updateOne(Filters.eq("studentId", 1023), Updates.combine(Updates.set("totalMarks", 170), Updates.push("subjectDetails", subjectData)));
+ System.out.println("updateQueryResult:- " + updateQueryResult);
+
+ }
+
+ public static void main(String args[]) {
+
+ //
+ // Connect to cluster (default is localhost:27017)
+ //
+ setUp();
+
+ //
+ // Push document into the array and set a field
+ //
+ pushSetSolution();
+
+ }
+}
+
diff --git a/persistence-modules/java-mongodb-2/src/main/resources/logback.xml b/persistence-modules/java-mongodb-2/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/persistence-modules/java-mongodb-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/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/PustSetOperationLiveTest.java b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/PustSetOperationLiveTest.java
new file mode 100644
index 0000000000..6279747429
--- /dev/null
+++ b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/PustSetOperationLiveTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.update;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+import org.bson.Document;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.Filters;
+import com.mongodb.client.model.Updates;
+import com.mongodb.client.result.UpdateResult;
+
+public class PustSetOperationLiveTest {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase db;
+ private static MongoCollection collection;
+
+ @BeforeClass
+ public static void setup() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+ db = mongoClient.getDatabase("baeldung");
+ collection = db.getCollection("marks");
+
+ collection.insertOne(Document.parse("{\n" + " \"studentId\": 1023,\n" + " \"studentName\":\"James Broad\",\n" + " \"joiningYear\":\"2018\",\n" + " \"totalMarks\":100,\n" + " \"subjectDetails\":[\n"
+ + " {\n" + " \"subjectId\":123,\n" + " \"subjectName\":\"Operating Systems Concepts\",\n" + " \"marks\":4,\n" + " },\n" + " {\n"
+ + " \"subjectId\":124,\n" + " \"subjectName\":\"Numerical Analysis\",\n" + " \"marks\":60\n" + " }\n" + " ]\n" + " }"));
+
+ }
+ }
+
+ @Test
+ public void givenMarksCollection_whenPushSetOperation_thenCheckingForDocument() {
+
+ Document subjectData = new Document().append("subjectId", 126)
+ .append("subjectName", "Java Programming")
+ .append("marks", 70);
+ UpdateResult updateQueryResult = collection.updateOne(Filters.eq("studentId", 1023), Updates.combine(Updates.set("totalMarks", 170), Updates.push("subjectDetails", subjectData)));
+
+ Document studentDetail = collection.find(Filters.eq("studentId", 1023))
+ .first();
+ assertNotNull(studentDetail);
+ assertFalse(studentDetail.isEmpty());
+
+ }
+
+}
+
diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml
index 64a9519a8b..f8e3cb05e8 100644
--- a/persistence-modules/pom.xml
+++ b/persistence-modules/pom.xml
@@ -43,6 +43,7 @@
java-jpa-2
java-jpa-3
java-mongodb
+ java-mongodb-2
jnosql
jooq
jpa-hibernate-cascade-type
@@ -104,4 +105,4 @@
42.2.20
-
\ No newline at end of file
+